Compare commits

..

58 Commits

Author SHA1 Message Date
Xie Qiming
ba7995270a Merge pull request #263 from ftu62738-creator/workstation_dev_YB_260410
feat: cherry-pick dev branch updates + 新增东华电化学/SSE自动合成设备驱动
2026-05-22 15:22:56 +08:00
Andy6M
9165c9f421 feat: 新增东华电化学设备驱动、SSE自动合成设备,优化扣电组装条码匹配逻辑
- 新增 donghua_ec 电化学工作站驱动及相关 DLL 依赖
- 新增 sse_auto_synthesis 自动合成设备驱动及注册配置
- 优化 coin_cell_assembly.py 电解液瓶条码精确匹配方案(按条码反查配方,降级按位置索引兜底)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 15:14:54 +08:00
Xuwznln
e5462f748e support notebook id 2026-05-22 15:11:49 +08:00
Xuwznln
1abbcccb53 new build fix 2026-05-22 15:11:49 +08:00
Xuwznln
45337271ef v0.11.2
(cherry picked from commit bcb1790897)
2026-05-22 15:11:49 +08:00
Xuwznln
ec606bac3b env installation fix 2026-05-22 15:11:49 +08:00
Xuwznln
92828ea44a fix pack install 2 2026-05-22 15:11:49 +08:00
Xuwznln
63faa15bf2 fix pip install & git install failed 2026-05-22 15:11:49 +08:00
Xuwznln
78bc393847 fix pack build 1 2026-05-22 15:11:48 +08:00
Junhan Chang
575803d53d Update SKILL.md 2026-05-22 15:11:48 +08:00
Junhan Chang
5767a0d55f Update Skills 2026-05-22 15:11:48 +08:00
Xuwznln
14d82fe559 Update registry for all param desc 2026-05-22 15:11:48 +08:00
Xuwznln
14081acd59 Support display_name & desc in new registry system
(cherry picked from commit f71ea2a258)
2026-05-22 15:10:37 +08:00
Xuwznln
f5108104cb upgrade to 0.11.1 2026-05-22 15:10:37 +08:00
Xuwznln
9c256238af use gitee to install pylabrobot
fix virtual import
2026-05-22 15:10:37 +08:00
Xuwznln
742a96e4c0 v0.11.0
(cherry picked from commit 67a74172dc)
2026-05-22 15:10:37 +08:00
Andy6M
865dd87556 更新扣电组装驱动 coin_cell_assembly.py
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 14:52:00 +08:00
Andy6M
86f1640efb 更新工作站驱动,清理旧版模板文件
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 12:19:25 +08:00
Andy6M
99ee27bfc2 Revert "Revert "fix(neware): add coin_cell_code input handle to battery_transfer_confirm""
This reverts commit 201b1064d7.
2026-04-22 18:18:24 +08:00
Andy6M
e8f54d50f9 fix(neware): remove output_dir from submit_auto_export_excel input handles
Made-with: Cursor
2026-04-22 18:13:45 +08:00
Andy6M
201b1064d7 Revert "fix(neware): add coin_cell_code input handle to battery_transfer_confirm"
This reverts commit 2ebe35e70e.
2026-04-22 18:13:32 +08:00
Andy6M
2ebe35e70e fix(neware): add coin_cell_code input handle to battery_transfer_confirm
Made-with: Cursor
2026-04-22 18:06:37 +08:00
Andy6M
717f236332 feat(neware): submit_auto_export_excel add manual backup path and electrolyte_code
- Add output_dir param, backup dir derived from user input (xml_dir/backup_dir auto-created)
- Add electrolyte_code param, backup file name format: coin_cell_code-electrolyte_code-devid-subdevid-chlid
- manual_confirm return value adds electrolyte_code field for downstream passthrough
- YAML: manual_confirm output handles add electrolyte_code
- YAML: submit_auto_export_excel goal/schema/goal_default/handles add output_dir and electrolyte_code
- YAML: battery_transfer_confirm output changed to empty list

Made-with: Cursor
2026-04-22 17:29:28 +08:00
Xie Qiming
79c0815b70 fix(neware): 修复 submit_auto_export_excel 因 resource=[] 导致 0 下发 + filetype kwarg
问题:
- 日志中 submit_auto_export_excel 收到 resource=[](工作流本身不传成品电池资源,
  电池由人工搬运),原代码 n = len(resource) = 0 → 整个循环跳过 →
  "共 0 颗电池,成功下发 0 颗"。
- neware_driver.start_test 原来不接收 filetype kwarg,导致 TypeError 阻塞下发。

修复:
1. submit_auto_export_excel 改为由 mount_resource 驱动循环长度:
   - 新签名以 mount_resource 为主,resource/pole_weight/coin_cell_code 均可选
   - 新增 coin_cell_code 入参,coin_id 优先级 coin_cell_code > resource.name > fallback
   - n==0 时提前返回并给出明确错误信息
2. manual_confirm 的返回值与 YAML handles/output 新增 coin_cell_code
   (从已解包的 assembly_data 直接取)
3. submit_auto_export_excel YAML goal/schema/goal_default/handles.input
   新增 coin_cell_code;required 中移除 resource(不再强制)
4. neware_driver.build_start_command / start_test 增加 filetype:int=1 参数,
   动态嵌入 XML backup 配置,消除 TypeError

Made-with: Cursor
2026-04-22 16:24:35 +08:00
Xie Qiming
f431d61d85 Fix neware test dispatch and manual_confirm CSV archival
- neware_driver: default backup filetype="1" so Neware BTS produces Excel
  backups out of the box (matches submit_*_export_excel semantics).
- submit_auto_export_excel: pass filetype=1 to align with function name
  and the newly default Excel backup.
- manual_confirm: prefix Channel_Name with a single quote when writing
  the integrated CSV so Excel keeps it as text (e.g. "6-10-2") instead
  of auto-coercing to a date (e.g. "2006/10/2"). The on-disk value is
  archival only and submit_auto_export_excel never reads it, so the
  live workflow is unaffected either way.
- neware yaml: declare explicit item properties for manual_confirm's
  formulations and assembly_data arrays so the orchestrator schema
  projection keeps the 7/9 upstream fields intact.

Made-with: Cursor
2026-04-22 15:21:15 +08:00
Xie Qiming
3af86a07f2 Trim manual_confirm outputs and fix resource uuid lookup
- neware manual_confirm: drop formulations/assembly_data from result and output handles (they only feed internal CSV export and should not be passed downstream); return dict no longer carries those two keys
- base_device_node.loop_find_with_uuid consumer: iterate all figured_resources instead of breaking after first attempt; raise explicit error when uuid cannot be resolved

Made-with: Cursor
2026-04-22 11:18:45 +08:00
Xie Qiming
d1713fcca1 Wire bioyond/coin-cell/neware param passing and add manual-confirm CSV export
- coin_cell_assembly: align battery_info to 9 fields (Time/open_circuit_voltage/pole_weight/assembly_time/assembly_pressure/electrolyte_volume/data_coin_type/electrolyte_code/coin_cell_code); expose assembly_data single array; rename CSV column coin_num -> data_coin_type
- coin_cell_workstation.yaml: add assembly_data_output handle for auto-func_sendbottle_allpack_multi
- neware manual_confirm: accept formulations + assembly_data + csv_export_dir, unpack to parallel lists, export merged CSV to {csv_export_dir}/{date}/date_{date}.csv, output pole_weight for downstream
- neware transfer -> battery_transfer_confirm with manual_confirm node_type, timeout_seconds, assignee_user_ids
- neware test -> submit_auto_export_excel, accept pole_weight input; relabel battery_system as xml工步

Made-with: Cursor
2026-04-21 20:01:49 +08:00
Xie Qiming
52b460466d Update neware battery test system driver and registry
- Expand neware_battery_test_system.py with new actions and logic
- Update generate_xml_content.py with additional XML generation support
- Extend neware_battery_test_system.yaml registry with new action schemas
- Update OSS upload READMEs and device.json
- Add electrode_sheet.py resource fields

Made-with: Cursor
2026-04-21 17:30:56 +08:00
Xuwznln
7efccbc688 update workbench example 2026-04-21 12:03:25 +08:00
Xuwznln
dc1de44b19 update aksk desc 2026-04-21 12:03:12 +08:00
Xuwznln
4581ee1eeb print res query logs 2026-04-21 12:03:01 +08:00
Xuwznln
620cb8435f Fix skills exec error with action type 2026-04-21 12:02:40 +08:00
Xuwznln
83565038cb Fix skills exec error with action type 2026-04-21 12:01:51 +08:00
Xuwznln
01d281189a Update Skills 2026-04-21 11:58:28 +08:00
Xuwznln
db22156d77 Update Skills addr 2026-04-21 11:58:16 +08:00
Xuwznln
20342c6484 Change uni-lab. to leap-lab.
Support unit in pylabrobot
2026-04-21 11:58:02 +08:00
Xuwznln
008c355754 Support async func. 2026-04-21 11:57:48 +08:00
Xuwznln
0895252bc1 change to leap-lab backend. Support feedback interval. Reduce cocurrent lags. 2026-04-21 11:56:13 +08:00
Andy6M
3e43359460 fix(bioyond): fix order name type and prep bottle max volumes
bioyond_cell: Ensure order_name is cast to str and fix mix_time handling for single int/float values. YB_bottles: Fix max_volume capacity for 15mL and 60mL prep bottles to match their names.
2026-04-16 21:17:22 +08:00
Andy6M
73add2dc06 feat: implement electrolyte CSV export and barcode tracking
- add CSV export for order data in bioyond_cell
- extract prep and vial bottles from order_finish report
- update bioyond_cell registry with csv_export_path
- update coin_cell_assembly to export new bottle barcodes and mass ratios
- add 260415csv_export_walkthrough.md
2026-04-15 12:07:01 +08:00
Andy6M
dd21d93151 chore: remove local-only date CSV files (not for upstream) 2026-04-10 18:06:58 +08:00
Andy6M
e11c3533c7 Merge origin/dev into backup/local-0.10.18-20260324 2026-04-09 18:21:14 +08:00
Xuwznln
58997f0654 fix create_resource_with_slot 2026-04-09 17:34:25 +08:00
Xuwznln
fbfc3e30fb update unilabos_formulation & batch-submit-exp 2026-04-09 16:40:31 +08:00
Andy6M
ed952e8a44 feat: 更新Neware电池测试系统驱动及电芯组装工作站相关文件
- 更新 neware_battery_test_system 驱动及设备配置
- 新增 generate_xml_content.py 工具脚本
- 更新 bioyond_cell_workstation 工作站实现
- 更新 coin_cell_assembly 扣式电池组装逻辑
- 更新相关注册表 YAML 配置:neware_battery_test_system、coin_cell_workstation、bioyond_cell
2026-04-09 14:16:49 +08:00
Xuwznln
1d1c1367df scale multi exec thread up to 48 2026-04-09 14:15:38 +08:00
Xuwznln
c91b600e90 update handle creation api 2026-04-02 22:53:31 +08:00
Xuwznln
49b3c850f9 fit cocurrent gap 2026-04-02 16:01:23 +08:00
Xuwznln
25c94af755 add running status debounce 2026-04-01 16:01:22 +08:00
Xuwznln
861a012747 allow non @topic_config support 2026-03-31 13:15:06 +08:00
Andy6M
467f0b1115 feat: update coin cell assembly, bioyond cell workstation, and resource configs 2026-03-25 23:31:06 +08:00
Xuwznln
ee63e95f50 update skill 2026-03-25 23:20:13 +08:00
Andy6M
91928a87ac Merge remote-tracking branch 'origin/dev' into backup/local-0.10.18-20260324 2026-03-24 12:26:03 +08:00
Junhan Chang
d7850b050b add create_orders_foumulation and extract common code 2026-03-24 11:15:54 +08:00
Junhan Chang
dff70bd72b add formulation action 2026-03-24 11:12:05 +08:00
Junhan Chang
03e3719b18 add ai conventions 2026-03-24 11:08:49 +08:00
Andy6M
41a018febc chore: 鏈湴淇敼瀛樻。 - 0.10.18 鍩虹鐗堟湰澶囦唤 (2026-03-24)
Made-with: Cursor
2026-03-24 10:54:59 +08:00
Andy6M
7505e024f3 fix: 物料系统标准化重构 + 多轮运行期 Bug 修复 (2026-03-12)
- MagazineHolder: klasses=None,解耦极片子节点初始化
- Magazine: 重写 serialize/deserialize,截断旧极片脏数据
- bottle_carriers: 移除 YIHUA_Electrolyte_12VialCarrier 初始化填瓶
- decks.py: BIOYOND_YB_Deck→BioyondElectrolyteDeck,移除 setup 参数
- YB_YH_materials.py: CoincellDeck→YihuaCoinCellDeck,新增 electrolyte_buffer 槽位
- resource_tracker.py: Container 状态键预填 + 重复 UUID 自动修复 + 树级名称去重
- itemized_carrier.py: XY 近似坐标匹配,修复 Z 偏移问题
- bioyond_cell_workstation.py: 跨站转运改用真实资源 + 类型映射双模式查找
- station.py: sync_to_external 属性访问路径修复
- coin_cell_assembly.py: 新增 10 个 Modbus 余量属性
- CSV/JSON/YAML 配置同步更新(类名重命名 + 移除 setup)
- 新增 changelog_2026-03-12.md
2026-03-19 00:41:26 +08:00
816 changed files with 122142 additions and 8088 deletions

View File

@@ -3,7 +3,7 @@
package:
name: unilabos
version: 0.10.19
version: 0.11.2
source:
path: ../../unilabos
@@ -54,7 +54,7 @@ requirements:
- pymodbus
- matplotlib
- pylibftdi
- uni-lab::unilabos-env ==0.10.19
- uni-lab::unilabos-env ==0.11.2
about:
repository: https://github.com/deepmodeling/Uni-Lab-OS

View File

@@ -2,7 +2,7 @@
package:
name: unilabos-env
version: 0.10.19
version: 0.11.2
build:
noarch: generic

View File

@@ -3,7 +3,7 @@
package:
name: unilabos-full
version: 0.10.19
version: 0.11.2
build:
noarch: generic
@@ -11,7 +11,7 @@ build:
requirements:
run:
# Base unilabos package (includes unilabos-env)
- uni-lab::unilabos ==0.10.19
- uni-lab::unilabos ==0.11.2
# Documentation tools
- sphinx
- sphinx_rtd_theme

View File

@@ -71,6 +71,22 @@ from unilabos.registry.decorators import action
- `_` 开头的方法 → 不扫描
- `@not_action` 标记的方法 → 排除
### 参数文档 → JSON Schema 元数据
`__init__` 和 action 方法 docstring 的 `Args:` 小节里,使用以下格式生成入参 schema 的显示信息:
```python
"""
Args:
param[显示名称]: 参数说明,会写入 JSON Schema 的 description。
"""
```
- `param[显示名称]` 的显示名称会写入 goal property 的 `title`
- `:` 后面的说明会写入 goal property 的 `description`
- 如果只写 `param: 参数说明``title` 会兜底为字段名,`description` 使用参数说明。
- 如果没有写参数文档,生成器也会兜底补齐 `title=<字段名>``description=""`,但新设备应优先写清楚显示名和说明。
### @topic_config — 状态属性配置
```python
@@ -105,13 +121,27 @@ import logging
from typing import Any, Dict, Optional
from unilabos.ros.nodes.base_device_node import BaseROS2DeviceNode
from unilabos.registry.decorators import device, action, topic_config, not_action
from unilabos.registry.decorators import action, device, not_action, topic_config
@device(id="my_device", category=["my_category"], description="设备描述")
@device(
id="my_device",
category=["my_category"],
description="设备描述",
display_name="设备显示名",
)
class MyDevice:
"""设备类说明。"""
_ros_node: BaseROS2DeviceNode
def __init__(self, device_id: Optional[str] = None, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
初始化设备。
Args:
device_id[设备ID]: 设备实例 ID默认使用 my_device。
config[设备配置]: 设备启动配置。
"""
self.device_id = device_id or "my_device"
self.config = config or {}
self.logger = logging.getLogger(f"MyDevice.{self.device_id}")
@@ -133,7 +163,13 @@ class MyDevice:
@action(description="执行操作")
def my_action(self, param: float = 0.0, name: str = "") -> Dict[str, Any]:
"""带 @action 装饰器 → 注册为 'my_action' 动作"""
"""
带 @action 装饰器 → 注册为 'my_action' 动作。
Args:
param[操作数值]: 操作使用的数值参数。
name[操作名称]: 操作名称或备注。
"""
return {"success": True}
def get_info(self) -> Dict[str, Any]:

View File

@@ -27,14 +27,15 @@ python -c "import base64,sys; print('Authorization: Lab ' + base64.b64encode(f'{
### 2. --addr → BASE URL
| `--addr` 值 | BASE |
|-------------|------|
| `test` | `https://uni-lab.test.bohrium.com` |
| `uat` | `https://uni-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://uni-lab.bohrium.com` |
| `--addr` | BASE |
| ------------ | ----------------------------------- |
| `test` | `https://leap-lab.test.bohrium.com` |
| `uat` | `https://leap-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://leap-lab.bohrium.com` |
确认后设置:
```bash
BASE="<根据 addr 确定的 URL>"
AUTH="Authorization: Lab <gen_auth.py 输出的 token>"
@@ -65,7 +66,7 @@ curl -s -X GET "$BASE/api/v1/edge/lab/info" -H "$AUTH"
返回:
```json
{"code": 0, "data": {"uuid": "xxx", "name": "实验室名称"}}
{ "code": 0, "data": { "uuid": "xxx", "name": "实验室名称" } }
```
记住 `data.uuid``lab_uuid`
@@ -90,6 +91,7 @@ curl -s -X POST "$BASE/api/v1/lab/reagent" \
```
返回成功时包含试剂 UUID
```json
{"code": 0, "data": {"uuid": "xxx", ...}}
```
@@ -98,28 +100,28 @@ curl -s -X POST "$BASE/api/v1/lab/reagent" \
## 试剂字段说明
| 字段 | 类型 | 必填 | 说明 | 示例 |
|------|------|------|------|------|
| `lab_uuid` | string | 是 | 实验室 UUID从 API #1 获取) | `"8511c672-..."` |
| `cas` | string | 是 | CAS 注册号 | `"7732-18-3"` |
| `name` | string | 是 | 试剂中文/英文名称 | `"水"` |
| `molecular_formula` | string | 是 | 分子式 | `"H2O"` |
| `smiles` | string | 是 | SMILES 表示 | `"O"` |
| `stock_in_quantity` | number | 是 | 入库数量 | `10` |
| `unit` | string | 是 | 单位(字符串,见下表) | `"mL"` |
| `supplier` | string | 否 | 供应商名称 | `"国药集团"` |
| `production_date` | string | 否 | 生产日期ISO 8601 | `"2025-11-18T00:00:00Z"` |
| `expiry_date` | string | 否 | 过期日期ISO 8601 | `"2026-11-18T00:00:00Z"` |
| 字段 | 类型 | 必填 | 说明 | 示例 |
| ------------------- | ------ | ---- | ----------------------------- | ------------------------ |
| `lab_uuid` | string | 是 | 实验室 UUID从 API #1 获取) | `"8511c672-..."` |
| `cas` | string | 是 | CAS 注册号 | `"7732-18-3"` |
| `name` | string | 是 | 试剂中文/英文名称 | `"水"` |
| `molecular_formula` | string | 是 | 分子式 | `"H2O"` |
| `smiles` | string | 是 | SMILES 表示 | `"O"` |
| `stock_in_quantity` | number | 是 | 入库数量 | `10` |
| `unit` | string | 是 | 单位(字符串,见下表) | `"mL"` |
| `supplier` | string | 否 | 供应商名称 | `"国药集团"` |
| `production_date` | string | 否 | 生产日期ISO 8601 | `"2025-11-18T00:00:00Z"` |
| `expiry_date` | string | 否 | 过期日期ISO 8601 | `"2026-11-18T00:00:00Z"` |
### unit 单位值
| 值 | 单位 |
|------|------|
| 值 | 单位 |
| ------ | ---- |
| `"mL"` | 毫升 |
| `"L"` | 升 |
| `"g"` | 克 |
| `"L"` | 升 |
| `"g"` | 克 |
| `"kg"` | 千克 |
| `"瓶"` | 瓶 |
| `"瓶"` | 瓶 |
> 根据试剂状态选择:液体用 `"mL"` / `"L"`,固体用 `"g"` / `"kg"`。
@@ -133,8 +135,22 @@ curl -s -X POST "$BASE/api/v1/lab/reagent" \
```json
[
{"cas": "7732-18-3", "name": "水", "molecular_formula": "H2O", "smiles": "O", "stock_in_quantity": 10, "unit": "mL"},
{"cas": "64-17-5", "name": "乙醇", "molecular_formula": "C2H6O", "smiles": "CCO", "stock_in_quantity": 5, "unit": "L"}
{
"cas": "7732-18-3",
"name": "水",
"molecular_formula": "H2O",
"smiles": "O",
"stock_in_quantity": 10,
"unit": "mL"
},
{
"cas": "64-17-5",
"name": "乙醇",
"molecular_formula": "C2H6O",
"smiles": "CCO",
"stock_in_quantity": 5,
"unit": "L"
}
]
```
@@ -160,9 +176,20 @@ cas,name,molecular_formula,smiles,stock_in_quantity,unit,supplier,production_dat
7732-18-3,水,H2O,O,10,mL,农夫山泉,2025-11-18T00:00:00Z,2026-11-18T00:00:00Z
```
### 日期格式规则(重要)
所有日期字段(`production_date``expiry_date`**必须**使用 ISO 8601 完整格式:`YYYY-MM-DDTHH:MM:SSZ`
- 用户输入 `2025-03-01` → 转换为 `"2025-03-01T00:00:00Z"`
- 用户输入 `2025/9/1` → 转换为 `"2025-09-01T00:00:00Z"`
- 用户未提供日期 → 使用当天日期 + `T00:00:00Z`,有效期默认 +1 年
**禁止**发送不带时间部分的日期字符串(如 `"2025-03-01"`API 会拒绝。
### 执行与汇报
每次 API 调用后:
1. 检查返回 `code`0 = 成功)
2. 记录成功/失败数量
3. 全部完成后汇总:「共录入 N 条试剂,成功 X 条,失败 Y 条」
@@ -172,28 +199,29 @@ cas,name,molecular_formula,smiles,stock_in_quantity,unit,supplier,production_dat
## 常见试剂速查表
| 名称 | CAS | 分子式 | SMILES |
|------|-----|--------|--------|
| 水 | 7732-18-3 | H2O | O |
| 乙醇 | 64-17-5 | C2H6O | CCO |
| 甲醇 | 67-56-1 | CH4O | CO |
| 丙酮 | 67-64-1 | C3H6O | CC(C)=O |
| 二甲基亚砜(DMSO) | 67-68-5 | C2H6OS | CS(C)=O |
| 乙酸乙酯 | 141-78-6 | C4H8O2 | CCOC(C)=O |
| 二氯甲烷 | 75-09-2 | CH2Cl2 | ClCCl |
| 四氢呋喃(THF) | 109-99-9 | C4H8O | C1CCOC1 |
| N,N-二甲基甲酰胺(DMF) | 68-12-2 | C3H7NO | CN(C)C=O |
| 氯仿 | 67-66-3 | CHCl3 | ClC(Cl)Cl |
| 乙腈 | 75-05-8 | C2H3N | CC#N |
| 甲苯 | 108-88-3 | C7H8 | Cc1ccccc1 |
| 正己烷 | 110-54-3 | C6H14 | CCCCCC |
| 异丙醇 | 67-63-0 | C3H8O | CC(C)O |
| 盐酸 | 7647-01-0 | HCl | Cl |
| 酸 | 7664-93-9 | H2SO4 | OS(O)(=O)=O |
| 氢氧化钠 | 1310-73-2 | NaOH | [Na]O |
| 碳酸钠 | 497-19-8 | Na2CO3 | [Na]OC([O-])=O.[Na+] |
| 氯化钠 | 7647-14-5 | NaCl | [Na]Cl |
| 乙二胺四乙酸(EDTA) | 60-00-4 | C10H16N2O8 | OC(=O)CN(CCN(CC(O)=O)CC(O)=O)CC(O)=O |
| 名称 | CAS | 分子式 | SMILES |
| --------------------- | --------- | ---------- | ------------------------------------ |
| 水 | 7732-18-3 | H2O | O |
| 乙醇 | 64-17-5 | C2H6O | CCO |
| 乙酸 | 64-19-7 | C2H4O2 | CC(O)=O |
| 甲醇 | 67-56-1 | CH4O | CO |
| 丙酮 | 67-64-1 | C3H6O | CC(C)=O |
| 二甲基亚砜(DMSO) | 67-68-5 | C2H6OS | CS(C)=O |
| 乙酸乙酯 | 141-78-6 | C4H8O2 | CCOC(C)=O |
| 二氯甲烷 | 75-09-2 | CH2Cl2 | ClCCl |
| 四氢呋喃(THF) | 109-99-9 | C4H8O | C1CCOC1 |
| N,N-二甲基甲酰胺(DMF) | 68-12-2 | C3H7NO | CN(C)C=O |
| 氯仿 | 67-66-3 | CHCl3 | ClC(Cl)Cl |
| 乙腈 | 75-05-8 | C2H3N | CC#N |
| 甲苯 | 108-88-3 | C7H8 | Cc1ccccc1 |
| 正己烷 | 110-54-3 | C6H14 | CCCCCC |
| 异丙醇 | 67-63-0 | C3H8O | CC(C)O |
| | 7647-01-0 | HCl | Cl |
| 硫酸 | 7664-93-9 | H2SO4 | OS(O)(=O)=O |
| 氢氧化钠 | 1310-73-2 | NaOH | [Na]O |
| 碳酸钠 | 497-19-8 | Na2CO3 | [Na]OC([O-])=O.[Na+] |
| 氯化钠 | 7647-14-5 | NaCl | [Na]Cl |
| 乙二胺四乙酸(EDTA) | 60-00-4 | C10H16N2O8 | OC(=O)CN(CCN(CC(O)=O)CC(O)=O)CC(O)=O |
> 此表仅供快速参考。对于不在表中的试剂agent 应根据化学知识推断或提示用户补充。

View File

@@ -1,11 +1,13 @@
---
name: batch-submit-experiment
description: Batch submit experiments (notebooks) to Uni-Lab platform — list workflows, generate node_params from registry schemas, submit multiple rounds. Use when the user wants to submit experiments, create notebooks, batch run workflows, or mentions 提交实验/批量实验/notebook/实验轮次.
description: Batch submit experiments (notebooks) to the Uni-Lab cloud platform (leap-lab) — list workflows, generate node_params from registry schemas, submit multiple rounds, check notebook status. Use when the user wants to submit experiments, create notebooks, batch run workflows, check experiment status, or mentions 提交实验/批量实验/notebook/实验轮次/实验状态.
---
# 批量提交实验指南
# Uni-Lab 批量提交实验指南
通过云端 API 批量提交实验notebook支持多轮实验参数配置。根据 workflow 模板详情和本地设备注册表自动生成 `node_params` 模板。
通过 Uni-Lab 云端 API 批量提交实验notebook支持多轮实验参数配置。根据 workflow 模板详情和本地设备注册表自动生成 `node_params` 模板。
> **重要**:本指南中的 `Authorization: Lab <token>` 是 **Uni-Lab 平台专用的认证方式**`Lab` 是 Uni-Lab 的 auth scheme 关键字,**不是** HTTP Basic 认证。请勿将其替换为 `Basic`。
## 前置条件(缺一不可)
@@ -18,25 +20,28 @@ description: Batch submit experiments (notebooks) to Uni-Lab platform — list w
生成 AUTH token任选一种方式
```bash
# 方式一Python 一行生成
# 方式一Python 一行生成注意scheme 是 "Lab" 不是 "Basic"
python -c "import base64,sys; print('Authorization: Lab ' + base64.b64encode(f'{sys.argv[1]}:{sys.argv[2]}'.encode()).decode())" <ak> <sk>
# 方式二:手动计算
# base64(ak:sk) → Authorization: Lab <token>
# ⚠️ 这里的 "Lab" 是 Uni-Lab 平台的 auth scheme绝对不能用 "Basic" 替代
```
### 2. --addr → BASE URL
| `--addr` 值 | BASE |
|-------------|------|
| `test` | `https://uni-lab.test.bohrium.com` |
| `uat` | `https://uni-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://uni-lab.bohrium.com` |
| `--addr` | BASE |
| ------------ | ----------------------------------- |
| `test` | `https://leap-lab.test.bohrium.com` |
| `uat` | `https://leap-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://leap-lab.bohrium.com` |
确认后设置:
```bash
BASE="<根据 addr 确定的 URL>"
# ⚠️ Auth scheme 必须是 "Lab"Uni-Lab 专用),不是 "Basic"
AUTH="Authorization: Lab <上面命令输出的 token>"
```
@@ -44,22 +49,23 @@ AUTH="Authorization: Lab <上面命令输出的 token>"
**批量提交实验时需要本地注册表来解析 workflow 节点的参数 schema。**
按优先级搜索
**必须先用 Glob 工具搜索文件**,不要直接猜测路径
```
<workspace 根目录>/unilabos_data/req_device_registry_upload.json
<workspace 根目录>/req_device_registry_upload.json
Glob: **/req_device_registry_upload.json
```
也可直接 Glob 搜索:`**/req_device_registry_upload.json`
常见位置(仅供参考,以 Glob 实际结果为准):
- `<workspace>/unilabos_data/req_device_registry_upload.json`
- `<workspace>/req_device_registry_upload.json`
找到后**检查文件修改时间**并告知用户。超过 1 天提醒用户是否需要重新启动 `unilab`
**如果文件不存在** → 告知用户先运行 `unilab` 启动命令,等注册表生成后再执行。可跳过此步,但将无法自动生成参数模板,需要用户手动填写 `param`
**如果 Glob 搜索无结果** → 告知用户先运行 `unilab` 启动命令,等注册表生成后再执行。可跳过此步,但将无法自动生成参数模板,需要用户手动填写 `param`
### 4. workflow_uuid目标工作流
用户需要提供要提交的 workflow UUID。如果用户不确定通过 API #2 列出可用 workflow 供选择。
用户需要提供要提交的 workflow UUID。如果用户不确定通过 API #3 列出可用 workflow 供选择。
**四项全部就绪后才可开始。**
@@ -68,8 +74,9 @@ AUTH="Authorization: Lab <上面命令输出的 token>"
在整个对话过程中agent 需要记住以下状态,避免重复询问用户:
- `lab_uuid` — 实验室 UUID首次通过 API #1 自动获取,**不需要问用户**
- `project_uuid` — 项目 UUID通过 API #2 列出项目列表,**让用户选择**
- `workflow_uuid` — 工作流 UUID用户提供或从列表选择
- `workflow_nodes` — workflow 中各 action 节点的 uuid、设备 ID、动作名从 API #3 获取)
- `workflow_nodes` — workflow 中各 action 节点的 uuid、设备 ID、动作名从 API #4 获取)
## 请求约定
@@ -92,12 +99,46 @@ curl -s -X GET "$BASE/api/v1/edge/lab/info" -H "$AUTH"
返回:
```json
{"code": 0, "data": {"uuid": "xxx", "name": "实验室名称"}}
{ "code": 0, "data": { "uuid": "xxx", "name": "实验室名称" } }
```
记住 `data.uuid``lab_uuid`
### 2. 列出可用 workflow
### 2. 列出实验室项目(让用户选择项目)
```bash
curl -s -X GET "$BASE/api/v1/lab/project/list?lab_uuid=$lab_uuid" -H "$AUTH"
```
返回:
```json
{
"code": 0,
"data": {
"items": [
{
"uuid": "1b3f249a-...",
"name": "bt",
"description": null,
"status": "active",
"created_at": "2026-04-09T14:31:28+08:00"
},
{
"uuid": "b6366243-...",
"name": "default",
"description": "默认项目",
"status": "active",
"created_at": "2026-03-26T11:13:36+08:00"
}
]
}
}
```
展示 `data.items[]` 中每个项目的 `name``uuid`,让用户选择。用户**必须**选择一个项目,记住 `project_uuid`(即选中项目的 `uuid`),后续创建 notebook 时需要提供。
### 3. 列出可用 workflow
```bash
curl -s -X GET "$BASE/api/v1/lab/workflow/workflows?page=1&page_size=20&lab_uuid=$lab_uuid" -H "$AUTH"
@@ -105,13 +146,14 @@ curl -s -X GET "$BASE/api/v1/lab/workflow/workflows?page=1&page_size=20&lab_uuid
返回 workflow 列表,展示给用户选择。列出每个 workflow 的 `uuid``name`
### 3. 获取 workflow 模板详情
### 4. 获取 workflow 模板详情
```bash
curl -s -X GET "$BASE/api/v1/lab/workflow/template/detail/$workflow_uuid" -H "$AUTH"
```
返回 workflow 的完整结构,包含所有 action 节点信息。需要从响应中提取:
- 每个 action 节点的 `node_uuid`
- 每个节点对应的设备 ID`resource_template_name`
- 每个节点的动作名(`node_template_name`
@@ -119,7 +161,7 @@ curl -s -X GET "$BASE/api/v1/lab/workflow/template/detail/$workflow_uuid" -H "$A
> **注意**:此 API 返回格式可能因版本不同而有差异。首次调用时,先打印完整响应分析结构,再提取节点信息。常见的节点字段路径为 `data.nodes[]` 或 `data.workflow_nodes[]`。
### 4. 提交实验(创建 notebook
### 5. 提交实验(创建 notebook
```bash
curl -s -X POST "$BASE/api/v1/lab/notebook" \
@@ -131,34 +173,45 @@ curl -s -X POST "$BASE/api/v1/lab/notebook" \
```json
{
"lab_uuid": "<lab_uuid>",
"workflow_uuid": "<workflow_uuid>",
"name": "<实验名称>",
"node_params": [
"lab_uuid": "<lab_uuid>",
"project_uuid": "<project_uuid>",
"workflow_uuid": "<workflow_uuid>",
"name": "<实验名称>",
"node_params": [
{
"sample_uuids": ["<样品UUID1>", "<样品UUID2>"],
"datas": [
{
"sample_uuids": ["<样品UUID1>", "<样品UUID2>"],
"datas": [
{
"node_uuid": "<workflow中的节点UUID>",
"param": {},
"sample_params": [
{
"container_uuid": "<容器UUID>",
"sample_value": {
"liquid_names": "<液体名称>",
"volumes": 1000
}
}
]
}
]
"node_uuid": "<workflow中的节点UUID>",
"param": {},
"sample_params": [
{
"container_uuid": "<容器UUID>",
"sample_value": {
"liquid_names": "<液体名称>",
"volumes": 1000
}
}
]
}
]
]
}
]
}
```
> **注意**`sample_uuids` 必须是 **UUID 数组**`[]uuid.UUID`),不是字符串。无样品时传空数组 `[]`。
### 6. 查询 notebook 状态
提交成功后,使用返回的 notebook UUID 查询执行状态:
```bash
curl -s -X GET "$BASE/api/v1/lab/notebook/status?uuid=$notebook_uuid" -H "$AUTH"
```
提交后应**立即查询一次**状态,确认 notebook 已被正确接收并开始调度。
---
## Notebook 请求体详解
@@ -172,25 +225,25 @@ curl -s -X POST "$BASE/api/v1/lab/notebook" \
### 每轮的字段
| 字段 | 类型 | 说明 |
|------|------|------|
| 字段 | 类型 | 说明 |
| -------------- | ------------- | ----------------------------------------- |
| `sample_uuids` | array\<uuid\> | 该轮实验的样品 UUID 数组,无样品时传 `[]` |
| `datas` | array | 该轮中每个 workflow 节点的参数配置 |
| `datas` | array | 该轮中每个 workflow 节点的参数配置 |
### datas 中每个节点
| 字段 | 类型 | 说明 |
|------|------|------|
| `node_uuid` | string | workflow 模板中的节点 UUID从 API #3 获取) |
| `param` | object | 动作参数(根据本地注册表 schema 填写) |
| `sample_params` | array | 样品相关参数(液体名、体积等) |
| 字段 | 类型 | 说明 |
| --------------- | ------ | -------------------------------------------- |
| `node_uuid` | string | workflow 模板中的节点 UUID从 API #4 获取) |
| `param` | object | 动作参数(根据本地注册表 schema 填写) |
| `sample_params` | array | 样品相关参数(液体名、体积等) |
### sample_params 中每条
| 字段 | 类型 | 说明 |
|------|------|------|
| `container_uuid` | string | 容器 UUID |
| `sample_value` | object | 样品值,如 `{"liquid_names": "水", "volumes": 1000}` |
| 字段 | 类型 | 说明 |
| ---------------- | ------ | ---------------------------------------------------- |
| `container_uuid` | string | 容器 UUID |
| `sample_value` | object | 样品值,如 `{"liquid_names": "水", "volumes": 1000}` |
---
@@ -211,6 +264,7 @@ python scripts/gen_notebook_params.py \
> 脚本位于本文档同级目录下的 `scripts/gen_notebook_params.py`。
脚本会:
1. 调用 workflow detail API 获取所有 action 节点
2. 读取本地注册表,为每个节点查找对应的 action schema
3. 生成 `notebook_template.json`,包含:
@@ -222,7 +276,7 @@ python scripts/gen_notebook_params.py \
如果脚本不可用或注册表不存在:
1. 调用 API #3 获取 workflow 详情
1. 调用 API #4 获取 workflow 详情
2. 找到每个 action 节点的 `node_uuid`
3. 在本地注册表中查找对应设备的 `action_value_mappings`
```
@@ -248,8 +302,11 @@ python scripts/gen_notebook_params.py \
"properties": {
"goal": {
"properties": {
"asp_vols": {"type": "array", "items": {"type": "number"}},
"sources": {"type": "array"}
"asp_vols": {
"type": "array",
"items": { "type": "number" }
},
"sources": { "type": "array" }
},
"required": ["asp_vols", "sources"]
}
@@ -275,13 +332,15 @@ Task Progress:
- [ ] Step 1: 确认 ak/sk → 生成 AUTH token
- [ ] Step 2: 确认 --addr → 设置 BASE URL
- [ ] Step 3: GET /edge/lab/info → 获取 lab_uuid
- [ ] Step 4: 确认 workflow_uuid用户提供或从 GET #2 列表选择)
- [ ] Step 5: GET workflow detail (#3) → 提取各节点 uuid、设备ID、动作名
- [ ] Step 6: 定位本地注册表 req_device_registry_upload.json
- [ ] Step 7: 运行 gen_notebook_params.py 或手动匹配 → 生成 node_params 模板
- [ ] Step 8: 引导用户填写每轮的参数sample_uuids、param、sample_params
- [ ] Step 9: 构建完整请求体 → POST /lab/notebook 提交
- [ ] Step 10: 检查返回结果,确认提交成功
- [ ] Step 4: GET /lab/project/list → 列出项目,让用户选择 → 获取 project_uuid
- [ ] Step 5: 确认 workflow_uuid用户提供或从 GET #3 列表选择)
- [ ] Step 6: GET workflow detail (#4) → 提取各节点 uuid、设备ID、动作名
- [ ] Step 7: 定位本地注册表 req_device_registry_upload.json
- [ ] Step 8: 运行 gen_notebook_params.py 或手动匹配 → 生成 node_params 模板
- [ ] Step 9: 引导用户填写每轮的参数sample_uuids、param、sample_params
- [ ] Step 10: 构建完整请求体(含 project_uuid→ POST /lab/notebook 提交
- [ ] Step 11: 检查返回结果,记录 notebook UUID
- [ ] Step 12: GET /lab/notebook/status → 查询 notebook 状态,确认已调度
```
---

View File

@@ -7,7 +7,7 @@
选项:
--auth <token> Lab tokenbase64(ak:sk) 的结果,不含 "Lab " 前缀)
--base <url> API 基础 URL如 https://uni-lab.test.bohrium.com
--base <url> API 基础 URL如 https://leap-lab.test.bohrium.com
--workflow-uuid <uuid> 目标 workflow 的 UUID
--registry <path> 本地注册表文件路径(默认自动搜索)
--rounds <n> 实验轮次数(默认 1
@@ -17,7 +17,7 @@
示例:
python gen_notebook_params.py \\
--auth YTFmZDlkNGUtxxxx \\
--base https://uni-lab.test.bohrium.com \\
--base https://leap-lab.test.bohrium.com \\
--workflow-uuid abc-123-def \\
--rounds 2
"""
@@ -265,6 +265,7 @@ def generate_template(nodes, registry_index, rounds):
return {
"lab_uuid": "$TODO_LAB_UUID",
"project_uuid": "$TODO_PROJECT_UUID",
"workflow_uuid": "$TODO_WORKFLOW_UUID",
"name": "$TODO_EXPERIMENT_NAME",
"node_params": node_params,

View File

@@ -40,13 +40,13 @@ python ./scripts/gen_auth.py --config <config.py>
决定 API 请求发往哪个服务器。从启动命令的 `--addr` 参数获取:
| `--addr` 值 | BASE URL |
|-------------|----------|
| `test` | `https://uni-lab.test.bohrium.com` |
| `uat` | `https://uni-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://uni-lab.bohrium.com` |
| 其他自定义 URL | 直接使用该 URL |
| `--addr` | BASE URL |
| -------------- | ----------------------------------- |
| `test` | `https://leap-lab.test.bohrium.com` |
| `uat` | `https://leap-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://leap-lab.bohrium.com` |
| 其他自定义 URL | 直接使用该 URL |
#### 必备项 ③req_device_registry_upload.json设备注册表
@@ -54,11 +54,11 @@ python ./scripts/gen_auth.py --config <config.py>
**推断 working_dir**(即 `unilabos_data` 所在目录):
| 条件 | working_dir 取值 |
|------|------------------|
| 条件 | working_dir 取值 |
| -------------------- | -------------------------------------------------------- |
| 传了 `--working_dir` | `<working_dir>/unilabos_data/`(若子目录已存在则直接用) |
| 仅传了 `--config` | `<config 文件所在目录>/unilabos_data/` |
| 都没传 | `<当前工作目录>/unilabos_data/` |
| 仅传了 `--config` | `<config 文件所在目录>/unilabos_data/` |
| 都没传 | `<当前工作目录>/unilabos_data/` |
**按优先级搜索文件**
@@ -84,24 +84,6 @@ python ./scripts/gen_auth.py --config <config.py>
python ./scripts/extract_device_actions.py --registry <找到的文件路径>
```
#### 完整示例
用户提供:
```
--ak a1fd9d4e-xxxx-xxxx-xxxx-d9a69c09f0fd
--sk 136ff5c6-xxxx-xxxx-xxxx-a03e301f827b
--addr test
--port 8003
--disable_browser
```
从中提取:
- ✅ ak/sk → 运行 `gen_auth.py` 得到 `AUTH="Authorization: Lab YTFmZDlk..."`
- ✅ addr=test → `BASE=https://uni-lab.test.bohrium.com`
- ✅ 搜索 `unilabos_data/req_device_registry_upload.json` → 找到并确认时间
- ✅ 用户指明目标设备 → 如 `liquid_handler.prcxi`
**四项全部就绪后才进入 Step 1。**
### Step 1 — 列出可用设备
@@ -129,6 +111,7 @@ python ./scripts/extract_device_actions.py [--registry <path>] <device_id> ./ski
脚本会显示设备的 Python 源码路径和类名,方便阅读源码了解参数含义。
每个 action 生成一个 JSON 文件,包含:
- `type` — 作为 API 调用的 `action_type`
- `schema` — 完整 JSON Schema`properties.goal.properties` 参数定义)
- `goal` — goal 字段映射(含占位符 `$placeholder`
@@ -136,13 +119,14 @@ python ./scripts/extract_device_actions.py [--registry <path>] <device_id> ./ski
### Step 3 — 写 action-index.md
按模板为每个 action 写条目:
按模板为每个 action 写条目**必须包含 `action_type`**
```markdown
### `<action_name>`
<用途描述(一句话)>
- **action_type**: `<从 actions/<name>.json 的 type 字段获取>`
- **Schema**: [`actions/<filename>.json`](actions/<filename>.json)
- **核心参数**: `param1`, `param2`(从 schema.required 获取)
- **可选参数**: `param3`, `param4`
@@ -150,6 +134,8 @@ python ./scripts/extract_device_actions.py [--registry <path>] <device_id> ./ski
```
描述规则:
- **每个 action 必须标注 `action_type`**(从 JSON 的 `type` 字段读取),这是 API #9 调用时的必填参数,传错会导致任务永远卡住
-`schema.properties` 读参数列表schema 已提升为 goal 内容)
-`schema.required` 区分核心/可选参数
- 按功能分类(移液、枪头、外设等)
@@ -158,12 +144,14 @@ python ./scripts/extract_device_actions.py [--registry <path>] <device_id> ./ski
- `unilabos_devices`**DeviceSlot**,填入路径字符串如 `"/host_node"`(从资源树筛选 type=device
- `unilabos_nodes`**NodeSlot**,填入路径字符串如 `"/PRCXI/PRCXI_Deck"`(资源树中任意节点)
- `unilabos_class`**ClassSlot**,填入类名字符串如 `"container"`(从注册表查找)
- `unilabos_formulation`**FormulationSlot**,填入配方数组 `[{well_name, liquids: [{name, volume}]}]`well_name 为目标物料的 name
- array 类型字段 → `[{id, name, uuid}, ...]`
- 特殊:`create_resource``res_id`ResourceSlot可填不存在的路径
### Step 4 — 写 SKILL.md
直接复用 `unilab-device-api` 的 API 模板10 个 endpoint,修改:
直接复用 `unilab-device-api` 的 API 模板,修改:
- 设备名称
- Action 数量
- 目录列表
@@ -171,43 +159,96 @@ python ./scripts/extract_device_actions.py [--registry <path>] <device_id> ./ski
- **AUTH 头** — 使用 Step 0 中 `gen_auth.py` 生成的 `Authorization: Lab <token>`(不要硬编码 `Api` 类型的 key
- **Python 源码路径** — 在 SKILL.md 开头注明设备对应的源码文件,方便参考参数含义
- **Slot 字段表** — 列出本设备哪些 action 的哪些字段需要填入 Slot物料/设备/节点/类名)
- **action_type 速查表** — 在 API #9 说明后面紧跟一个表格,列出每个 action 对应的 `action_type` 值(从 JSON `type` 字段提取),方便 agent 快速查找而无需打开 JSON 文件
API 模板结构:
```markdown
## 设备信息
- device_id, Python 源码路径, 设备类名
## 前置条件(缺一不可)
- ak/sk → AUTH, --addr → BASE URL
## Session State
- lab_uuid通过 API #1 自动匹配,不要问用户), device_name
## 请求约定
## API Endpoints (10 个)
# 注意:
# - #1 获取 lab 列表 + 自动匹配 lab_uuid遍历 is_admin 的 lab
# 调用 /lab/info/{uuid} 比对 access_key == ak
# - #2 创建工作流用 POST /lab/workflow
# - #10 获取资源树路径含 lab_uuid: /lab/material/download/{lab_uuid}
- Windows 平台必须用 curl.exe非 PowerShell 的 curl 别名)
## Session State
- lab_uuid通过 GET /edge/lab/info 直接获取,不要问用户), device_name
## API Endpoints
# - #1 GET /edge/lab/info → 直接拿到 lab_uuid
# - #2 创建工作流 POST /lab/workflow/owner → 拼 URL 告知用户
# - #3 创建节点 POST /edge/workflow/node
# body: {workflow_uuid, resource_template_name: "<device_id>", node_template_name: "<action_name>"}
# - #4 删除节点 DELETE /lab/workflow/nodes
# - #5 更新节点参数 PATCH /lab/workflow/node
# - #6 查询节点 handles POST /lab/workflow/node-handles
# body: {node_uuids: ["uuid1","uuid2"]} → 返回各节点的 handle_uuid
# - #7 批量创建边 POST /lab/workflow/edges
# body: {edges: [{source_node_uuid, target_node_uuid, source_handle_uuid, target_handle_uuid}]}
# - #8 启动工作流 POST /lab/workflow/{uuid}/run
# - #9 运行设备单动作 POST /lab/mcp/run/action action_type 必须从 action-index.md 或 actions/<name>.json 的 type 字段获取,传错会导致任务永远卡住)
# - #10 查询任务状态 GET /lab/mcp/task/{task_uuid}
# - #11 运行工作流单节点 POST /lab/mcp/run/workflow/action
# - #12 获取资源树 GET /lab/material/download/{lab_uuid}
# - #13 获取工作流模板详情 GET /lab/workflow/template/detail/{workflow_uuid}
# 返回 workflow 完整结构data.nodes[] 含每个节点的 uuid、name、param、device_name、handles
# - #14 按名称查询物料模板 GET /lab/material/template/by-name?lab_uuid=&name=
# 返回 res_template_uuid用于 #15 创建物料时的必填字段
# - #15 创建物料节点 POST /edge/material/node
# body: {res_template_uuid(从#14获取), name(自定义), display_name, parent_uuid?(从#12获取), ...}
# - #16 更新物料节点 PUT /edge/material/node
# body: {uuid(从#12获取), display_name?, description?, init_param_data?, data?, ...}
## Placeholder Slot 填写规则
- unilabos_resources → ResourceSlot → {"id":"/path/name","name":"name","uuid":"xxx"}
- unilabos_devices → DeviceSlot → "/parent/device" 路径字符串
- unilabos_nodes → NodeSlot → "/parent/node" 路径字符串
- unilabos_class → ClassSlot → "class_name" 字符串
- unilabos_formulation → FormulationSlot → [{well_name, liquids: [{name, volume}]}] 配方数组
- 特例create_resource 的 res_id 允许填不存在的路径
- 列出本设备所有 Slot 字段、类型及含义
## 渐进加载策略
## 完整工作流 Checklist
```
### Step 5 — 验证
检查文件完整性:
- [ ] `SKILL.md` 包含 10 个 API endpoint
- [ ] `SKILL.md` 包含 Placeholder Slot 填写规则ResourceSlot / DeviceSlot / NodeSlot / ClassSlot + create_resource 特例)和本设备的 Slot 字段表
- [ ] `SKILL.md` 包含 API endpoint#1 获取 lab_uuid、#2-#7 工作流/节点/边、#8-#11 运行/查询、#12 资源树、#13 工作流模板详情、#14-#16 物料管理)
- [ ] `SKILL.md` 包含 Placeholder Slot 填写规则ResourceSlot / DeviceSlot / NodeSlot / ClassSlot / FormulationSlot + create_resource 特例)和本设备的 Slot 字段表
- [ ] `action-index.md` 列出所有 action 并有描述
- [ ] `actions/` 目录中每个 action 有对应 JSON 文件
- [ ] JSON 文件包含 `type`, `schema`(已提升为 goal 内容), `goal`, `goal_default`, `placeholder_keys` 字段
@@ -249,71 +290,202 @@ API 模板结构:
```
> **注意**`schema` 已由脚本从原始 `schema.properties.goal` 提升为顶层,直接包含参数定义。
> `schema.properties` 中的字段即为 API 请求 `param.goal` 中的字段
> `schema.properties` 中的字段即为 API 创建节点返回的 `data.param` 中的字段PATCH 更新时直接修改 `param` 即可
## Placeholder Slot 类型体系
`placeholder_keys` / `_unilabos_placeholder_info` 中有 4 种值,对应不同的填写方式:
`placeholder_keys` / `_unilabos_placeholder_info` 中有 5 种值,对应不同的填写方式:
| placeholder 值 | Slot 类型 | 填写格式 | 选取范围 |
|---------------|-----------|---------|---------|
| `unilabos_resources` | ResourceSlot | `{"id": "/path/name", "name": "name", "uuid": "xxx"}` | 仅**物料**节点(不含设备) |
| `unilabos_devices` | DeviceSlot | `"/parent/device_name"` | 仅**设备**节点type=device路径字符串 |
| `unilabos_nodes` | NodeSlot | `"/parent/node_name"` | **设备 + 物料**,即所有节点,路径字符串 |
| `unilabos_class` | ClassSlot | `"class_name"` | 注册表中已上报的资源类 name |
| placeholder 值 | Slot 类型 | 填写格式 | 选取范围 |
| ---------------------- | --------------- | ----------------------------------------------------- | ----------------------------------------- |
| `unilabos_resources` | ResourceSlot | `{"id": "/path/name", "name": "name", "uuid": "xxx"}` | 仅**物料**节点(不含设备) |
| `unilabos_devices` | DeviceSlot | `"/parent/device_name"` | 仅**设备**节点type=device路径字符串 |
| `unilabos_nodes` | NodeSlot | `"/parent/node_name"` | **设备 + 物料**,即所有节点,路径字符串 |
| `unilabos_class` | ClassSlot | `"class_name"` | 注册表中已上报的资源类 name |
| `unilabos_formulation` | FormulationSlot | `[{well_name, liquids: [{name, volume}]}]` | 资源树中物料节点的 **name**,配合液体配方 |
### ResourceSlot`unilabos_resources`
最常见的类型。从资源树中选取**物料**节点(孔板、枪头盒、试剂槽等):
- 单个:`{"id": "/workstation/container1", "name": "container1", "uuid": "ff149a9a-..."}`
- 数组:`[{"id": "/path/a", "name": "a", "uuid": "xxx"}, ...]`
- `id` 从 parent 计算的路径格式,根据 action 语义选择正确的物料
> **特例**`create_resource` 的 `res_id`,目标物料可能尚不存在,直接填期望路径,不需要 uuid。
### DeviceSlot / NodeSlot / ClassSlot
- **DeviceSlot**`unilabos_devices`):路径字符串如 `"/host_node"`,仅 type=device 的节点
- **NodeSlot**`unilabos_nodes`):路径字符串如 `"/PRCXI/PRCXI_Deck"`,设备 + 物料均可选
- **ClassSlot**`unilabos_class`):类名字符串如 `"container"`,从 `req_resource_registry_upload.json` 查找
### FormulationSlot`unilabos_formulation`
描述**液体配方**:向哪些容器中加入哪些液体及体积。
```json
{"id": "/workstation/container1", "name": "container1", "uuid": "ff149a9a-2cb8-419d-8db5-d3ba056fb3c2"}
[
{
"sample_uuid": "",
"well_name": "bottle_A1",
"liquids": [{ "name": "LiPF6", "volume": 0.6 }]
}
]
```
- 单个schema type=object`{"id": "/path/name", "name": "name", "uuid": "xxx"}`
- 数组schema type=array`[{"id": "/path/a", "name": "a", "uuid": "xxx"}, ...]`
- `id` 本身是从 parent 计算的路径格式
- 根据 action 语义选择正确的物料(如 `sources` = 液体来源,`targets` = 目标位置)
- `well_name` — 目标物料的 **name**(从资源树取,不是 `id` 路径)
- `liquids[]` — 液体列表,每条含 `name`(试剂名)和 `volume`体积单位由上下文决定pylabrobot 内部统一 uL
- `sample_uuid` — 样品 UUID无样品传 `""`
- 与 ResourceSlot 的区别ResourceSlot 指向物料本身FormulationSlot 引用物料名并附带配方信息
> **特例**`create_resource` 的 `res_id` 字段,目标物料可能**尚不存在**,此时直接填写期望的路径(如 `"/workstation/container1"`),不需要 uuid。
### DeviceSlot`unilabos_devices`
填写**设备路径字符串**。从资源树中筛选 type=device 的节点,从 parent 计算路径:
```
"/host_node"
"/bioyond_cell/reaction_station"
```
- 只填路径字符串,不需要 `{id, uuid}` 对象
- 根据 action 语义选择正确的设备(如 `target_device_id` = 目标设备)
### NodeSlot`unilabos_nodes`
范围 = 设备 + 物料。即资源树中**所有节点**都可以选,填写**路径字符串**
```
"/PRCXI/PRCXI_Deck"
```
- 使用场景:当参数既可能指向物料也可能指向设备时(如 `PumpTransferProtocol``from_vessel`/`to_vessel``create_resource``parent`
### ClassSlot`unilabos_class`
填写注册表中已上报的**资源类 name**。从本地 `req_resource_registry_upload.json` 中查找:
```
"container"
```
### 通过 API #10 获取资源树
### 通过 API #12 获取资源树
```bash
curl -s -X GET "$BASE/api/v1/lab/material/download/$lab_uuid" -H "$AUTH"
```
注意 `lab_uuid` 在路径中(不是查询参数)。资源树返回所有节点,每个节点包含 `id`(路径格式)、`name``uuid``type``parent` 等字段。填写 Slot 时需根据 placeholder 类型筛选正确的节点。
注意 `lab_uuid` 在路径中(不是查询参数)。返回结构:
```json
{
"code": 0,
"data": {
"nodes": [
{"name": "host_node", "uuid": "c3ec1e68-...", "type": "device", "parent": ""},
{"name": "PRCXI", "uuid": "e249c9a6-...", "type": "device", "parent": ""},
{"name": "PRCXI_Deck", "uuid": "fb6a8b71-...", "type": "deck", "parent": "PRCXI"}
],
"edges": [...]
}
}
```
- `data.nodes[]` — 所有节点(设备 + 物料),每个节点含 `name``uuid``type``parent`
- `type` 区分设备(`device`)和物料(`deck``container``resource` 等)
- `parent` 为父节点名称(空字符串表示顶级)
- 填写 Slot 时根据 placeholder 类型筛选ResourceSlot 取非 device 节点DeviceSlot 取 device 节点
- 创建/更新物料时:`parent_uuid` 取父节点的 `uuid`,更新目标的 `uuid` 取节点自身的 `uuid`
## 物料管理 API
设备 Skill 除了设备动作外,还需支持物料节点的创建和参数设定,用于在资源树中动态管理物料。
典型流程:先通过 **#14 按名称查询模板** 获取 `res_template_uuid` → 再通过 **#15 创建物料** → 之后可通过 **#16 更新物料** 修改属性。更新时需要的 `uuid``parent_uuid` 均从 **#12 资源树下载** 获取。
### API #14 — 按名称查询物料模板
创建物料前,需要先获取物料模板的 UUID。通过模板名称查询
```bash
curl -s -X GET "$BASE/api/v1/lab/material/template/by-name?lab_uuid=$lab_uuid&name=<template_name>" -H "$AUTH"
```
| 参数 | 必填 | 说明 |
| ---------- | ------ | -------------------------------- |
| `lab_uuid` | **是** | 实验室 UUID从 API #1 获取) |
| `name` | **是** | 物料模板名称(如 `"container"` |
返回 `code: 0` 时,**`data.uuid`** 即为 `res_template_uuid`,用于 API #15 创建物料。返回还包含 `name``resource_type``handles``config_infos` 等模板元信息。
模板不存在时返回 `code: 10002``data` 为空对象。模板名称来自资源注册表中已注册的资源类型。
### API #15 — 创建物料节点
```bash
curl -s -X POST "$BASE/api/v1/edge/material/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '<request_body>'
```
请求体:
```json
{
"res_template_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"name": "my_custom_bottle",
"display_name": "自定义瓶子",
"parent_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "",
"init_param_data": {},
"schema": {},
"data": {
"liquids": [["water", 1000, "uL"]],
"max_volume": 50000
},
"plate_well_datas": {},
"plate_reagent_datas": {},
"pose": {},
"model": {}
}
```
| 字段 | 必填 | 类型 | 数据来源 | 说明 |
| --------------------- | ------ | ------------- | ----------------------------------- | -------------------------------------- |
| `res_template_uuid` | **是** | string (UUID) | **API #14** 按名称查询获取 | 物料模板 UUID |
| `name` | 否 | string | **用户自定义** | 节点名称(标识符),可自由命名 |
| `display_name` | 否 | string | 用户自定义 | 显示名称UI 展示用) |
| `parent_uuid` | 否 | string (UUID) | **API #12** 资源树中父节点的 `uuid` | 父节点,为空则创建顶级节点 |
| `type` | 否 | string | 从模板继承 | 节点类型 |
| `init_param_data` | 否 | object | 用户指定 | 初始化参数,覆盖模板默认值 |
| `data` | 否 | object | 用户指定 | 节点数据container 见下方 data 格式 |
| `plate_well_datas` | 否 | object | 用户指定 | 孔板子节点数据(创建带孔位的板时使用) |
| `plate_reagent_datas` | 否 | object | 用户指定 | 试剂关联数据 |
| `schema` | 否 | object | 从模板继承 | 自定义 schema不传则从模板继承 |
| `pose` | 否 | object | 用户指定 | 位姿信息 |
| `model` | 否 | object | 用户指定 | 3D 模型信息 |
#### container 的 `data` 格式
> **体积单位统一为 uL微升**。pylabrobot 体系中所有体积值(`max_volume`、`liquids` 中的 volume均为 uL。外部如果是 mL 需乘 1000 转换。
```json
{
"liquids": [["water", 1000, "uL"], ["ethanol", 500, "uL"]],
"max_volume": 50000
}
```
- `liquids` — 液体列表,每条为 `[液体名称, 体积(uL), 单位字符串]`
- `max_volume` — 容器最大容量uL如 50 mL = 50000 uL
### API #16 — 更新物料节点
```bash
curl -s -X PUT "$BASE/api/v1/edge/material/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '<request_body>'
```
请求体:
```json
{
"uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"parent_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"display_name": "新显示名称",
"description": "新描述",
"init_param_data": {},
"data": {},
"pose": {},
"schema": {},
"extra": {}
}
```
| 字段 | 必填 | 类型 | 数据来源 | 说明 |
| ----------------- | ------ | ------------- | ------------------------------------- | ---------------- |
| `uuid` | **是** | string (UUID) | **API #12** 资源树中目标节点的 `uuid` | 要更新的物料节点 |
| `parent_uuid` | 否 | string (UUID) | API #12 资源树 | 移动到新父节点 |
| `display_name` | 否 | string | 用户指定 | 更新显示名称 |
| `description` | 否 | string | 用户指定 | 更新描述 |
| `init_param_data` | 否 | object | 用户指定 | 更新初始化参数 |
| `data` | 否 | object | 用户指定 | 更新节点数据 |
| `pose` | 否 | object | 用户指定 | 更新位姿 |
| `schema` | 否 | object | 用户指定 | 更新 schema |
| `extra` | 否 | object | 用户指定 | 更新扩展数据 |
> 只传需要更新的字段,未传的字段保持不变。
## 最终目录结构

View File

@@ -0,0 +1,450 @@
---
name: filter-workflow-by-tags
description: Query backend workflow list, aggregate all tags, and filter workflows by domain/scenario requirements using tags. Use when the user wants to search workflows, find workflows by tags, list available workflow tags, filter workflows by category/domain/scenario, or mentions 工作流筛选/标签查询/workflow tags/按领域查找工作流.
---
# Uni-Lab 工作流标签筛选指南
通过 Uni-Lab 云端 API 查询工作流列表汇总所有可用标签tags并根据领域和场景要求筛选工作流。
> **重要**:本指南中的 `Authorization: Lab <token>` 是 **Uni-Lab 平台专用的认证方式**`Lab` 是 Uni-Lab 的 auth scheme 关键字,**不是** HTTP Basic 认证。请勿将其替换为 `Basic`。
## 使用模式识别
**用户可能一开始就给出场景目标**(如"我要做有机合成实验"、"找柱层析相关的 protocol")。此时:
1. **识别场景关键词** → 映射到可能的 tags如 synthesis、organic、chromatography、purification
2. **直接执行完整流程**(获取 ak/sk/addr → 拉取所有工作流 → 汇总 tags → 按场景筛选)
3. **展示筛选结果** → 引导用户从候选 workflow 中**选择明确的实验 protocol**
4. **如果用户确认某个 workflow** → 记录 `workflow_uuid`,准备对接“与其他 Skill 的协作”
**如果用户未给场景目标**,则按标准 checklist 询问筛选条件。
---
## 前置条件
使用本指南前,**必须**先确认以下信息。如果缺少任何一项,**立即向用户询问并终止**,等补齐后再继续。
### 1. ak / sk → AUTH
询问用户的启动参数,从 `--ak` `--sk` 或 config.py 中获取。
生成 AUTH token
```bash
python -c "import base64,sys; print('Authorization: Lab ' + base64.b64encode(f'{sys.argv[1]}:{sys.argv[2]}'.encode()).decode())" <ak> <sk>
```
### 2. --addr → BASE URL
| `--addr` 值 | BASE |
| ------------- | ------------------------------------- |
| `test` | `https://leap-lab.test.bohrium.com` |
| `uat` | `https://leap-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://leap-lab.bohrium.com` |
确认后设置:
```bash
BASE="<根据 addr 确定的 URL>"
AUTH="Authorization: Lab <上面命令输出的 token>"
```
### 3. lab_uuid实验室 UUID
如果用户未提供 `lab_uuid`,通过以下 API 自动获取:
```bash
curl -s -X GET "$BASE/api/v1/edge/lab/info" -H "$AUTH"
```
返回 `data.uuid` 即为 `lab_uuid`
**三项全部就绪后才可开始。**
## Session State
在整个对话过程中agent 需要记住以下状态:
- `lab_uuid` — 实验室 UUID
- `all_workflows` — 完整工作流列表(分页获取后缓存到内存或临时文件)
- `all_tags` — 所有工作流的标签汇总
---
## API 端点
### 查询工作流列表(支持分页)
```
GET $BASE/api/v1/lab/workflow/owner/list?page=<page>&page_size=<page_size>&lab_uuid=$lab_uuid
```
**参数:**
- `page` — 页码,从 1 开始
- `page_size` — 每页数量,建议 1000
- `lab_uuid` — 实验室 UUID
**返回结构:**
```json
{
"code": 0,
"data": {
"has_more": true,
"data": [
{
"uuid": "9661bba2-1b9f-4687-a63d-910245df174b",
"name": "Untitled",
"description": "",
"user_id": "114211",
"published": false,
"tags": null
},
{
"uuid": "e0436638-190b-46bc-b1a1-2711d9602f6a",
"name": "Synthesis v2",
"user_id": "114211",
"published": true,
"tags": ["synthesis", "organic"]
}
]
}
}
```
**字段说明:**
- `has_more` — 若为 `true`,需要继续请求 `page+1`
- `tags` — 可能为 `null`、空数组或字符串数组;聚合时必须容忍 `null`
### 启动工作流(直接运行)
```
POST $BASE/api/v1/lab/workflow/<workflow_uuid>/run
```
**用途:** 直接启动一个 workflow 的默认执行(使用模板中预设的参数),无需创建 notebook。适用于快速测试或无参数变化的重复执行。
**请求体:** 空 JSON `{}` 或省略
**返回:**
```json
{
"code": 0,
"data": "<run_uuid>"
}
```
- `run_uuid` — 本次执行的唯一标识(不是 notebook UUID
**注意:**
- 该接口会使用 workflow 模板中保存的默认参数直接执行
- 如果 workflow 需要动态参数(如 CSV 路径、样品 UUID应使用 `POST /lab/notebook` 创建 notebook 并传入 `node_params`
- 返回的 `run_uuid` 可直接传入下方「查询任务状态」接口查询实时进度
### 查询任务状态
```
GET $BASE/api/v1/lab/mcp/task/<task_uuid>
```
**用途:** 查询由 `POST /lab/workflow/<uuid>/run` 返回的 `run_uuid`(即 task_uuid的实时执行状态包括整体状态和每个节点JOSJob On Station的执行详情。
**路径参数:**
- `task_uuid` — 等同于启动工作流接口返回的 `run_uuid`
**返回:**
```json
{
"code": 0,
"data": {
"status": "running",
"jos_status": [
{
"uuid": "d0e24bfe-8d99-450e-b19d-f25849dfbaad",
"node_name": "PRCXI_BioER_96_wellplate_slot_1",
"action_name": "create_resource",
"status": "success",
"return_info": {
"suc": true,
"error": "",
"return_value": { ... }
}
},
{
"uuid": "...",
"node_name": "...",
"action_name": "transfer_liquid",
"status": "pending",
"return_info": null
}
]
}
}
```
**字段说明:**
- `data.status` — 整体任务状态
- `running` — 正在执行(至少一个节点 pending 或 running
- `success` — 全部节点成功
- `failed` — 有节点失败
- `data.jos_status[]` — 节点级执行列表(按执行顺序)
- `uuid` — 节点执行实例 UUID
- `node_name` — 节点名称(资源/设备名或工位名)
- `action_name` — 动作类型(`create_resource``transfer_liquid``centrifuge`、等)
- `status` — 节点状态:`success``pending``running``failed`
- `return_info` — 执行返回,失败时 `suc=false``error` 有错误信息
**注意:**
- 此接口的 `task_uuid` **是** `POST /lab/workflow/<uuid>/run` 返回的 `run_uuid`,二者为同一个 ID 的不同称呼
- **不要**把 notebook UUID`POST /lab/notebook` 返回)传进来——那条路径用 `GET /lab/notebook/status` 查询
- `jos_status` 数组按节点执行顺序给出;从 pending 数量可以估算剩余进度
- 返回体可能较大(`return_info.return_value` 中可能包含完整 resource tree可在脚本中只提取 `status` + `node_name` + `action_name` 做摘要
**状态轮询示例:**
```bash
# 每 5 秒轮询一次直至完成
TASK="b183d97e-d2b5-4b24-b14b-820df04d87c0"
while :; do
st=$(curl -s -X GET "$BASE/api/v1/lab/mcp/task/$TASK" -H "$AUTH" \
| python3 -c "import json,sys; d=json.load(sys.stdin)['data']; \
print(d['status'], '|', sum(1 for j in d['jos_status'] if j['status']=='success'), '/', len(d['jos_status']))")
echo "$(date +%H:%M:%S) $st"
[[ "$st" == success* || "$st" == failed* ]] && break
sleep 5
done
```
---
## 完整工作流 Checklist
```
Task Progress:
- [ ] Step 0: 识别用户是否已给出场景目标(如"有机合成"、"柱层析"
- 若已给出 → 记录场景关键词,自动进入后续步骤
- 若未给出 → 在 Step 6 询问用户
- [ ] Step 1: 确认 ak/sk → 生成 AUTH token
- [ ] Step 2: 确认 --addr → 设置 BASE URL
- [ ] Step 3: GET /edge/lab/info → 获取 lab_uuid如用户未提供
- [ ] Step 4: 分页获取所有工作流(从 page=1 开始直到 has_more=false
- [ ] Step 5: 汇总所有非空 tags → 生成 all_tags去重、排序、附出现次数
- [ ] Step 6: 根据场景关键词Step 0 或新询问)在 all_tags 中做语义映射 → 确定候选 tags
- 若语义映射不唯一,列出候选 tags 让用户确认
- [ ] Step 7: 按候选 tags 筛选工作流(默认 any 模式,召回优先)
- [ ] Step 8: 展示筛选结果uuid、name、description、tags、published
- [ ] Step 9: 引导用户从结果中选择**明确的实验 protocol**
- 若结果只有 1 条 → 直接确认该 workflow_uuid
- 若结果 210 条 → 让用户按编号选择
- 若结果过多 → 提示收紧条件(加 tag、切换 all 模式、仅 published
- 若结果为空 → 放宽条件(去掉最稀有 tag或提示用户换关键词
- [ ] Step 10: 记录用户选中的 workflow_uuid并提示提交实验或查看详情
```
---
## 推荐路径:使用脚本
同目录下提供 `scripts/filter_workflows.py`,一次完成分页抓取、标签聚合与筛选:
```bash
# 1. 仅汇总标签(不筛选)
python scripts/filter_workflows.py \
--auth "<Lab base64token>" \
--base "$BASE" \
--lab-uuid "$lab_uuid" \
--summary-only
# 2. 按标签筛选ANY 模式:包含任一)
python scripts/filter_workflows.py \
--auth "<Lab base64token>" \
--base "$BASE" \
--lab-uuid "$lab_uuid" \
--tags synthesis organic \
--mode any
# 3. 按标签筛选ALL 模式:必须同时包含)
python scripts/filter_workflows.py \
--auth "<Lab base64token>" \
--base "$BASE" \
--lab-uuid "$lab_uuid" \
--tags synthesis organic \
--mode all \
--output filtered.json
# 4. 仅筛选已发布
python scripts/filter_workflows.py \
--auth "<Lab base64token>" \
--base "$BASE" \
--lab-uuid "$lab_uuid" \
--tags synthesis \
--published-only
```
**`--auth` 参数说明**:传入 `Authorization` 头中 `Lab` 之后的 base64 token不带 `Lab ` 前缀),脚本内部会自动补上 scheme。
**输出结构:**
```json
{
"total_workflows": 150,
"tag_counts": {"synthesis": 12, "organic": 8, "analysis": 5},
"all_tags": ["analysis", "organic", "synthesis"],
"filter": {"tags": ["synthesis", "organic"], "mode": "any"},
"filtered_workflows": [
{"uuid": "...", "name": "...", "description": "...", "tags": [...], "published": true}
]
}
```
---
## 手动路径curl + jq
如果脚本不可用或环境缺少 Python可用 shell 实现。
### 1. 分页抓取(写入 `all_workflows.json`
```bash
page=1
echo "[]" > all_workflows.json
while :; do
resp=$(curl -s -X GET \
"$BASE/api/v1/lab/workflow/owner/list?page=$page&page_size=1000&lab_uuid=$lab_uuid" \
-H "$AUTH")
page_data=$(echo "$resp" | jq -c '.data.data // []')
jq -c --argjson p "$page_data" '. + $p' all_workflows.json > _tmp.json && mv _tmp.json all_workflows.json
has_more=$(echo "$resp" | jq -r '.data.has_more')
[ "$has_more" != "true" ] && break
page=$((page + 1))
done
echo "Total: $(jq 'length' all_workflows.json)"
```
### 2. 汇总所有标签(含出现次数)
```bash
jq '[.[].tags // [] | .[]] | group_by(.) | map({tag: .[0], count: length}) | sort_by(-.count)' \
all_workflows.json
```
### 3. 按标签筛选
```bash
# ANY包含任一指定标签
jq --argjson want '["synthesis","organic"]' \
'[.[] | select((.tags // []) | any(. as $t | $want | index($t)))]' \
all_workflows.json
# ALL同时包含所有指定标签
jq --argjson want '["synthesis","organic"]' \
'[.[] | select(($want | all(. as $w | (.tags // []) | index($w))))]' \
all_workflows.json
```
---
## 筛选策略
agent 拿到用户的「领域 + 场景」自然语言描述时,按如下顺序选择 tag
1. **优先用户显式指定的 tags**:若用户明确给出标签词,直接精确匹配。
2. **从 all_tags 中做语义映射**:若用户描述是自然语言(如"有机合成、柱层析"),在 all_tags 中找语义相关项(如 `synthesis``organic``chromatography`)。必要时展示候选 tag 让用户确认。
3. **模式选择**
- 默认 `any`(更多召回),给出 tag 集合的并集匹配
- 用户强调"必须同时满足"时用 `all`
4. **空结果兜底**:如果筛选为空,放宽条件(去掉最稀有 tag、切换 any 模式),并提醒用户。
---
## 引导到明确的 Protocol
筛选完成后,**最终目标是让用户确认一个具体的 workflow_uuid**,而不是停留在"一堆候选"上。按结果数量采取不同策略:
| 结果数量 | 策略 |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| 0 条 | 放宽筛选(去掉最稀有 tag → 切换 any 模式 → 去掉 `--published-only`)。仍为空则提示换关键词,或列出 `all_tags` 让用户重新选。 |
| 1 条 | 直接确认:"找到唯一匹配:`<name>` (uuid `<uuid>`),是否用它?"用户确认后记录 `workflow_uuid`。 |
| 210 条 | 编号列表展示,让用户选编号。每项给出 name、tags、description 摘要、published 状态。 |
| 1030 条 | 先展示 tag 分布帮助用户进一步收紧:列出匹配结果中最常见的子标签,提示"加一个 tag 可将结果缩小到 N 条"。 |
| >30 条 | 强制要求用户补充条件:仅 published、指定具体 tag 组合、或按名称关键词过滤。 |
**确认 workflow 后**
1.`workflow_uuid` 写入 session state
2. 提示用户下一步可用的 skill
- 提交实验 → 引导到“与其他 Skill 的协作”
- 查看 workflow 详细节点 → `GET /api/v1/lab/workflow/template/detail/<workflow_uuid>`
3. 若用户想换一个,回到筛选步骤。
---
## 展示结果
推荐格式(表格 + 汇总统计):
```
共 150 个工作流,其中 32 个匹配筛选条件 [tags: synthesis OR organic]
| UUID (短) | 名称 | Tags | 已发布 |
|-----------|--------------------------|------------------------------|--------|
| e0436638 | Synthesis v2 | synthesis, organic | ✓ |
| 5b60dbb8 | Grignard Protocol | synthesis, organometallic | ✓ |
| ... | ... | ... | ... |
所有可用标签(按频次):
synthesis (12), organic (8), analysis (5), purification (4), ...
```
如果用户下一步想执行某工作流 → 引导到“与其他 Skill 的协作”。
---
## 常见问题
### Q: tags 为 null 的工作流要不要展示?
默认**不展示**在筛选结果中(因为无法按 tag 匹配)。但在 `--summary-only` 或无筛选条件时,这些工作流仍会计入总数,并在输出中单独列出"未打标签"计数。
### Q: 如何按名称/描述做模糊匹配?
脚本未内置,但可在 jq 中组合:
```bash
jq '[.[] | select((.name + " " + (.description // "")) | test("organic"; "i"))]' all_workflows.json
```
### Q: `page_size=1000` 是否会被服务端限制?
接口通常允许最大 1000如果返回量少于 1000 且 `has_more=false`,说明已到末页。极端情况下若服务端返回错误,可降到 200 或 500 再试。
### Q: 工作流数量极大(>10k怎么办
1. 先跑 `--summary-only` 了解 tag 分布
2. 提示用户先限定 `--published-only` 或指定 tag
3. 考虑将 `all_workflows.json` 缓存到本地,下次直接复用
---
## 与其他 Skill 的协作
- 正常情况下,找到 workflow 之后可以直接用它提交实验(启动工作流的 api 端点 POST $BASE/api/v1/lab/workflow/<workflow_uuid>/run不用别的 skill
- **仅当需要进行多次实验时,使用 batch-submit-experiment** — 筛选到目标工作流后,`workflow_uuid` 直接用于实验提交
## 脚本依赖
`scripts/filter_workflows.py` 仅使用 Python 标准库(`urllib``json``argparse`),无需额外安装。

View File

@@ -0,0 +1,191 @@
#!/usr/bin/env python3
"""分页拉取 Uni-Lab 工作流列表,汇总 tags 并按 tag 筛选。
使用示例:
python filter_workflows.py \
--auth <base64token> \
--base https://leap-lab.test.bohrium.com \
--lab-uuid a9059772-... \
--tags synthesis organic --mode any
仅依赖 Python 标准库。
"""
from __future__ import annotations
import argparse
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
def fetch_all_workflows(base: str, auth_token: str, lab_uuid: str, page_size: int = 1000) -> list[dict]:
"""分页拉取所有 owner 工作流,直到 has_more=false。"""
workflows: list[dict] = []
page = 1
while True:
query = urllib.parse.urlencode(
{"page": page, "page_size": page_size, "lab_uuid": lab_uuid}
)
url = f"{base.rstrip('/')}/api/v1/lab/workflow/owner/list?{query}"
req = urllib.request.Request(
url,
headers={
"Authorization": f"Lab {auth_token}",
"Accept": "application/json",
},
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
payload = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
sys.exit(f"[ERROR] HTTP {e.code} on page {page}: {e.read().decode('utf-8', 'ignore')}")
except urllib.error.URLError as e:
sys.exit(f"[ERROR] URL error on page {page}: {e.reason}")
if payload.get("code") != 0:
sys.exit(f"[ERROR] API returned non-zero code: {payload}")
data = payload.get("data") or {}
page_items = data.get("data") or []
workflows.extend(page_items)
if not data.get("has_more"):
break
page += 1
# 防御性兜底,避免接口异常导致无限循环
if page > 1000:
print(f"[WARN] page count exceeded 1000, stopping early", file=sys.stderr)
break
return workflows
def aggregate_tags(workflows: list[dict]) -> tuple[list[str], dict[str, int], int]:
"""返回 (sorted_tags, tag_counts, untagged_count)。"""
counter: Counter[str] = Counter()
untagged = 0
for wf in workflows:
tags = wf.get("tags")
if not tags:
untagged += 1
continue
for t in tags:
if isinstance(t, str) and t.strip():
counter[t.strip()] += 1
return sorted(counter.keys()), dict(counter), untagged
def filter_workflows(
workflows: list[dict],
want_tags: list[str],
mode: str,
published_only: bool,
) -> list[dict]:
"""按 tag 筛选。mode 取值 any / all。"""
want_set = {t.strip() for t in want_tags if t.strip()}
out: list[dict] = []
for wf in workflows:
if published_only and not wf.get("published"):
continue
if not want_set:
out.append(wf)
continue
tags = wf.get("tags") or []
tag_set = {t for t in tags if isinstance(t, str)}
if mode == "all":
if want_set.issubset(tag_set):
out.append(wf)
else: # any
if want_set & tag_set:
out.append(wf)
return out
def project_workflow(wf: dict) -> dict:
"""精简输出字段。"""
return {
"uuid": wf.get("uuid"),
"name": wf.get("name"),
"description": wf.get("description", ""),
"tags": wf.get("tags") or [],
"published": bool(wf.get("published")),
"user_id": wf.get("user_id"),
}
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Fetch & filter Uni-Lab workflows by tags.")
p.add_argument("--auth", required=True, help="Base64 token (the part after `Lab `).")
p.add_argument("--base", required=True, help="Base URL, e.g. https://leap-lab.test.bohrium.com")
p.add_argument("--lab-uuid", required=True, help="Lab UUID.")
p.add_argument("--tags", nargs="*", default=[], help="Tags to filter by (space separated).")
p.add_argument(
"--mode",
choices=["any", "all"],
default="any",
help="any: workflow contains at least one tag; all: workflow contains every tag.",
)
p.add_argument("--published-only", action="store_true", help="Only include published workflows.")
p.add_argument("--page-size", type=int, default=1000, help="Page size, default 1000.")
p.add_argument(
"--summary-only",
action="store_true",
help="Print tag summary without applying filter (still fetches everything).",
)
p.add_argument("--output", help="Write JSON result to this path. If omitted, print to stdout.")
return p.parse_args()
def main() -> None:
args = parse_args()
workflows = fetch_all_workflows(
base=args.base,
auth_token=args.auth,
lab_uuid=args.lab_uuid,
page_size=args.page_size,
)
sorted_tags, tag_counts, untagged = aggregate_tags(workflows)
if args.summary_only:
result = {
"total_workflows": len(workflows),
"untagged_count": untagged,
"tag_counts": tag_counts,
"all_tags": sorted_tags,
}
else:
filtered = filter_workflows(
workflows,
want_tags=args.tags,
mode=args.mode,
published_only=args.published_only,
)
result = {
"total_workflows": len(workflows),
"untagged_count": untagged,
"tag_counts": tag_counts,
"all_tags": sorted_tags,
"filter": {
"tags": args.tags,
"mode": args.mode,
"published_only": args.published_only,
},
"matched_count": len(filtered),
"filtered_workflows": [project_workflow(wf) for wf in filtered],
}
payload = json.dumps(result, ensure_ascii=False, indent=2)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
f.write(payload)
print(f"Wrote {len(workflows)} workflows summary → {args.output}", file=sys.stderr)
else:
print(payload)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,251 @@
---
name: host-node
description: Operate Uni-Lab host node via REST API — create resources, test latency, test resource tree, manual confirm. Use when the user mentions host_node, creating resources, resource management, testing latency, or any host node operation.
---
# Host Node API Skill
## 设备信息
- **device_id**: `host_node`
- **Python 源码**: `unilabos/ros/nodes/presets/host_node.py`
- **设备类**: `HostNode`
- **动作数**: 4`create_resource`, `test_latency`, `auto-test_resource`, `manual_confirm`
## 前置条件(缺一不可)
使用本 skill 前,**必须**先确认以下信息。如果缺少任何一项,**立即向用户询问并终止**,等补齐后再继续。
### 1. ak / sk → AUTH
从启动参数 `--ak` `--sk` 或 config.py 中获取,生成 token`base64(ak:sk)``Authorization: Lab <token>`
### 2. --addr → BASE URL
| `--addr` 值 | BASE |
| ------------ | ----------------------------------- |
| `test` | `https://leap-lab.test.bohrium.com` |
| `uat` | `https://leap-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://leap-lab.bohrium.com` |
确认后设置:
```bash
BASE="<根据 addr 确定的 URL>"
AUTH="Authorization: Lab <token>"
```
**两项全部就绪后才可发起 API 请求。**
## Session State
在整个对话过程中agent 需要记住以下状态,避免重复询问用户:
- `lab_uuid` — 实验室 UUID首次通过 API #1 自动获取,**不需要问用户**
- `device_name``host_node`
## 请求约定
所有请求使用 `curl -s`POST/PATCH/DELETE 需加 `Content-Type: application/json`
> **Windows 平台**必须使用 `curl.exe`(而非 PowerShell 的 `curl` 别名)。
---
## API Endpoints
### 1. 获取实验室信息(自动获取 lab_uuid
```bash
curl -s -X GET "$BASE/api/v1/edge/lab/info" -H "$AUTH"
```
返回 `data.uuid``lab_uuid``data.name``lab_name`
### 2. 创建工作流
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/owner" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"name":"<名称>","lab_uuid":"<lab_uuid>","description":"<描述>"}'
```
返回 `data.uuid``workflow_uuid`。创建成功后告知用户链接:`$BASE/laboratory/$lab_uuid/workflow/$workflow_uuid`
### 3. 创建节点
```bash
curl -s -X POST "$BASE/api/v1/edge/workflow/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"workflow_uuid":"<workflow_uuid>","resource_template_name":"host_node","node_template_name":"<action_name>"}'
```
- `resource_template_name` 固定为 `host_node`
- `node_template_name` — action 名称(如 `create_resource`, `test_latency`
### 4. 删除节点
```bash
curl -s -X DELETE "$BASE/api/v1/lab/workflow/nodes" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"node_uuids":["<uuid1>"],"workflow_uuid":"<workflow_uuid>"}'
```
### 5. 更新节点参数
```bash
curl -s -X PATCH "$BASE/api/v1/lab/workflow/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"workflow_uuid":"<wf_uuid>","uuid":"<node_uuid>","param":{...}}'
```
`param` 直接使用创建节点返回的 `data.param` 结构,修改需要填入的字段值。参考 [action-index.md](action-index.md) 确定哪些字段是 Slot。
### 6. 查询节点 handles
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/node-handles" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"node_uuids":["<node_uuid_1>","<node_uuid_2>"]}'
```
### 7. 批量创建边
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/edges" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"edges":[{"source_node_uuid":"<uuid>","target_node_uuid":"<uuid>","source_handle_uuid":"<uuid>","target_handle_uuid":"<uuid>"}]}'
```
### 8. 启动工作流
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/<workflow_uuid>/run" -H "$AUTH"
```
### 9. 运行设备单动作
```bash
curl -s -X POST "$BASE/api/v1/lab/mcp/run/action" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"lab_uuid":"<lab_uuid>","device_id":"host_node","action":"<action_name>","action_type":"<type>","param":{...}}'
```
`param` 直接放 goal 里的属性,**不要**再包一层 `{"goal": {...}}`
> **WARNING: `action_type` 必须正确,传错会导致任务永远卡住无法完成。** 从下表或 `actions/<name>.json` 的 `type` 字段获取。
#### action_type 速查表
| action | action_type |
|--------|-------------|
| `test_latency` | `UniLabJsonCommand` |
| `create_resource` | `ResourceCreateFromOuterEasy` |
| `auto-test_resource` | `UniLabJsonCommand` |
| `manual_confirm` | `UniLabJsonCommand` |
### 10. 查询任务状态
```bash
curl -s -X GET "$BASE/api/v1/lab/mcp/task/<task_uuid>" -H "$AUTH"
```
### 11. 运行工作流单节点
```bash
curl -s -X POST "$BASE/api/v1/lab/mcp/run/workflow/action" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"node_uuid":"<node_uuid>"}'
```
### 12. 获取资源树(物料信息)
```bash
curl -s -X GET "$BASE/api/v1/lab/material/download/$lab_uuid" -H "$AUTH"
```
注意 `lab_uuid` 在路径中。返回 `data.nodes[]` 含所有节点(设备 + 物料),每个节点含 `name``uuid``type``parent`
### 13. 获取工作流模板详情
```bash
curl -s -X GET "$BASE/api/v1/lab/workflow/template/detail/$workflow_uuid" -H "$AUTH"
```
> 必须使用 `/lab/workflow/template/detail/{uuid}`,其他路径会返回 404。
### 14. 按名称查询物料模板
```bash
curl -s -X GET "$BASE/api/v1/lab/material/template/by-name?lab_uuid=$lab_uuid&name=<template_name>" -H "$AUTH"
```
返回 `data.uuid``res_template_uuid`,用于 API #15
### 15. 创建物料节点
```bash
curl -s -X POST "$BASE/api/v1/edge/material/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"res_template_uuid":"<uuid>","name":"<名称>","display_name":"<显示名>","parent_uuid":"<父节点uuid>","data":{...}}'
```
### 16. 更新物料节点
```bash
curl -s -X PUT "$BASE/api/v1/edge/material/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"uuid":"<节点uuid>","display_name":"<新名称>","data":{...}}'
```
---
## Placeholder Slot 填写规则
| `placeholder_keys` 值 | Slot 类型 | 填写格式 | 选取范围 |
| --------------------- | ------------ | ----------------------------------------------------- | ---------------------- |
| `unilabos_resources` | ResourceSlot | `{"id": "/path/name", "name": "name", "uuid": "xxx"}` | 仅物料节点(非设备) |
| `unilabos_devices` | DeviceSlot | `"/parent/device_name"` | 仅设备节点type=device |
| `unilabos_nodes` | NodeSlot | `"/parent/node_name"` | 所有节点(设备 + 物料) |
| `unilabos_class` | ClassSlot | `"class_name"` | 注册表中已注册的资源类 |
### host_node 设备的 Slot 字段表
| Action | 字段 | Slot 类型 | 说明 |
| ----------------- | ----------- | ------------ | ------------------------------ |
| `create_resource` | `res_id` | ResourceSlot | 新资源路径(可填不存在的路径) |
| `create_resource` | `device_id` | DeviceSlot | 归属设备 |
| `create_resource` | `parent` | NodeSlot | 父节点路径 |
| `create_resource` | `class_name`| ClassSlot | 资源类名如 `"container"` |
| `auto-test_resource` | `resource` | ResourceSlot | 单个测试物料 |
| `auto-test_resource` | `resources` | ResourceSlot | 测试物料数组 |
| `auto-test_resource` | `device` | DeviceSlot | 测试设备 |
| `auto-test_resource` | `devices` | DeviceSlot | 测试设备 |
---
## 渐进加载策略
1. **SKILL.md**(本文件)— API 端点 + session state 管理
2. **[action-index.md](action-index.md)** — 按分类浏览 4 个动作的描述和核心参数
3. **[actions/\<name\>.json](actions/)** — 仅在需要构建具体请求时,加载对应 action 的完整 JSON Schema
---
## 完整工作流 Checklist
```
Task Progress:
- [ ] Step 1: GET /edge/lab/info 获取 lab_uuid
- [ ] Step 2: 获取资源树 (GET #12) → 记住可用物料
- [ ] Step 3: 读 action-index.md 确定要用的 action 名
- [ ] Step 4: 创建工作流 (POST #2) → 记住 workflow_uuid告知用户链接
- [ ] Step 5: 创建节点 (POST #3, resource_template_name=host_node) → 记住 node_uuid + data.param
- [ ] Step 6: 根据 _unilabos_placeholder_info 和资源树,填写 data.param 中的 Slot 字段
- [ ] Step 7: 更新节点参数 (PATCH #5)
- [ ] Step 8: 查询节点 handles (POST #6) → 获取各节点的 handle_uuid
- [ ] Step 9: 批量创建边 (POST #7) → 用 handle_uuid 连接节点
- [ ] Step 10: 启动工作流 (POST #8) 或运行单节点 (POST #11)
- [ ] Step 11: 查询任务状态 (GET #10) 确认完成
```

View File

@@ -0,0 +1,58 @@
# Action Index — host_node
4 个动作,按功能分类。每个动作的完整 JSON Schema 在 `actions/<name>.json`
---
## 资源管理
### `create_resource`
在资源树中创建新资源(容器、物料等),支持指定位置、类型和初始液体
- **action_type**: `ResourceCreateFromOuterEasy`
- **Schema**: [`actions/create_resource.json`](actions/create_resource.json)
- **可选参数**: `res_id`, `device_id`, `class_name`, `parent`, `bind_locations`, `liquid_input_slot`, `liquid_type`, `liquid_volume`, `slot_on_deck`
- **占位符字段**:
- `res_id`**ResourceSlot**(特例:目标物料可能尚不存在,直接填期望路径)
- `device_id`**DeviceSlot**,填路径字符串如 `"/host_node"`
- `parent`**NodeSlot**,填路径字符串如 `"/workstation/deck"`
- `class_name`**ClassSlot**,填类名如 `"container"`
### `auto-test_resource`
测试资源系统,返回当前资源树和设备列表
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/test_resource.json`](actions/test_resource.json)
- **可选参数**: `resource`, `resources`, `device`, `devices`
- **占位符字段**:
- `resource`**ResourceSlot**,单个物料节点 `{id, name, uuid}`
- `resources`**ResourceSlot**,物料节点数组 `[{id, name, uuid}, ...]`
- `device`**DeviceSlot**,设备路径字符串
- `devices`**DeviceSlot**,设备路径字符串
---
## 系统工具
### `test_latency`
测试设备通信延迟,返回 RTT、时间差、任务延迟等指标
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/test_latency.json`](actions/test_latency.json)
- **参数**: 无(零参数调用)
---
## 人工确认
### `manual_confirm`
创建人工确认节点,等待用户手动确认后继续
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/manual_confirm.json`](actions/manual_confirm.json)
- **核心参数**: `timeout_seconds`(超时时间,秒), `assignee_user_ids`(指派用户 ID 列表)
- **占位符字段**: `assignee_user_ids``unilabos_manual_confirm` 类型

View File

@@ -0,0 +1,93 @@
{
"type": "ResourceCreateFromOuterEasy",
"goal": {
"res_id": "res_id",
"class_name": "class_name",
"parent": "parent",
"device_id": "device_id",
"bind_locations": "bind_locations",
"liquid_input_slot": "liquid_input_slot[]",
"liquid_type": "liquid_type[]",
"liquid_volume": "liquid_volume[]",
"slot_on_deck": "slot_on_deck"
},
"schema": {
"type": "object",
"properties": {
"res_id": {
"type": "string"
},
"device_id": {
"type": "string"
},
"class_name": {
"type": "string"
},
"parent": {
"type": "string"
},
"bind_locations": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z"
],
"title": "bind_locations",
"additionalProperties": false
},
"liquid_input_slot": {
"type": "array",
"items": {
"type": "integer"
}
},
"liquid_type": {
"type": "array",
"items": {
"type": "string"
}
},
"liquid_volume": {
"type": "array",
"items": {
"type": "number"
}
},
"slot_on_deck": {
"type": "string"
}
},
"required": [],
"_unilabos_placeholder_info": {
"res_id": "unilabos_resources",
"device_id": "unilabos_devices",
"parent": "unilabos_nodes",
"class_name": "unilabos_class"
}
},
"goal_default": {},
"placeholder_keys": {
"res_id": "unilabos_resources",
"device_id": "unilabos_devices",
"parent": "unilabos_nodes",
"class_name": "unilabos_class"
}
}

View File

@@ -0,0 +1,32 @@
{
"type": "UniLabJsonCommand",
"goal": {
"timeout_seconds": "timeout_seconds",
"assignee_user_ids": "assignee_user_ids"
},
"schema": {
"type": "object",
"properties": {
"timeout_seconds": {
"type": "integer"
},
"assignee_user_ids": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"timeout_seconds",
"assignee_user_ids"
],
"_unilabos_placeholder_info": {
"assignee_user_ids": "unilabos_manual_confirm"
}
},
"goal_default": {},
"placeholder_keys": {
"assignee_user_ids": "unilabos_manual_confirm"
}
}

View File

@@ -0,0 +1,11 @@
{
"type": "UniLabJsonCommand",
"goal": {},
"schema": {
"type": "object",
"properties": {},
"required": []
},
"goal_default": {},
"placeholder_keys": {}
}

View File

@@ -0,0 +1,255 @@
{
"type": "UniLabJsonCommand",
"goal": {
"resource": "resource",
"resources": "resources",
"device": "device",
"devices": "devices"
},
"schema": {
"type": "object",
"properties": {
"resource": {
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"sample_id": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"type": "string"
}
},
"parent": {
"type": "string"
},
"type": {
"type": "string"
},
"category": {
"type": "string"
},
"pose": {
"type": "object",
"properties": {
"position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z"
],
"title": "position",
"additionalProperties": false
},
"orientation": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"w": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z",
"w"
],
"title": "orientation",
"additionalProperties": false
}
},
"required": [
"position",
"orientation"
],
"title": "pose",
"additionalProperties": false
},
"config": {
"type": "string"
},
"data": {
"type": "string"
}
},
"title": "resource"
},
"resources": {
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"sample_id": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"type": "string"
}
},
"parent": {
"type": "string"
},
"type": {
"type": "string"
},
"category": {
"type": "string"
},
"pose": {
"type": "object",
"properties": {
"position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z"
],
"title": "position",
"additionalProperties": false
},
"orientation": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"w": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z",
"w"
],
"title": "orientation",
"additionalProperties": false
}
},
"required": [
"position",
"orientation"
],
"title": "pose",
"additionalProperties": false
},
"config": {
"type": "string"
},
"data": {
"type": "string"
}
},
"title": "resources"
},
"type": "array"
},
"device": {
"type": "string",
"description": "device reference"
},
"devices": {
"type": "string",
"description": "device reference"
}
},
"required": [],
"_unilabos_placeholder_info": {
"resource": "unilabos_resources",
"resources": "unilabos_resources",
"device": "unilabos_devices",
"devices": "unilabos_devices"
}
},
"goal_default": {},
"placeholder_keys": {
"resource": "unilabos_resources",
"resources": "unilabos_resources",
"device": "unilabos_devices",
"devices": "unilabos_devices"
}
}

View File

@@ -0,0 +1,284 @@
---
name: submit-agent-result
description: Submit historical experiment results (agent_result) to Uni-Lab cloud platform (leap-lab) notebook — read data files, assemble JSON payload, PUT to cloud API. Use when the user wants to submit experiment results, upload agent results, report experiment data, or mentions agent_result/实验结果/历史记录/notebook结果.
---
# Uni-Lab 提交历史实验记录指南
通过 Uni-Lab 云端 API 向已创建的 notebook 提交实验结果数据agent_result。支持从 JSON / CSV 文件读取数据,整合后提交。
> **重要**:本指南中的 `Authorization: Lab <token>` 是 **Uni-Lab 平台专用的认证方式**`Lab` 是 Uni-Lab 的 auth scheme 关键字,**不是** HTTP Basic 认证。请勿将其替换为 `Basic`。
## 前置条件(缺一不可)
使用本指南前,**必须**先确认以下信息。如果缺少任何一项,**立即向用户询问并终止**,等补齐后再继续。
### 1. ak / sk → AUTH
询问用户的启动参数,从 `--ak` `--sk` 或 config.py 中获取。
生成 AUTH token
```bash
# ⚠️ 注意scheme 是 "Lab"Uni-Lab 专用),不是 "Basic"
python -c "import base64,sys; print(base64.b64encode(f'{sys.argv[1]}:{sys.argv[2]}'.encode()).decode())" <ak> <sk>
```
输出即为 token 值,拼接为 `Authorization: Lab <token>``Lab` 是 Uni-Lab 平台 auth scheme不可替换为 `Basic`)。
### 2. --addr → BASE URL
| `--addr` 值 | BASE |
| ------------ | ----------------------------------- |
| `test` | `https://leap-lab.test.bohrium.com` |
| `uat` | `https://leap-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://leap-lab.bohrium.com` |
确认后设置:
```bash
BASE="<根据 addr 确定的 URL>"
# ⚠️ Auth scheme 必须是 "Lab"Uni-Lab 专用),不是 "Basic"
AUTH="Authorization: Lab <上面命令输出的 token>"
```
### 3. notebook_uuid**必须询问用户**
**必须主动询问用户**:「请提供要提交结果的 notebook UUID。」
notebook_uuid 来自之前通过「批量提交实验」创建的实验批次,即 `POST /api/v1/lab/notebook` 返回的 `data.uuid`
如果用户不记得,可提示:
- 查看之前的对话记录中创建 notebook 时返回的 UUID
- 或通过平台页面查找对应的 notebook
**绝不能跳过此步骤,没有 notebook_uuid 无法提交。**
### 4. 实验结果数据
用户需要提供实验结果数据,支持以下方式:
| 方式 | 说明 |
| --------- | ----------------------------------------------- |
| JSON 文件 | 直接作为 `agent_result` 的内容合并 |
| CSV 文件 | 转为 `{"文件名": [行数据...]}` 格式 |
| 手动指定 | 用户直接告知 key-value 数据,由 agent 构建 JSON |
**四项全部就绪后才可开始。**
## Session State
在整个对话过程中agent 需要记住以下状态:
- `lab_uuid` — 实验室 UUID通过 API #1 自动获取,**不需要问用户**
- `notebook_uuid` — 目标 notebook UUID**必须询问用户**
## 请求约定
所有请求使用 `curl -s`PUT 需加 `Content-Type: application/json`
> **Windows 平台**必须使用 `curl.exe`(而非 PowerShell 的 `curl` 别名),示例中的 `curl` 均指 `curl.exe`。
>
> **PowerShell JSON 传参**PowerShell 中 `-d '{"key":"value"}'` 会因引号转义失败。请将 JSON 写入临时文件,用 `-d '@tmp_body.json'`(单引号包裹 `@`,否则 `@` 会被 PowerShell 解析为 splatting 运算符导致报错)。
---
## API Endpoints
### 1. 获取实验室信息(自动获取 lab_uuid
```bash
curl -s -X GET "$BASE/api/v1/edge/lab/info" -H "$AUTH"
```
返回:
```json
{ "code": 0, "data": { "uuid": "xxx", "name": "实验室名称" } }
```
记住 `data.uuid``lab_uuid`
### 2. 提交实验结果agent_result
```bash
curl -s -X PUT "$BASE/api/v1/lab/notebook/agent-result" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '<request_body>'
```
请求体结构:
```json
{
"notebook_uuid": "<notebook_uuid>",
"agent_result": {
"<key1>": "<value1>",
"<key2>": 123,
"<nested_key>": {"a": 1, "b": 2},
"<array_key>": [{"col1": "v1", "col2": "v2"}, ...]
}
}
```
> **注意**HTTP 方法是 **PUT**(不是 POST
#### 必要字段
| 字段 | 类型 | 说明 |
| --------------- | ------------- | ------------------------------------------- |
| `notebook_uuid` | string (UUID) | 目标 notebook 的 UUID从批量提交实验时获取 |
| `agent_result` | object | 实验结果数据,任意 JSON 对象 |
#### agent_result 内容格式
`agent_result` 接受**任意 JSON 对象**,常见格式:
**简单键值对**
```json
{
"avg_rtt_ms": 12.5,
"status": "success",
"test_count": 5
}
```
**包含嵌套结构**
```json
{
"summary": { "total": 100, "passed": 98, "failed": 2 },
"measurements": [
{ "sample_id": "S001", "value": 3.14, "unit": "mg/mL" },
{ "sample_id": "S002", "value": 2.71, "unit": "mg/mL" }
]
}
```
**从 CSV 文件导入**(脚本自动转换):
```json
{
"experiment_data": [
{ "温度": 25, "压力": 101.3, "产率": 0.85 },
{ "温度": 30, "压力": 101.3, "产率": 0.91 }
]
}
```
---
## 整合脚本
本文档同级目录下的 `scripts/prepare_agent_result.py` 可自动读取文件并构建请求体。
### 用法
```bash
python scripts/prepare_agent_result.py \
--notebook-uuid <uuid> \
--files data1.json data2.csv \
[--auth <token>] \
[--base <BASE_URL>] \
[--submit] \
[--output <output.json>]
```
| 参数 | 必选 | 说明 |
| ----------------- | ---------- | ----------------------------------------------- |
| `--notebook-uuid` | 是 | 目标 notebook UUID |
| `--files` | 是 | 输入文件路径支持多个JSON / CSV |
| `--auth` | 提交时必选 | Lab tokenbase64(ak:sk) |
| `--base` | 提交时必选 | API base URL |
| `--submit` | 否 | 加上此标志则直接提交到云端 |
| `--output` | 否 | 输出 JSON 路径(默认 `agent_result_body.json` |
### 文件合并规则
| 文件类型 | 合并方式 |
| --------------------- | -------------------------------------------- |
| `.json`dict | 字段直接合并到 `agent_result` 顶层 |
| `.json`list/other | 以文件名为 key 放入 `agent_result` |
| `.csv` | 以文件名(不含扩展名)为 key值为行对象数组 |
多个文件的字段会合并。JSON dict 中的重复 key 后者覆盖前者。
### 示例
```bash
# 仅生成请求体文件(不提交)
python scripts/prepare_agent_result.py \
--notebook-uuid 73c67dca-c8cc-4936-85a0-329106aa7cca \
--files results.json measurements.csv
# 生成并直接提交
python scripts/prepare_agent_result.py \
--notebook-uuid 73c67dca-c8cc-4936-85a0-329106aa7cca \
--files results.json \
--auth YTFmZDlkNGUt... \
--base https://leap-lab.test.bohrium.com \
--submit
```
---
## 手动构建方式
如果不使用脚本,也可手动构建请求体:
1. 将实验结果数据组装为 JSON 对象
2. 写入临时文件:
```json
{
"notebook_uuid": "<uuid>",
"agent_result": { ... }
}
```
3. 用 curl 提交:
```bash
curl -s -X PUT "$BASE/api/v1/lab/notebook/agent-result" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '@tmp_body.json'
```
---
## 完整工作流 Checklist
```
Task Progress:
- [ ] Step 1: 确认 ak/sk → 生成 AUTH token
- [ ] Step 2: 确认 --addr → 设置 BASE URL
- [ ] Step 3: GET /edge/lab/info → 获取 lab_uuid
- [ ] Step 4: **询问用户** notebook_uuid必须不可跳过
- [ ] Step 5: 确认实验结果数据来源(文件路径或手动数据)
- [ ] Step 6: 运行 prepare_agent_result.py 或手动构建请求体
- [ ] Step 7: PUT /lab/notebook/agent-result 提交
- [ ] Step 8: 检查返回结果,确认提交成功
```
---
## 常见问题
### Q: notebook_uuid 从哪里获取?
从之前「批量提交实验」时 `POST /api/v1/lab/notebook` 的返回值 `data.uuid` 获取。也可以在平台 UI 中查找对应的 notebook。
### Q: agent_result 有固定的 schema 吗?
没有严格 schema接受任意 JSON 对象。但建议包含有意义的字段名和结构化数据,方便后续分析。
### Q: 可以多次提交同一个 notebook 的结果吗?
可以,后续提交会覆盖之前的 agent_result。
### Q: 认证方式是 Lab 还是 Api
本指南统一使用 `Authorization: Lab <base64(ak:sk)>` 方式(`Lab` 是 Uni-Lab 平台的 auth scheme**绝不能用 `Basic` 替代**)。如果用户有独立的 API Key也可用 `Authorization: Api <key>` 替代。

View File

@@ -0,0 +1,133 @@
"""
读取实验结果文件JSON / CSV整合为 agent_result 请求体并可选提交。
用法:
python prepare_agent_result.py \
--notebook-uuid <uuid> \
--files data1.json data2.csv \
[--auth <Lab token>] \
[--base <BASE_URL>] \
[--submit] \
[--output <output.json>]
支持的输入文件格式:
- .json → 直接作为 dict 合并
- .csv → 转为 {"filename": [row_dict, ...]} 格式
"""
import argparse
import base64
import csv
import json
import os
import sys
from pathlib import Path
from typing import Any, Dict, List
def read_json_file(filepath: str) -> Dict[str, Any]:
with open(filepath, "r", encoding="utf-8") as f:
return json.load(f)
def read_csv_file(filepath: str) -> List[Dict[str, Any]]:
rows = []
with open(filepath, "r", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
for row in reader:
converted = {}
for k, v in row.items():
try:
converted[k] = int(v)
except (ValueError, TypeError):
try:
converted[k] = float(v)
except (ValueError, TypeError):
converted[k] = v
rows.append(converted)
return rows
def merge_files(filepaths: List[str]) -> Dict[str, Any]:
"""将多个文件合并为一个 agent_result dict"""
merged: Dict[str, Any] = {}
for fp in filepaths:
path = Path(fp)
ext = path.suffix.lower()
key = path.stem
if ext == ".json":
data = read_json_file(fp)
if isinstance(data, dict):
merged.update(data)
else:
merged[key] = data
elif ext == ".csv":
merged[key] = read_csv_file(fp)
else:
print(f"[警告] 不支持的文件格式: {fp},跳过", file=sys.stderr)
return merged
def build_request_body(notebook_uuid: str, agent_result: Dict[str, Any]) -> Dict[str, Any]:
return {
"notebook_uuid": notebook_uuid,
"agent_result": agent_result,
}
def submit(base: str, auth: str, body: Dict[str, Any]) -> Dict[str, Any]:
try:
import requests
except ImportError:
print("[错误] 提交需要 requests 库: pip install requests", file=sys.stderr)
sys.exit(1)
url = f"{base}/api/v1/lab/notebook/agent-result"
headers = {
"Content-Type": "application/json",
"Authorization": f"Lab {auth}",
}
resp = requests.put(url, json=body, headers=headers, timeout=30)
return {"status_code": resp.status_code, "body": resp.json() if resp.headers.get("content-type", "").startswith("application/json") else resp.text}
def main():
parser = argparse.ArgumentParser(description="整合实验结果文件并构建 agent_result 请求体")
parser.add_argument("--notebook-uuid", required=True, help="目标 notebook UUID")
parser.add_argument("--files", nargs="+", required=True, help="输入文件路径JSON / CSV")
parser.add_argument("--auth", help="Lab tokenbase64(ak:sk)")
parser.add_argument("--base", help="API base URL")
parser.add_argument("--submit", action="store_true", help="直接提交到云端")
parser.add_argument("--output", default="agent_result_body.json", help="输出 JSON 文件路径")
args = parser.parse_args()
for fp in args.files:
if not os.path.exists(fp):
print(f"[错误] 文件不存在: {fp}", file=sys.stderr)
sys.exit(1)
agent_result = merge_files(args.files)
body = build_request_body(args.notebook_uuid, agent_result)
with open(args.output, "w", encoding="utf-8") as f:
json.dump(body, f, ensure_ascii=False, indent=2)
print(f"[完成] 请求体已保存: {args.output}")
print(f" notebook_uuid: {args.notebook_uuid}")
print(f" agent_result 字段数: {len(agent_result)}")
print(f" 合并文件数: {len(args.files)}")
if args.submit:
if not args.auth or not args.base:
print("[错误] 提交需要 --auth 和 --base 参数", file=sys.stderr)
sys.exit(1)
print(f"\n[提交] PUT {args.base}/api/v1/lab/notebook/agent-result ...")
result = submit(args.base, args.auth, body)
print(f" HTTP {result['status_code']}")
print(f" 响应: {json.dumps(result['body'], ensure_ascii=False)}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,272 @@
---
name: virtual-workbench
description: Operate Virtual Workbench via REST API — prepare materials, move to heating stations, start heating, move to output, transfer resources. Use when the user mentions virtual workbench, virtual_workbench, 虚拟工作台, heating stations, material processing, or workbench operations.
---
# Virtual Workbench API Skill
## 设备信息
- **device_id**: `virtual_workbench`
- **Python 源码**: `unilabos/devices/virtual/workbench.py`
- **设备类**: `VirtualWorkbench`
- **动作数**: 6`auto-prepare_materials`, `auto-move_to_heating_station`, `auto-start_heating`, `auto-move_to_output`, `transfer`, `manual_confirm`
- **设备描述**: 模拟工作台,包含 1 个机械臂(每次操作 2s独占锁和 3 个加热台(每次加热 60s可并行
### 典型工作流程
1. `prepare_materials` — 生成 A1-A5 物料5 个 output handle
2. `move_to_heating_station` — 物料并发竞争机械臂,移动到空闲加热台
3. `start_heating` — 启动加热3 个加热台可并行)
4. `move_to_output` — 加热完成后移到输出位置 Cn
## 前置条件(缺一不可)
使用本 skill 前,**必须**先确认以下信息。如果缺少任何一项,**立即向用户询问并终止**,等补齐后再继续。
### 1. ak / sk → AUTH
从启动参数 `--ak` `--sk` 或 config.py 中获取,生成 token`base64(ak:sk)``Authorization: Lab <token>`
### 2. --addr → BASE URL
| `--addr` 值 | BASE |
| ------------ | ----------------------------------- |
| `test` | `https://leap-lab.test.bohrium.com` |
| `uat` | `https://leap-lab.uat.bohrium.com` |
| `local` | `http://127.0.0.1:48197` |
| 不传(默认) | `https://leap-lab.bohrium.com` |
确认后设置:
```bash
BASE="<根据 addr 确定的 URL>"
AUTH="Authorization: Lab <token>"
```
**两项全部就绪后才可发起 API 请求。**
## Session State
- `lab_uuid` — 实验室 UUID首次通过 API #1 自动获取,**不需要问用户**
- `device_name``virtual_workbench`
## 请求约定
所有请求使用 `curl -s`POST/PATCH/DELETE 需加 `Content-Type: application/json`
> **Windows 平台**必须使用 `curl.exe`(而非 PowerShell 的 `curl` 别名)。
---
## API Endpoints
### 1. 获取实验室信息(自动获取 lab_uuid
```bash
curl -s -X GET "$BASE/api/v1/edge/lab/info" -H "$AUTH"
```
返回 `data.uuid``lab_uuid``data.name``lab_name`
### 2. 创建工作流
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/owner" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"name":"<名称>","lab_uuid":"<lab_uuid>","description":"<描述>"}'
```
返回 `data.uuid``workflow_uuid`。创建成功后告知用户链接:`$BASE/laboratory/$lab_uuid/workflow/$workflow_uuid`
### 3. 创建节点
```bash
curl -s -X POST "$BASE/api/v1/edge/workflow/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"workflow_uuid":"<workflow_uuid>","resource_template_name":"virtual_workbench","node_template_name":"<action_name>"}'
```
- `resource_template_name` 固定为 `virtual_workbench`
- `node_template_name` — action 名称(如 `auto-prepare_materials`, `auto-move_to_heating_station`
### 4. 删除节点
```bash
curl -s -X DELETE "$BASE/api/v1/lab/workflow/nodes" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"node_uuids":["<uuid1>"],"workflow_uuid":"<workflow_uuid>"}'
```
### 5. 更新节点参数
```bash
curl -s -X PATCH "$BASE/api/v1/lab/workflow/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"workflow_uuid":"<wf_uuid>","uuid":"<node_uuid>","param":{...}}'
```
参考 [action-index.md](action-index.md) 确定哪些字段是 Slot。
### 6. 查询节点 handles
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/node-handles" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"node_uuids":["<node_uuid_1>","<node_uuid_2>"]}'
```
### 7. 批量创建边
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/edges" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"edges":[{"source_node_uuid":"<uuid>","target_node_uuid":"<uuid>","source_handle_uuid":"<uuid>","target_handle_uuid":"<uuid>"}]}'
```
### 8. 启动工作流
```bash
curl -s -X POST "$BASE/api/v1/lab/workflow/<workflow_uuid>/run" -H "$AUTH"
```
### 9. 运行设备单动作
```bash
curl -s -X POST "$BASE/api/v1/lab/mcp/run/action" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"lab_uuid":"<lab_uuid>","device_id":"virtual_workbench","action":"<action_name>","action_type":"<type>","param":{...}}'
```
`param` 直接放 goal 里的属性,**不要**再包一层 `{"goal": {...}}`
> **WARNING: `action_type` 必须正确,传错会导致任务永远卡住无法完成。** 从下表或 `actions/<name>.json` 的 `type` 字段获取。
#### action_type 速查表
| action | action_type |
|--------|-------------|
| `auto-prepare_materials` | `UniLabJsonCommand` |
| `auto-move_to_heating_station` | `UniLabJsonCommand` |
| `auto-start_heating` | `UniLabJsonCommand` |
| `auto-move_to_output` | `UniLabJsonCommand` |
| `transfer` | `UniLabJsonCommandAsync` |
| `manual_confirm` | `UniLabJsonCommand` |
### 10. 查询任务状态
```bash
curl -s -X GET "$BASE/api/v1/lab/mcp/task/<task_uuid>" -H "$AUTH"
```
### 11. 运行工作流单节点
```bash
curl -s -X POST "$BASE/api/v1/lab/mcp/run/workflow/action" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"node_uuid":"<node_uuid>"}'
```
### 12. 获取资源树(物料信息)
```bash
curl -s -X GET "$BASE/api/v1/lab/material/download/$lab_uuid" -H "$AUTH"
```
注意 `lab_uuid` 在路径中。返回 `data.nodes[]` 含所有节点(设备 + 物料),每个节点含 `name``uuid``type``parent`
### 13. 获取工作流模板详情
```bash
curl -s -X GET "$BASE/api/v1/lab/workflow/template/detail/$workflow_uuid" -H "$AUTH"
```
> 必须使用 `/lab/workflow/template/detail/{uuid}`,其他路径会返回 404。
### 14. 按名称查询物料模板
```bash
curl -s -X GET "$BASE/api/v1/lab/material/template/by-name?lab_uuid=$lab_uuid&name=<template_name>" -H "$AUTH"
```
返回 `data.uuid``res_template_uuid`,用于 API #15
### 15. 创建物料节点
```bash
curl -s -X POST "$BASE/api/v1/edge/material/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"res_template_uuid":"<uuid>","name":"<名称>","display_name":"<显示名>","parent_uuid":"<父节点uuid>","data":{...}}'
```
### 16. 更新物料节点
```bash
curl -s -X PUT "$BASE/api/v1/edge/material/node" \
-H "$AUTH" -H "Content-Type: application/json" \
-d '{"uuid":"<节点uuid>","display_name":"<新名称>","data":{...}}'
```
---
## Placeholder Slot 填写规则
| `placeholder_keys` 值 | Slot 类型 | 填写格式 | 选取范围 |
| --------------------- | ------------ | ----------------------------------------------------- | ---------------------- |
| `unilabos_resources` | ResourceSlot | `{"id": "/path/name", "name": "name", "uuid": "xxx"}` | 仅物料节点(非设备) |
| `unilabos_devices` | DeviceSlot | `"/parent/device_name"` | 仅设备节点type=device |
| `unilabos_nodes` | NodeSlot | `"/parent/node_name"` | 所有节点(设备 + 物料) |
| `unilabos_class` | ClassSlot | `"class_name"` | 注册表中已注册的资源类 |
### virtual_workbench 设备的 Slot 字段表
| Action | 字段 | Slot 类型 | 说明 |
| ----------------- | ---------------- | ------------ | -------------------- |
| `transfer` | `resource` | ResourceSlot | 待转移物料数组 |
| `transfer` | `target_device` | DeviceSlot | 目标设备路径 |
| `transfer` | `mount_resource` | ResourceSlot | 目标孔位数组 |
| `manual_confirm` | `resource` | ResourceSlot | 确认用物料数组 |
| `manual_confirm` | `target_device` | DeviceSlot | 确认用目标设备 |
| `manual_confirm` | `mount_resource` | ResourceSlot | 确认用目标孔位数组 |
> `prepare_materials`、`move_to_heating_station`、`start_heating`、`move_to_output` 这 4 个动作**无 Slot 字段**,参数为纯数值/整数。
---
## 渐进加载策略
1. **SKILL.md**(本文件)— API 端点 + session state 管理 + 设备工作流概览
2. **[action-index.md](action-index.md)** — 按分类浏览 6 个动作的描述和核心参数
3. **[actions/\<name\>.json](actions/)** — 仅在需要构建具体请求时,加载对应 action 的完整 JSON Schema
---
## 完整工作流 Checklist
```
Task Progress:
- [ ] Step 1: GET /edge/lab/info 获取 lab_uuid
- [ ] Step 2: 获取资源树 (GET #12) → 记住可用物料
- [ ] Step 3: 读 action-index.md 确定要用的 action 名
- [ ] Step 4: 创建工作流 (POST #2) → 记住 workflow_uuid告知用户链接
- [ ] Step 5: 创建节点 (POST #3, resource_template_name=virtual_workbench) → 记住 node_uuid + data.param
- [ ] Step 6: 根据 _unilabos_placeholder_info 和资源树,填写 data.param 中的 Slot 字段
- [ ] Step 7: 更新节点参数 (PATCH #5)
- [ ] Step 8: 查询节点 handles (POST #6) → 获取各节点的 handle_uuid
- [ ] Step 9: 批量创建边 (POST #7) → 用 handle_uuid 连接节点
- [ ] Step 10: 启动工作流 (POST #8) 或运行单节点 (POST #11)
- [ ] Step 11: 查询任务状态 (GET #10) 确认完成
```
### 典型 5 物料并发加热工作流示例
```
prepare_materials (count=5)
├─ channel_1 → move_to_heating_station (material_number=1) → start_heating → move_to_output
├─ channel_2 → move_to_heating_station (material_number=2) → start_heating → move_to_output
├─ channel_3 → move_to_heating_station (material_number=3) → start_heating → move_to_output
├─ channel_4 → move_to_heating_station (material_number=4) → start_heating → move_to_output
└─ channel_5 → move_to_heating_station (material_number=5) → start_heating → move_to_output
```
创建节点时,`prepare_materials` 的 5 个 output handle`channel_1` ~ `channel_5`)分别连接到 5 个 `move_to_heating_station` 节点的 `material_input` handle。每个 `move_to_heating_station``heating_station_output``material_number_output` 连接到对应 `start_heating``station_id_input``material_number_input`

View File

@@ -0,0 +1,76 @@
# Action Index — virtual_workbench
6 个动作,按功能分类。每个动作的完整 JSON Schema 在 `actions/<name>.json`
---
## 物料准备
### `auto-prepare_materials`
批量准备物料(虚拟起始节点),生成 A1-A5 物料编号,输出 5 个 handle 供后续节点使用
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/prepare_materials.json`](actions/prepare_materials.json)
- **可选参数**: `count`(物料数量,默认 5
---
## 机械臂 & 加热台操作
### `auto-move_to_heating_station`
将物料从 An 位置移动到空闲加热台(竞争机械臂,自动查找空闲加热台)
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/move_to_heating_station.json`](actions/move_to_heating_station.json)
- **核心参数**: `material_number`物料编号integer
### `auto-start_heating`
启动指定加热台的加热程序可并行3 个加热台同时工作)
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/start_heating.json`](actions/start_heating.json)
- **核心参数**: `station_id`(加热台 ID`material_number`(物料编号)
### `auto-move_to_output`
将加热完成的物料从加热台移动到输出位置 Cn
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/move_to_output.json`](actions/move_to_output.json)
- **核心参数**: `station_id`(加热台 ID`material_number`(物料编号)
---
## 物料转移
### `transfer`
异步转移物料到目标设备(通过 ROS 资源转移)
- **action_type**: `UniLabJsonCommandAsync`
- **Schema**: [`actions/transfer.json`](actions/transfer.json)
- **核心参数**: `resource`, `target_device`, `mount_resource`
- **占位符字段**:
- `resource`**ResourceSlot**,待转移的物料数组 `[{id, name, uuid}, ...]`
- `target_device`**DeviceSlot**,目标设备路径字符串
- `mount_resource`**ResourceSlot**,目标孔位数组 `[{id, name, uuid}, ...]`
---
## 人工确认
### `manual_confirm`
创建人工确认节点,等待用户手动确认后继续(含物料转移上下文)
- **action_type**: `UniLabJsonCommand`
- **Schema**: [`actions/manual_confirm.json`](actions/manual_confirm.json)
- **核心参数**: `resource`, `target_device`, `mount_resource`, `timeout_seconds`, `assignee_user_ids`
- **占位符字段**:
- `resource`**ResourceSlot**,物料数组
- `target_device`**DeviceSlot**,目标设备路径
- `mount_resource`**ResourceSlot**,目标孔位数组
- `assignee_user_ids``unilabos_manual_confirm` 类型

View File

@@ -0,0 +1,270 @@
{
"type": "UniLabJsonCommand",
"goal": {
"resource": "resource",
"target_device": "target_device",
"mount_resource": "mount_resource",
"timeout_seconds": "timeout_seconds",
"assignee_user_ids": "assignee_user_ids"
},
"schema": {
"type": "object",
"properties": {
"resource": {
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"sample_id": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"type": "string"
}
},
"parent": {
"type": "string"
},
"type": {
"type": "string"
},
"category": {
"type": "string"
},
"pose": {
"type": "object",
"properties": {
"position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z"
],
"title": "position",
"additionalProperties": false
},
"orientation": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"w": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z",
"w"
],
"title": "orientation",
"additionalProperties": false
}
},
"required": [
"position",
"orientation"
],
"title": "pose",
"additionalProperties": false
},
"config": {
"type": "string"
},
"data": {
"type": "string"
}
},
"title": "resource"
},
"type": "array"
},
"target_device": {
"type": "string",
"description": "device reference"
},
"mount_resource": {
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"sample_id": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"type": "string"
}
},
"parent": {
"type": "string"
},
"type": {
"type": "string"
},
"category": {
"type": "string"
},
"pose": {
"type": "object",
"properties": {
"position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z"
],
"title": "position",
"additionalProperties": false
},
"orientation": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"w": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z",
"w"
],
"title": "orientation",
"additionalProperties": false
}
},
"required": [
"position",
"orientation"
],
"title": "pose",
"additionalProperties": false
},
"config": {
"type": "string"
},
"data": {
"type": "string"
}
},
"title": "mount_resource"
},
"type": "array"
},
"timeout_seconds": {
"type": "integer"
},
"assignee_user_ids": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"resource",
"target_device",
"mount_resource",
"timeout_seconds",
"assignee_user_ids"
],
"_unilabos_placeholder_info": {
"resource": "unilabos_resources",
"target_device": "unilabos_devices",
"mount_resource": "unilabos_resources",
"assignee_user_ids": "unilabos_manual_confirm"
}
},
"goal_default": {},
"placeholder_keys": {
"resource": "unilabos_resources",
"target_device": "unilabos_devices",
"mount_resource": "unilabos_resources",
"assignee_user_ids": "unilabos_manual_confirm"
}
}

View File

@@ -0,0 +1,19 @@
{
"type": "UniLabJsonCommand",
"goal": {
"material_number": "material_number"
},
"schema": {
"type": "object",
"properties": {
"material_number": {
"type": "integer"
}
},
"required": [
"material_number"
]
},
"goal_default": {},
"placeholder_keys": {}
}

View File

@@ -0,0 +1,24 @@
{
"type": "UniLabJsonCommand",
"goal": {
"station_id": "station_id",
"material_number": "material_number"
},
"schema": {
"type": "object",
"properties": {
"station_id": {
"type": "integer"
},
"material_number": {
"type": "integer"
}
},
"required": [
"station_id",
"material_number"
]
},
"goal_default": {},
"placeholder_keys": {}
}

View File

@@ -0,0 +1,20 @@
{
"type": "UniLabJsonCommand",
"goal": {
"count": "count"
},
"schema": {
"type": "object",
"properties": {
"count": {
"type": "integer",
"default": 5
}
},
"required": []
},
"goal_default": {
"count": 5
},
"placeholder_keys": {}
}

View File

@@ -0,0 +1,24 @@
{
"type": "UniLabJsonCommand",
"goal": {
"station_id": "station_id",
"material_number": "material_number"
},
"schema": {
"type": "object",
"properties": {
"station_id": {
"type": "integer"
},
"material_number": {
"type": "integer"
}
},
"required": [
"station_id",
"material_number"
]
},
"goal_default": {},
"placeholder_keys": {}
}

View File

@@ -0,0 +1,255 @@
{
"type": "UniLabJsonCommandAsync",
"goal": {
"resource": "resource",
"target_device": "target_device",
"mount_resource": "mount_resource"
},
"schema": {
"type": "object",
"properties": {
"resource": {
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"sample_id": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"type": "string"
}
},
"parent": {
"type": "string"
},
"type": {
"type": "string"
},
"category": {
"type": "string"
},
"pose": {
"type": "object",
"properties": {
"position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z"
],
"title": "position",
"additionalProperties": false
},
"orientation": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"w": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z",
"w"
],
"title": "orientation",
"additionalProperties": false
}
},
"required": [
"position",
"orientation"
],
"title": "pose",
"additionalProperties": false
},
"config": {
"type": "string"
},
"data": {
"type": "string"
}
},
"title": "resource"
},
"type": "array"
},
"target_device": {
"type": "string",
"description": "device reference"
},
"mount_resource": {
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"sample_id": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"type": "string"
}
},
"parent": {
"type": "string"
},
"type": {
"type": "string"
},
"category": {
"type": "string"
},
"pose": {
"type": "object",
"properties": {
"position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z"
],
"title": "position",
"additionalProperties": false
},
"orientation": {
"type": "object",
"properties": {
"x": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"y": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"z": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
},
"w": {
"type": "number",
"minimum": -1.7976931348623157e+308,
"maximum": 1.7976931348623157e+308
}
},
"required": [
"x",
"y",
"z",
"w"
],
"title": "orientation",
"additionalProperties": false
}
},
"required": [
"position",
"orientation"
],
"title": "pose",
"additionalProperties": false
},
"config": {
"type": "string"
},
"data": {
"type": "string"
}
},
"title": "mount_resource"
},
"type": "array"
}
},
"required": [
"resource",
"target_device",
"mount_resource"
],
"_unilabos_placeholder_info": {
"resource": "unilabos_resources",
"target_device": "unilabos_devices",
"mount_resource": "unilabos_resources"
}
},
"goal_default": {},
"placeholder_keys": {
"resource": "unilabos_resources",
"target_device": "unilabos_devices",
"mount_resource": "unilabos_resources"
}
}

View File

@@ -0,0 +1,483 @@
---
name: yibin-electrolyte-submit
description: >-
通过 Uni-Lab Notebook API 向宜宾电解液工站提交实验覆盖配液分液Bioyond LIMS
扣电组装CoinCellAssembly、扣电测试全流程。
包含 Excel 解析、formulation 构建、工作流节点参数填写、notebook 提交与状态轮询。
Use when the user wants to submit electrolyte experiments, assemble or test coin cells,
parse experiment Excel files, build notebook payloads, or mentions
宜宾/配液/分液/扣电/电解液实验/notebook提交/CoinCell/BioyondLIMS.
---
# 宜宾电解液产线 API 操作指南
本 skill 覆盖两个设备的完整操作流程:
1. **配液分液工站** (`bioyond_cell_workstation`) — Bioyond LIMS 配液/分液/转运
2. **扣电组装站** (`BatteryStation`) — Modbus PLC 扣电组装/数据采集
## 设备信息
| 属性 | 配液分液工站 | 扣电组装站 |
|------|------------|-----------|
| device_id | `bioyond_cell_workstation` | `BatteryStation` |
| 显示名 | 配液分液工站 | 扣电工作站 |
| 源码 | `unilabos/devices/workstation/bioyond_studio/bioyond_cell/bioyond_cell_workstation.py` | `unilabos/devices/workstation/coin_cell_assembly/coin_cell_assembly.py` |
| 类名 | `BioyondCellWorkstation` | `CoinCellAssemblyWorkstation` |
| 通讯 | HTTP REST (Bioyond LIMS API) | Modbus TCP (PLC 寄存器) |
## 前置条件
### 认证信息
```
AUTH="Authorization: Lab OTdlY2FkNmUtZmZmMi00YjhiLThhOWEtNWM5ODAyOTJmOTUxOmU0OGM2YWJkLTA4ZmEtNDFjMy04NzhhLTc4M2FiODlhZjYxMw=="
BASE="https://uni-lab.test.bohrium.com"
```
来源:`--ak 97ecad6e-fff2-4b8b-8a9a-5c980292f951 --sk e48c6abd-08fa-41c3-878a-783ab89af613 --addr test`
### 启动 unilab云端模式
> **重要**:提交实验前必须确保 unilab 正在运行且已连接云端 WebSocket。
```powershell
$env:PYTHONIOENCODING="utf-8"
conda activate newunilab2603
cd D:\UniLabdev\Uni-Lab-OS\unilabos\devices\workstation
unilab -g D:\UniLabdev\Uni-Lab-OS\yibin_electrolyte_config.json --ak 97ecad6e-fff2-4b8b-8a9a-5c980292f951 --sk e48c6abd-08fa-41c3-878a-783ab89af613 --upload_registry --addr test --disable_browser --skip_env_check
```
**启动要点**
1. 必须先激活虚拟环境 `newunilab2603`
2. 工作目录切到 `unilabos/devices/workstation`(设备驱动所在目录)
3. `--upload_registry` 将 64 个设备 + 142 个资源注册到云端
4. `--skip_env_check` + `PYTHONIOENCODING=utf-8` 避免 Windows GBK 编码崩溃
5. 启动后后台运行,等待日志出现 `Application startup complete``Host node ready signal published with 3 devices`
**验证连接成功的标志**
- 日志出现 `[MessageProcessor] ... wss://uni-lab.test.bohrium.com/api/v1/ws/schedule`
- 日志出现 `[WebSocketClient] Host node ready signal published with 3 devices`
- 日志出现 `Resource tree add completed`(资源树同步完成)
### 云端物料上架与入库(启动后必做)
> **在提交实验之前,必须提醒用户完成以下云端操作,否则实验会因物料缺失而失败。**
1. **拖拽上料**:在云端 UI`$BASE/laboratory/<lab_uuid>`)的资源树视图中,将物料拖拽到对应的仓库/库位上。unilab 启动后资源树会自动同步到云端,但物料的**上架位置**需要用户在 UI 上手动确认或调整。
2. **确认配液物料入库**:确保所有配液实验需要的试剂(如 LiPF6、EC、DMC、EMC 等)已在 LIMS 系统中完成入库。可通过以下方式验证:
- 云端 UI 资源树中对应仓库(如"粉末加样头堆栈"、"配液站内试剂仓库")下有物料节点
- 或通过 API #8 获取资源树后检查物料节点是否存在
3. **告知 AI 可以提交**:用户完成上述操作后,告知 AI "物料已上架,可以提交实验"AI 再执行 notebook 提交流程。
**提醒话术模板**AI 应在启动成功后发送给用户):
```
unilab 已成功启动并连接云端。提交实验前请完成以下操作:
1. 在云端 UI 上确认资源树中的物料位置,必要时拖拽调整上料位
2. 确保配液所需的试剂(粉末、液体)已在 LIMS 中完成入库
3. 完成后告诉我,我将为您提交实验
```
### 生成 Action Schema首次使用
启动 unilab 后,在 `unilabos_data/` 目录下会生成 `req_device_registry_upload.json`。运行以下命令提取两个设备的 action JSON
```bash
python .cursor/skills/create-device-skill/scripts/extract_device_actions.py --registry unilabos_data/req_device_registry_upload.json bioyond_cell_workstation .cursor/skills/yibin-electrolyte-submit/actions/
python .cursor/skills/create-device-skill/scripts/extract_device_actions.py --registry unilabos_data/req_device_registry_upload.json BatteryStation .cursor/skills/yibin-electrolyte-submit/actions/
```
## 请求约定
- Windows 平台**必须用 `curl.exe`**(非 PowerShell 的 curl 别名)
- 所有请求带 `$AUTH`
- URL 格式:`$BASE/api/v1/<endpoint>`
- POST/PATCH 请求体写入临时 JSON 文件后用 `-d '@tmp.json'` 传参(避免 PowerShell 转义问题)
- 本地 API 基址:`http://127.0.0.1:8002/api/v1/`
## Session State
每次会话开始时,依次获取以下信息:
```bash
# 1. lab_uuid
curl.exe -s -X GET "$BASE/api/v1/edge/lab/info" -H "$AUTH"
# → data.uuid → $lab_uuid
# 2. project_uuid
curl.exe -s -X GET "$BASE/api/v1/lab/project/list?lab_uuid=$lab_uuid" -H "$AUTH"
# → data.items[].uuid/name → 让用户选择或取唯一项 → $project_uuid
```
## 工作流模板(重要)
> **必须向用户索要已有的工作流模板 UUID 或 URL不要自行创建。**
>
> 原因:通过 `edge/workflow/node` API 创建节点会报 `resource_node_template not found`——
> 云端的工作流节点模板系统和设备注册表是独立的,需要用户在云端 UI 上预先配置好工作流模板。
**获取方式**
- 用户提供工作流页面 URL`$BASE/laboratory/<lab_uuid>/workflow/<workflow_uuid>`
- 从 URL 中提取 `workflow_uuid`
- 用 API 获取模板详情:
```
GET /api/v1/lab/workflow/template/detail/<workflow_uuid>
```
返回 `data.nodes[]`:每个节点的 uuid、name、param、device_name、handles、disabled。
**示例**
```
工作流 URL: https://uni-lab.test.bohrium.com/laboratory/e9ed9102-d709-4741-b7a0-d1e8578e2065/workflow/b49f80d9-58d6-4456-a521-56f4dd39cda0
→ workflow_uuid = b49f80d9-58d6-4456-a521-56f4dd39cda0
```
从模板详情中提取**未 disabled** 的节点的 `uuid``name`,后续提交 notebook 时使用。
## API Endpoints
### #1 获取 lab_uuid
```
GET /api/v1/edge/lab/info
```
### #2 列出项目
```
GET /api/v1/lab/project/list?lab_uuid=$lab_uuid
```
返回 `data.items[]`,取 `uuid``name`
### #3 获取工作流模板详情
```
GET /api/v1/lab/workflow/template/detail/<workflow_uuid>
```
返回 `data.nodes[]`:每个节点的 uuid、name、param、device_name、handles。
提取活跃节点(`disabled != true`)的 `uuid` 用于构建 notebook 请求。
### #4 提交实验(创建 notebook— 核心 API
```
POST /api/v1/lab/notebook
Body: {
"lab_uuid": "<lab_uuid>",
"project_uuid": "<project_uuid>",
"workflow_uuid": "<workflow_uuid>",
"name": "<实验名称>",
"node_params": [
{
"sample_uuids": [],
"datas": [
{
"node_uuid": "<模板中的节点UUID>",
"param": { <参数键值对> },
"sample_params": []
}
]
}
]
}
```
**关键注意事项**
- `node_params` 是数组,每个元素代表一轮实验
- `datas` 中每个节点对应模板中的一个活跃节点
- `param` 中的字段名**必须使用 Python 函数参数名**,不能用模板中存储的 LIMS 字段名(见下方映射表)
### #5 查询 notebook 状态
```
GET /api/v1/lab/notebook/status?uuid=<notebook_uuid>
```
| status | 含义 |
|--------|------|
| `running` | 执行中 |
| `success` | 成功 |
| `fail` | 失败 |
### #6 运行设备单动作(本地 API
```
POST http://127.0.0.1:8002/api/v1/job/add
Body: {
"device_id": "<device_id>",
"action": "<action_name>",
"action_args": { <参数键值对> },
"sample_material": {}
}
```
本地 API 可自动解析 `action_type`,无需手动指定。适用于快速调试或云端未连接时。
### #7 查询本地任务状态
```
GET http://127.0.0.1:8002/api/v1/job/<job_id>/status
```
| status | 含义 |
|--------|------|
| 0 | UNKNOWN |
| 1 | ACCEPTED |
| 2 | EXECUTING |
| 4 | SUCCEEDED |
| 5 | CANCELED |
| 6 | ABORTED |
### #8 获取资源树
```
GET /api/v1/lab/material/download/<lab_uuid>
```
返回所有节点(`id`, `name`, `uuid`, `type`, `parent`)。填写 Slot 字段时用此接口筛选节点。
## Placeholder Slot 填写规则
action JSON 中 `placeholder_keys` 标记了哪些字段需要填 Slot
| placeholder 值 | Slot 类型 | 填写格式 |
|---------------|-----------|---------|
| `unilabos_resources` | ResourceSlot | `{"id": "/path/name", "name": "name", "uuid": "xxx"}` |
| `unilabos_devices` | DeviceSlot | `"/parent/device_name"` 路径字符串 |
| `unilabos_nodes` | NodeSlot | `"/parent/node_name"` 路径字符串 |
| `unilabos_class` | ClassSlot | `"class_name"` 字符串 |
| `unilabos_formulation` | FormulationSlot | `[{well_name, liquids: [{name, volume}]}]` |
### ResourceSlot 填写
从 API #8 资源树中筛选**物料**节点:
```json
{"id": "/bioyond_cell_workstation/YB_Bioyond_Deck/自动堆栈-左", "name": "自动堆栈-左", "uuid": "3a19debc-..."}
```
数组字段:`[{id, name, uuid}, ...]`
特例:`create_resource``res_id` 允许填不存在的路径。
### DeviceSlot 填写
从资源树筛选 `type=device` 的节点,填路径字符串:
```
"/BatteryStation"
"/bioyond_cell_workstation"
```
### FormulationSlot 填写
```json
[
{
"sample_uuid": "",
"well_name": "YB_PrepBottle_15mL_Carrier_bottle_A1",
"liquids": [
{ "name": "LiPF6", "mass": 12.5 },
{ "name": "EC", "mass": 50.0 }
]
}
]
```
`well_name` 从资源树中取物料节点的 `name`
## 参数名映射(重要的坑)
> 工作流模板中存储的参数名和 Python 函数实际接受的参数名**不一定相同**。
> 提交 notebook 时必须使用 **Python 函数参数名**。
### `create_orders_formulation` 参数映射
| 模板中的 param 键 | 实际 Python 参数名 | 说明 |
|-------------------|-------------------|------|
| `pouch_cell_info` | `pouch_cell_volume` | 软包组装分液体积 (mL) |
| `conductivity_info` | `conductivity_volume` | 电导测试分液体积 (mL) |
| `load_shedding_info` | `coin_cell_volume` | 扣电组装分液体积 (mL) |
| `formulation` | `formulation` | 配方数组(名称一致) |
| `batch_id` | `batch_id` | 批次号(名称一致) |
| `bottle_type` | `bottle_type` | 配液瓶类型(名称一致) |
| `mix_time` | `mix_time` | 混匀时间(秒)(名称一致) |
| `conductivity_bottle_count` | `conductivity_bottle_count` | 电导瓶数(名称一致) |
当从模板中读到 `param` 包含 `pouch_cell_info` 等 LIMS 字段名时,提交 notebook 时要用右列的 Python 函数参数名。否则会报 `TypeError: got an unexpected keyword argument`
## 典型工作流
### 方式一:通过 Notebook API 批量提交(推荐)
**适用场景**:多组配方的批量实验,云端管理实验记录
```
1. 向用户索要工作流模板 URL不要自行创建
2. 获取 lab_uuidAPI #1和 project_uuidAPI #2
3. 获取工作流模板详情API #3提取活跃节点 UUID
4. 解析用户提供的 Excel 文件,构建 formulation 数组
5. 提交 notebookAPI #4
6. 轮询 notebook 状态API #5直到完成
```
**Excel 解析规则**
- 全局参数在第一个数据行:`batch_id``bottle_type``mix_time``coin_cell_volume``pouch_cell_volume``conductivity_volume``conductivity_bottle_count`
- 配方列从"试剂名1"开始,交替排列:试剂名列 + 质量列(以 `(g)` 结尾)
- 每行一个配方,`order_name` = 配方ID列
- formulation 中每个配方的 materials 数组只包含 `mass > 0` 的试剂
**node_params 构建**:所有配方放入同一个 round 的同一个 datas 条目中,因为只有一个节点(`create_orders_formulation`)。
### 方式二:设备单步操作(本地 API
**适用场景**:调试、快速测试
```
1. 确保 unilab 已在本地启动
2. 通过 POST http://127.0.0.1:8002/api/v1/job/add 提交任务
3. 通过 GET /api/v1/job/<job_id>/status 查询状态
```
### 设备操作流程:配液 → 转运 → 扣电
```
1. [配液站] scheduler_start_and_auto_feeding → 启动调度 + 上料
2. [配液站] create_orders_formulation → 创建配液实验(配方输入)
3. [配液站] transfer_3_to_2_to_1_auto → 分液瓶板转运到扣电站
4. [扣电站] func_pack_device_init_auto_start_combined → 初始化+自动+启动
5. [扣电站] func_sendbottle_allpack_multi → 发送瓶数+批量组装
```
## 云端使用心得
### 环境准备
- Windows 必须设置 `$env:PYTHONIOENCODING="utf-8"` 防止编码崩溃
- 使用 `--skip_env_check` 跳过依赖检查,加快启动
- 工作目录建议在 `unilabos/devices/workstation` 下启动
### 连接与注册
- `--upload_registry` 会自动将设备和资源注册到云端
- WebSocket 连接建立后,本地和云端的资源树会自动同步
- 注册成功后用户需在云端 UI 完成**物料拖放上架**操作
- 如果 unilab 断开重连,资源树会重新同步
### 工作流模板
- **不要自行调用 API 创建工作流或节点**——云端工作流节点模板需要预配置
- 始终向用户索要已有的工作流模板 URL
- 从 URL 中提取 `workflow_uuid`,通过 API #3 获取详情
- 模板中 `disabled: true` 的节点跳过,只处理活跃节点
### Notebook 实验提交
- Notebook 是云端管理实验的标准方式
- 一个 notebook 可包含多轮(`node_params` 数组),每轮可包含多组参数
- 提交后通过 API #5 轮询状态LIMS 配液流程通常需要较长时间8 个配方约 30-60 分钟)
- 实验进度可在云端 UI 和本地 unilab 日志中同步查看
### 常见错误
| 错误 | 原因 | 解决 |
|------|------|------|
| `edge not started error` | unilab 未连接云端 WebSocket | 检查 unilab 是否在运行、重启 |
| `resource_node_template not found` | 云端没有该设备的工作流模板 | 向用户索要已有模板,不要自行创建 |
| `got an unexpected keyword argument` | 参数名用了模板字段名而非 Python 函数参数名 | 参照上方映射表转换 |
| `UnicodeEncodeError: 'gbk'` | Windows 默认编码不支持特殊字符 | 设置 `PYTHONIOENCODING=utf-8` |
| `parse parameter error` | 云端 API 字段名错误 | `device_id` (非 `device_name`)、`action` (非 `action_name`)、必须带 `action_type` |
## 渐进加载策略
1. 先读本文件了解 API 端点、参数映射和云端注意事项
2. 需要具体 action 参数时,读 [action-index.md](action-index.md) 查找 action 名称和核心参数
3. 需要完整 schema 时,读 `actions/<action_name>.json`(需先运行提取命令生成)
4. 需要理解参数含义时,读设备源码
## 完整 Notebook 提交 Checklist
```
- [ ] 确认 unilab 已在本地启动并连接云端 WebSocket
- [ ] 提醒用户在云端 UI 拖拽上料、确认物料位置
- [ ] 提醒用户确认配液所需试剂已在 LIMS 完成入库
- [ ] 等待用户确认物料就绪后再继续
- [ ] 向用户索要工作流模板 URL → 提取 workflow_uuid
- [ ] 获取 lab_uuidAPI #1
- [ ] 获取 project_uuidAPI #2
- [ ] 获取工作流模板详情API #3提取活跃节点 UUID
- [ ] 解析用户 Excel 文件 → 构建 formulation + 全局参数
- [ ] 注意参数名映射(模板字段名 → Python 函数参数名)
- [ ] 提交 notebookAPI #4
- [ ] 轮询 notebook 状态API #5直到完成
```
---
## 真实场景:宜宾产线 Excel 提交提示词模板
> 以下为已验证可用的标准提示词,适用于配液-分液-扣电全流程。
### 场景说明
- unilab 运行在本地 Windows 机器miniforge 环境),连接云端 WebSocket
- AICursor / OpenClaw在任意设备上通过云端 API 操作,**不需要本地 127.0.0.1**
- 工作流为 5 节点串联:`create_orders_formulation``transfer_3_to_2_to_1_auto``func_pack_device_init_auto_start_combined``func_sendbottle_allpack_multi``transfer_1_to_2`
### 已知固定参数(宜宾产线)
```
BASE = https://uni-lab.test.bohrium.com
lab_uuid = e9ed9102-d709-4741-b7a0-d1e8578e2065
project = YiBinElectrolyte (bc5224b4-8120-4765-9961-9dfc1802a1f6)
workflow = 配液分液formulation全流程 (2bc59938-db79-4415-ac2d-9897ef125f2f)
```
#### 工作流节点 UUID固定无需重新查询
| 顺序 | action | node_uuid |
|------|--------|-----------|
| Step1 | auto-create_orders_formulation | `ece6744a-81ac-4ae4-8cd1-1c8eeda1dab6` |
| Step2 | auto-transfer_3_to_2_to_1_auto | `1c37a8dd-5ba0-413d-81db-94b9c936a171` |
| Step3 | auto-func_pack_device_init_auto_start_combined | `97a676a2-d257-4479-9096-073b40300970` |
| Step4 | auto-func_sendbottle_allpack_multi | `cf69017a-d29c-4aad-a63b-309d63dac2e9` |
| Step5 | auto-transfer_1_to_2 | `80d1c1aa-dbc3-4601-86b7-5c22a992dd9e` |
### 标准提示词
```
请使用 yibin-electrolyte-submit skill提交以下实验
工作流模板 URLhttps://uni-lab.test.bohrium.com/laboratory/e9ed9102-d709-4741-b7a0-d1e8578e2065/workflow/2bc59938-db79-4415-ac2d-9897ef125f2f
Excel 文件路径:<粘贴或上传 xlsx 路径>
注意事项:
- lab_uuid、project_uuid、workflow节点UUID均已固定无需重新查询
- 直接解析 Excel → 构建 payload → 提交
- mix_time 传标量整数即可(已兼容)
- 试剂名以 Excel 为准,注意区分 LiDFOB / LiDOFB 等拼写
- csv_export_path 取 Excel 中 csv_export_path 列的值
- 提交后告知 notebook UUID无需自动轮询实验耗时较长
```
### Excel 列结构说明experment_template_0415sim-*.xlsx
| 列范围 | 内容 |
|--------|------|
| C | batch_id |
| D | bottle_type |
| E-H | coin_cell_volume / conductivity_bottle_count / conductivity_volume / csv_export_path |
| I-T | 试剂名+质量 交替排列最多6对|
| U | mix_time |
| V | order_name每行配方的订单号|
| W | pouch_cell_volume |
| X-Y | target_device / target_locationStep2参数|
| AA | material_search_enableStep3参数|
| AB-AS | 扣电站参数Step4|
### CSV 导出说明
每次 `create_orders_formulation` 完成后,在 `csv_export_path` 目录下生成:
```
electrolyte_orders_<YYYYMMDD_HHMMSS>.csv
```
列:`orderCode, orderName, 配液瓶类型, 配液瓶二维码, 分液瓶类型, 分液瓶二维码, 目标配液质量比, 真实配液质量比, 时间`
> **注意**barCode 为 `null` 或 `"nullBarCode123456"` 是正常现象,表示 LIMS 中该物料尚未扫码。配液瓶缺失通常是因为物料未放在手动传递窗(`locationId` 前缀 `3a19deae-2c7a-`)。

View File

@@ -0,0 +1,295 @@
# Action 索引
> Action JSON 文件需运行提取命令生成,详见 [SKILL.md](SKILL.md) 中「生成 Action Schema」。
> 以下描述和参数信息基于源码分析。
---
## 配液分液工站 (`bioyond_cell_workstation`)
源码:`unilabos/devices/workstation/bioyond_studio/bioyond_cell/bioyond_cell_workstation.py`
### 调度控制
#### `scheduler_start`
启动 Bioyond LIMS 调度系统
- **核心参数**: 无(仅需 apiKey/requestTime由设备内部处理
- **返回**: LIMS 响应 `{code, message, data}`
#### `scheduler_stop`
停止调度
- **核心参数**: 无
#### `scheduler_continue`
继续调度(从暂停状态恢复)
- **核心参数**: 无
#### `scheduler_reset`
复位调度
- **核心参数**: 无
#### `scheduler_start_and_auto_feeding`
**组合操作**:启动调度 + 自动化上料4号→3号手套箱
- **核心参数**: `xlsx_path`Excel 物料模板路径,可选)
- **可选参数**: WH4 加样头面 12 个点位materialName + quantity、WH4 原液瓶面 9 个点位materialName + quantity + materialType + targetWH、WH3 人工堆栈 15 个点位materialType + materialId + quantity
- **流程**: 先 `scheduler_start()`,成功后执行 `auto_feeding4to3()`
- **备注**: 支持 Excel 模式和手动参数模式Excel 路径存在时优先使用 Excel
### 物料上料/下料
#### `auto_feeding4to3`
自动化上料:从 4 号手套箱转运物料到 3 号手套箱
- **核心参数**: `xlsx_path`Excel 物料模板路径)
- **可选参数**: 同 `scheduler_start_and_auto_feeding` 的 WH4/WH3 点位参数
- **返回**: 等待上料任务完成后返回结果
#### `auto_batch_outbound_from_xlsx`
自动化下料(从 Excel 读取下料信息)
- **核心参数**: `xlsx_path`Excel 下料模板)
- **Excel 列**: locationId, warehouseId, 数量, x, y, z
### 物料管理
#### `create_and_inbound_materials`
批量创建固体物料并入库
- **核心参数**: `material_names`(物料名称列表,默认 `["LiPF6", "LiDFOB", "DTD", "LiFSI", "LiPO2F2"]`
- **可选参数**: `type_id`物料类型ID, `warehouse_name`(目标仓库,默认 "粉末加样头堆栈"
- **流程**: 创建物料 → 批量入库 → 同步
#### `create_material`
创建单个物料并可选入库
- **核心参数**: `material_name`, `type_id`, `warehouse_name`
- **可选参数**: `location_name_or_id`(库位编号如 "A01" 或 UUID
#### `create_sample`
创建配液板物料(含子瓶)并入库
- **核心参数**: `name`, `board_type`(如 "5ml分液瓶板", `bottle_type`(如 "5ml分液瓶", `location_code`(如 "A01"
- **可选参数**: `warehouse_name`(默认 "手动堆栈"
- **备注**: 自动创建 2x4=8 个子瓶
#### `storage_inbound`
单个物料入库
- **核心参数**: `material_id`, `location_id`
#### `storage_batch_inbound`
批量物料入库
- **核心参数**: `items``[{materialId, locationId}, ...]`
### 配液实验
#### `create_orders`
从 Excel 文件创建配液实验订单
- **核心参数**: `xlsx_path`Excel 文件路径)
- **Excel 列**: 配方ID, 创建日期, 配液瓶类型, 混匀时间(s), 扣电组装分液体积, 软包组装分液体积, 电导测试分液体积, 电导测试分液瓶数, 以及所有以 `(g)` 结尾的物料列
- **流程**: 解析 Excel → 提交订单 → 等待全部完成 → 计算质量比 → 提取分液瓶板 → 创建资源树对象
- **返回**: `{status, total_orders, bottle_count, reports, mass_ratios, vial_plates}`
#### `create_orders_formulation`
从配方列表创建配液实验订单(前端/API 输入版本)
- **核心参数**: `formulation`(配方数组)
- **可选参数**: `batch_id`, `bottle_type`(默认 "配液小瓶", `mix_time`(秒,列表), `coin_cell_volume`, `pouch_cell_volume`, `conductivity_volume`, `conductivity_bottle_count`
- **formulation 格式**:
```json
[
{
"order_name": "配方A",
"materials": [
{"name": "LiPF6", "mass": 12.5},
{"name": "EC", "mass": 50.0},
{"name": "DMC", "mass": 37.5}
]
}
]
```
- **返回**: 同 `create_orders`
### 物料转运
#### `transfer_3_to_2_to_1_auto`
**自动转运**:从 create_orders 结果中自动定位分液瓶板并转运到目标设备
- **核心参数**: `vial_plates`(分液瓶板列表,来自 create_orders 返回的 `vial_plates`
- **可选参数**: `target_device`(默认 "BatteryStation", `target_location`(默认 "bottle_rack_6x2", `mass_ratios`(配方信息)
- **流程**: 遍历瓶板 → 解析 locationId → 调用 LIMS 转运 API → 更新资源树
- **返回**: `{total, success, failed, results}`
#### `transfer_3_to_2_to_1`
3→2→1 物料转运(手动指定坐标)
- **核心参数**: `source_wh_id`, `source_x`, `source_y`, `source_z`
#### `transfer_3_to_2`
3→2 物料转运
- **核心参数**: `source_wh_id`, `source_x`, `source_y`, `source_z`
#### `transfer_1_to_2`
1→2 物料转运
- **核心参数**: 无
### 查询
#### `order_list_v2`
批量查询实验报告
- **可选参数**: `timeType`, `beginTime`, `endTime`, `status`60=运行中, 80=完成, 90=失败), `filter`, `skipCount`, `pageCount`, `sorting`
---
## 扣电组装站 (`BatteryStation`)
源码:`unilabos/devices/workstation/coin_cell_assembly/coin_cell_assembly.py`
### 设备控制(组合操作)
#### `func_pack_device_init_auto_start_combined`
**组合操作**:设备初始化 → 物料搜寻确认 → 切换自动模式 → 启动
- **核心参数**: `material_search_enable`(是否启用物料搜寻,默认 `False`
- **前置检查**: REG_UNILAB_INTERACT=False, COIL_GB_L_IGNORE_CMD=False, 所有握手寄存器无残留
- **流程**: 手动模式 → 初始化命令 → 监测物料搜寻弹窗并自动处理 → 自动模式 → 启动
- **返回**: `True`/`False`
- **备注**: 第一次运行必须调用此函数;后续批次调用 `func_sendbottle_allpack_multi`
### 批量组装
#### `func_sendbottle_allpack_multi`
**发送瓶数 + 批量组装**(适用于第二批次及后续批次)
- **核心参数**: `elec_num`(电解液瓶数), `elec_use_num`(每瓶组装电池数), `elec_vol`(电解液吸液量 μL默认 50
- **可选参数**:
- 双滴模式:`dual_drop_mode`(bool), `dual_drop_first_volume`(μL), `dual_drop_suction_timing`(bool), `dual_drop_start_timing`(bool)
- 组装参数:`assembly_type`(7=不用铝箔垫/8=用), `assembly_pressure`(N默认 4200)
- 物料参数:`fujipian_panshu`, `fujipian_juzhendianwei`, `gemopanshu`, `gemo_juzhendianwei`, `qiangtou_juzhendianwei`
- 开关:`lvbodian`(铝箔垫片), `battery_pressure_mode`(压力模式), `battery_clean_ignore`(忽略清洁)
- 其他:`file_path`(CSV保存路径), `formulations`(配方信息用于CSV追溯)
- **流程**: 发送瓶数触发物料搬运 → 设置PLC参数 → 循环等待PLC请求→下发参数→读取电池数据→写入CSV→更新资源树→ 完成握手
- **返回**: `{success, total_batteries, batteries, summary}`
- **备注**: 设备已初始化后直接调用;`formulations` 来自 create_orders 的 `mass_ratios`
#### `func_allpack_cmd`
全套组装(基础版本,含断点续传)
- **核心参数**: `elec_num`, `elec_use_num`, `elec_vol`, `assembly_type`, `assembly_pressure`, `file_path`
- **返回**: `{success, total_batteries, batteries, summary}`
#### `func_allpack_cmd_simp`
增强版组装(含双滴模式 + 负极片/隔膜/枪头参数)
- **核心参数**: 同 `func_sendbottle_allpack_multi`
- **备注**: 被 `func_sendbottle_allpack_multi` 内部调用
### 设备控制(单步操作)
#### `func_pack_device_init`
设备初始化(手动模式 → 初始化 → 复位标志)
#### `func_pack_device_auto`
切换自动模式
#### `func_pack_device_start`
启动设备
#### `func_pack_device_stop`
设备停止
#### `func_pack_send_bottle_num`
发送电解液瓶数(触发物料搬运)
- **核心参数**: `bottle_num`(瓶数)
### PLC 参数设置
#### `qiming_coin_cell_code`
设置组装物料参数
- **核心参数**: `fujipian_panshu`(负极片盘数)
- **可选参数**: `fujipian_juzhendianwei`, `gemopanshu`, `gemo_juzhendianwei`, `lvbodian`, `battery_pressure_mode`, `battery_pressure`, `battery_clean_ignore`
### 数据采集
#### `func_read_data_and_output`
持续数据采集并导出 CSV后台循环运行
- **核心参数**: `file_path`CSV 保存目录)
- **采集字段**: 开路电压, 极片质量, 组装时间, 压制力, 电解液加注量, 电池类型, 电解液二维码, 电池二维码
#### `func_stop_read_data`
停止 CSV 数据采集
### 设备状态属性(只读)
| 属性 | 类型 | 说明 |
|------|------|------|
| `sys_status` | str | 设备状态(启动中/停止中/复位中/初始化中) |
| `sys_mode` | str | 设备模式(手动/自动) |
| `data_assembly_coin_cell_num` | int | 已完成电池数量 |
| `data_assembly_time` | float | 单颗电池组装时间(秒) |
| `data_open_circuit_voltage` | float | 开路电压(V) |
| `data_pole_weight` | float | 正极片称重(g) |
| `data_glove_box_pressure` | float | 手套箱压力(mbar) |
| `data_glove_box_o2_content` | float | 手套箱氧含量(ppm) |
| `data_glove_box_water_content` | float | 手套箱水含量(ppm) |
| `data_coin_cell_code` | str | 电池二维码 |
| `data_electrolyte_code` | str | 电解液二维码 |
---
## 配置参考
设备图文件 `yibin_electrolyte_config.json` 中的仓库映射(`warehouse_mapping`
| 仓库名称 | 说明 | 典型操作 |
|---------|------|---------|
| 粉末加样头堆栈 | 20 个点位 (A01-T01) | `create_and_inbound_materials` 入库目标 |
| 配液站内试剂仓库 | 9 个点位 (A01-C03) | 试剂存储 |
| 自动堆栈-左 | 4 个点位 | 分液瓶板存放,`transfer_3_to_2_to_1_auto` 的源位置 |
| 自动堆栈-右 | 4 个点位 | 分液瓶板存放 |
| 手动传递窗左/右 | 各 15 个点位 | 人工上料/下料 |
| 4号手套箱内部堆栈 | 12 个点位 | `auto_feeding4to3` 的源位置 |

View File

@@ -38,7 +38,7 @@ jobs:
- name: Install ROS dependencies, uv and unilabos-msgs
run: |
echo Installing ROS dependencies...
mamba install -n check-env conda-forge::uv conda-forge::opencv robostack-staging::ros-humble-ros-core robostack-staging::ros-humble-action-msgs robostack-staging::ros-humble-std-msgs robostack-staging::ros-humble-geometry-msgs robostack-staging::ros-humble-control-msgs robostack-staging::ros-humble-nav2-msgs uni-lab::ros-humble-unilabos-msgs robostack-staging::ros-humble-cv-bridge robostack-staging::ros-humble-vision-opencv robostack-staging::ros-humble-tf-transformations robostack-staging::ros-humble-moveit-msgs robostack-staging::ros-humble-tf2-ros robostack-staging::ros-humble-tf2-ros-py conda-forge::transforms3d -c robostack-staging -c conda-forge -c uni-lab -y
mamba install -n check-env --override-channels -c robostack-staging -c conda-forge -c uni-lab conda-forge::uv conda-forge::opencv robostack-staging::ros-humble-ros-core robostack-staging::ros-humble-action-msgs robostack-staging::ros-humble-std-msgs robostack-staging::ros-humble-geometry-msgs robostack-staging::ros-humble-control-msgs robostack-staging::ros-humble-nav2-msgs uni-lab::ros-humble-unilabos-msgs robostack-staging::ros-humble-cv-bridge robostack-staging::ros-humble-vision-opencv robostack-staging::ros-humble-tf-transformations robostack-staging::ros-humble-moveit-msgs robostack-staging::ros-humble-tf2-ros robostack-staging::ros-humble-tf2-ros-py conda-forge::transforms3d -y
- name: Install pip dependencies and unilabos
run: |

View File

@@ -1,6 +1,10 @@
name: Build Conda-Pack Environment
on:
# 在 UniLabOS Conda Build 成功上传后自动构建非全量 conda-pack
workflow_run:
workflows: ["UniLabOS Conda Build"]
types: [completed]
workflow_dispatch:
inputs:
branch:
@@ -21,6 +25,16 @@ on:
jobs:
build-conda-pack:
if: |
github.event_name == 'workflow_dispatch' ||
(
github.event_name == 'workflow_run' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'workflow_run'
)
env:
BUILD_FULL: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.build_full == 'true' }}
PACKAGE_REF: ${{ github.event.inputs.branch || github.event.workflow_run.head_sha || github.ref_name }}
strategy:
fail-fast: false
matrix:
@@ -54,7 +68,9 @@ jobs:
id: should_build
shell: bash
run: |
if [[ -z "${{ github.event.inputs.platforms }}" ]]; then
if [[ "${{ github.event_name }}" != "workflow_dispatch" ]]; then
echo "should_build=true" >> $GITHUB_OUTPUT
elif [[ -z "${{ github.event.inputs.platforms }}" ]]; then
echo "should_build=true" >> $GITHUB_OUTPUT
elif [[ "${{ github.event.inputs.platforms }}" == *"${{ matrix.platform }}"* ]]; then
echo "should_build=true" >> $GITHUB_OUTPUT
@@ -65,7 +81,7 @@ jobs:
- uses: actions/checkout@v6
if: steps.should_build.outputs.should_build == 'true'
with:
ref: ${{ github.event.inputs.branch }}
ref: ${{ github.event.inputs.branch || github.event.workflow_run.head_sha || github.ref }}
fetch-depth: 0
- name: Setup Miniforge (with mamba)
@@ -75,7 +91,7 @@ jobs:
miniforge-version: latest
use-mamba: true
python-version: '3.11.14'
channels: conda-forge,robostack-staging,uni-lab,defaults
channels: conda-forge,robostack-staging,uni-lab
channel-priority: flexible
activate-environment: unilab
auto-update-conda: false
@@ -86,13 +102,13 @@ jobs:
run: |
echo Installing unilabos and dependencies to unilab environment...
echo Using mamba for faster and more reliable dependency resolution...
echo Build full: ${{ github.event.inputs.build_full }}
if "${{ github.event.inputs.build_full }}"=="true" (
echo Build full: ${{ env.BUILD_FULL }}
if "${{ env.BUILD_FULL }}"=="true" (
echo Installing unilabos-full ^(complete package^)...
mamba install -n unilab uni-lab::unilabos-full conda-pack -c uni-lab -c robostack-staging -c conda-forge -y
mamba install -n unilab --override-channels -c uni-lab -c robostack-staging -c conda-forge uni-lab::unilabos-full conda-pack zstandard -y
) else (
echo Installing unilabos ^(minimal package^)...
mamba install -n unilab uni-lab::unilabos conda-pack -c uni-lab -c robostack-staging -c conda-forge -y
mamba install -n unilab --override-channels -c uni-lab -c robostack-staging -c conda-forge uni-lab::unilabos conda-pack zstandard -y
)
- name: Install conda-pack, unilabos and dependencies (Unix)
@@ -101,13 +117,13 @@ jobs:
run: |
echo "Installing unilabos and dependencies to unilab environment..."
echo "Using mamba for faster and more reliable dependency resolution..."
echo "Build full: ${{ github.event.inputs.build_full }}"
if [[ "${{ github.event.inputs.build_full }}" == "true" ]]; then
echo "Build full: ${{ env.BUILD_FULL }}"
if [[ "${{ env.BUILD_FULL }}" == "true" ]]; then
echo "Installing unilabos-full (complete package)..."
mamba install -n unilab uni-lab::unilabos-full conda-pack -c uni-lab -c robostack-staging -c conda-forge -y
mamba install -n unilab --override-channels -c uni-lab -c robostack-staging -c conda-forge uni-lab::unilabos-full conda-pack zstandard -y
else
echo "Installing unilabos (minimal package)..."
mamba install -n unilab uni-lab::unilabos conda-pack -c uni-lab -c robostack-staging -c conda-forge -y
mamba install -n unilab --override-channels -c uni-lab -c robostack-staging -c conda-forge uni-lab::unilabos conda-pack zstandard -y
fi
- name: Get latest ros-humble-unilabos-msgs version (Windows)
@@ -134,27 +150,27 @@ jobs:
if: steps.should_build.outputs.should_build == 'true' && matrix.platform == 'win-64'
run: |
echo Checking for available ros-humble-unilabos-msgs versions...
mamba search ros-humble-unilabos-msgs -c uni-lab -c robostack-staging -c conda-forge || echo Search completed
mamba search --override-channels -c uni-lab -c robostack-staging -c conda-forge ros-humble-unilabos-msgs || echo Search completed
echo.
echo Updating ros-humble-unilabos-msgs to latest version...
mamba update -n unilab ros-humble-unilabos-msgs -c uni-lab -c robostack-staging -c conda-forge -y || echo Already at latest version
mamba update -n unilab --override-channels -c uni-lab -c robostack-staging -c conda-forge ros-humble-unilabos-msgs -y || echo Already at latest version
- name: Check for newer ros-humble-unilabos-msgs (Unix)
if: steps.should_build.outputs.should_build == 'true' && matrix.platform != 'win-64'
shell: bash
run: |
echo "Checking for available ros-humble-unilabos-msgs versions..."
mamba search ros-humble-unilabos-msgs -c uni-lab -c robostack-staging -c conda-forge || echo "Search completed"
mamba search --override-channels -c uni-lab -c robostack-staging -c conda-forge ros-humble-unilabos-msgs || echo "Search completed"
echo ""
echo "Updating ros-humble-unilabos-msgs to latest version..."
mamba update -n unilab ros-humble-unilabos-msgs -c uni-lab -c robostack-staging -c conda-forge -y || echo "Already at latest version"
mamba update -n unilab --override-channels -c uni-lab -c robostack-staging -c conda-forge ros-humble-unilabos-msgs -y || echo "Already at latest version"
- name: Install latest unilabos from source (Windows)
if: steps.should_build.outputs.should_build == 'true' && matrix.platform == 'win-64'
run: |
echo Uninstalling existing unilabos...
mamba run -n unilab pip uninstall unilabos -y || echo unilabos not installed via pip
echo Installing unilabos from source (branch: ${{ github.event.inputs.branch }})...
echo Installing unilabos from source (ref: ${{ env.PACKAGE_REF }})...
mamba run -n unilab pip install .
echo Verifying installation...
mamba run -n unilab pip show unilabos
@@ -165,7 +181,7 @@ jobs:
run: |
echo "Uninstalling existing unilabos..."
mamba run -n unilab pip uninstall unilabos -y || echo "unilabos not installed via pip"
echo "Installing unilabos from source (branch: ${{ github.event.inputs.branch }})..."
echo "Installing unilabos from source (ref: ${{ env.PACKAGE_REF }})..."
mamba run -n unilab pip install .
echo "Verifying installation..."
mamba run -n unilab pip show unilabos
@@ -226,7 +242,9 @@ jobs:
if: steps.should_build.outputs.should_build == 'true' && matrix.platform == 'win-64'
run: |
echo Packing unilab environment with conda-pack...
mamba activate unilab && conda pack -n unilab -o unilab-env-${{ matrix.platform }}.tar.gz --ignore-missing-files
for /f "delims=" %%i in ('mamba run -n unilab python -c "import os; print(os.environ['CONDA_PREFIX'])"') do set "UNILAB_PREFIX=%%i"
echo Packing environment at: %UNILAB_PREFIX%
mamba run -n unilab conda-pack -p "%UNILAB_PREFIX%" -o unilab-env-${{ matrix.platform }}.tar.gz --ignore-missing-files
echo Pack file created:
dir unilab-env-${{ matrix.platform }}.tar.gz
@@ -235,8 +253,9 @@ jobs:
shell: bash
run: |
echo "Packing unilab environment with conda-pack..."
mamba install conda-pack -c conda-forge -y
conda pack -n unilab -o unilab-env-${{ matrix.platform }}.tar.gz --ignore-missing-files
UNILAB_PREFIX="$(mamba run -n unilab python -c 'import os; print(os.environ["CONDA_PREFIX"])')"
echo "Packing environment at: $UNILAB_PREFIX"
mamba run -n unilab conda-pack -p "$UNILAB_PREFIX" -o unilab-env-${{ matrix.platform }}.tar.gz --ignore-missing-files
echo "Pack file created:"
ls -lh unilab-env-${{ matrix.platform }}.tar.gz
@@ -267,7 +286,7 @@ jobs:
rem Create README using Python script
echo Creating: README.txt
python scripts\create_readme.py ${{ matrix.platform }} ${{ github.event.inputs.branch }} dist-package\README.txt
python scripts\create_readme.py ${{ matrix.platform }} ${{ env.PACKAGE_REF }} dist-package\README.txt
echo.
echo Distribution package contents:
@@ -303,7 +322,7 @@ jobs:
# Create README using Python script
echo "Creating: README.txt"
python scripts/create_readme.py ${{ matrix.platform }} ${{ github.event.inputs.branch }} dist-package/README.txt
python scripts/create_readme.py ${{ matrix.platform }} ${{ env.PACKAGE_REF }} dist-package/README.txt
echo ""
echo "Distribution package contents:"
@@ -314,7 +333,7 @@ jobs:
if: steps.should_build.outputs.should_build == 'true'
uses: actions/upload-artifact@v6
with:
name: unilab-pack-${{ matrix.platform }}-${{ github.event.inputs.branch }}
name: unilab-pack-${{ matrix.platform }}-${{ env.PACKAGE_REF }}
path: dist-package/
retention-days: 90
if-no-files-found: error
@@ -326,9 +345,9 @@ jobs:
echo Build Summary
echo ==========================================
echo Platform: ${{ matrix.platform }}
echo Branch: ${{ github.event.inputs.branch }}
echo Branch: ${{ env.PACKAGE_REF }}
echo Python version: 3.11.14
if "${{ github.event.inputs.build_full }}"=="true" (
if "${{ env.BUILD_FULL }}"=="true" (
echo Package: unilabos-full ^(complete^)
) else (
echo Package: unilabos ^(minimal^)
@@ -337,7 +356,7 @@ jobs:
echo Distribution package contents:
dir dist-package
echo.
echo Artifact name: unilab-pack-${{ matrix.platform }}-${{ github.event.inputs.branch }}
echo Artifact name: unilab-pack-${{ matrix.platform }}-${{ env.PACKAGE_REF }}
echo.
echo After download, extract the ZIP and run:
echo install_unilab.bat
@@ -351,9 +370,9 @@ jobs:
echo "Build Summary"
echo "=========================================="
echo "Platform: ${{ matrix.platform }}"
echo "Branch: ${{ github.event.inputs.branch }}"
echo "Branch: ${{ env.PACKAGE_REF }}"
echo "Python version: 3.11.14"
if [[ "${{ github.event.inputs.build_full }}" == "true" ]]; then
if [[ "${{ env.BUILD_FULL }}" == "true" ]]; then
echo "Package: unilabos-full (complete)"
else
echo "Package: unilabos (minimal)"
@@ -362,7 +381,7 @@ jobs:
echo "Distribution package contents:"
ls -lh dist-package/
echo ""
echo "Artifact name: unilab-pack-${{ matrix.platform }}-${{ github.event.inputs.branch }}"
echo "Artifact name: unilab-pack-${{ matrix.platform }}-${{ env.PACKAGE_REF }}"
echo ""
echo "After download:"
echo " install_unilab.sh"

View File

@@ -56,7 +56,7 @@ jobs:
miniforge-version: latest
use-mamba: true
python-version: '3.11.14'
channels: conda-forge,robostack-staging,uni-lab,defaults
channels: conda-forge,robostack-staging,uni-lab
channel-priority: flexible
activate-environment: unilab
auto-update-conda: false
@@ -66,7 +66,7 @@ jobs:
run: |
echo "Installing unilabos and dependencies to unilab environment..."
echo "Using mamba for faster and more reliable dependency resolution..."
mamba install -n unilab uni-lab::unilabos -c uni-lab -c robostack-staging -c conda-forge -y
mamba install -n unilab --override-channels -c uni-lab -c robostack-staging -c conda-forge uni-lab::unilabos -y
- name: Install latest unilabos from source
run: |

View File

@@ -10,6 +10,9 @@ on:
# 支持 tag 推送(不依赖 CI Check
push:
tags: ['v*']
# GitHub Release 发布时自动构建并上传
release:
types: [published]
# 手动触发
workflow_dispatch:
inputs:
@@ -80,7 +83,7 @@ jobs:
- uses: actions/checkout@v6
with:
# 如果是 workflow_run 触发,使用触发 CI Check 的 commit
ref: ${{ github.event.workflow_run.head_sha || github.ref }}
ref: ${{ github.event.workflow_run.head_sha || github.event.release.tag_name || github.ref }}
fetch-depth: 0
- name: Check if platform should be built
@@ -96,12 +99,14 @@ jobs:
echo "should_build=false" >> $GITHUB_OUTPUT
fi
- name: Setup Miniconda
- name: Setup Miniforge
if: steps.should_build.outputs.should_build == 'true'
uses: conda-incubator/setup-miniconda@v3
with:
miniconda-version: 'latest'
channels: conda-forge,robostack-staging,defaults
miniforge-version: latest
use-mamba: true
python-version: '3.11.14'
channels: conda-forge,robostack-staging
channel-priority: strict
activate-environment: build-env
auto-update-conda: false
@@ -110,13 +115,15 @@ jobs:
- name: Install rattler-build and anaconda-client
if: steps.should_build.outputs.should_build == 'true'
run: |
conda install -c conda-forge rattler-build anaconda-client
mamba install -n build-env --override-channels -c conda-forge rattler-build anaconda-client -y
- name: Show environment info
if: steps.should_build.outputs.should_build == 'true'
run: |
conda info
conda list | grep -E "(rattler-build|anaconda-client)"
conda list -n build-env | grep -E "(rattler-build|anaconda-client)"
conda run -n build-env rattler-build --version
conda run -n build-env anaconda --version
echo "Platform: ${{ matrix.platform }}"
echo "OS: ${{ matrix.os }}"
@@ -124,9 +131,9 @@ jobs:
if: steps.should_build.outputs.should_build == 'true'
run: |
if [[ "${{ matrix.platform }}" == "osx-arm64" ]]; then
rattler-build build -r ./recipes/msgs/recipe.yaml -c robostack -c robostack-staging -c conda-forge
conda run -n build-env rattler-build build -r ./recipes/msgs/recipe.yaml -c robostack -c robostack-staging -c conda-forge
else
rattler-build build -r ./recipes/msgs/recipe.yaml -c robostack -c robostack-staging -c conda-forge
conda run -n build-env rattler-build build -r ./recipes/msgs/recipe.yaml -c robostack -c robostack-staging -c conda-forge
fi
- name: List built packages
@@ -157,9 +164,15 @@ jobs:
retention-days: 30
- name: Upload to Anaconda.org (unilab organization)
if: steps.should_build.outputs.should_build == 'true' && github.event.inputs.upload_to_anaconda == 'true'
if: |
steps.should_build.outputs.should_build == 'true' &&
(
github.event_name == 'release' ||
startsWith(github.ref, 'refs/tags/') ||
github.event.inputs.upload_to_anaconda == 'true'
)
run: |
for package in $(find ./output -name "*.conda"); do
echo "Uploading $package to unilab organization..."
anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
conda run -n build-env anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
done

View File

@@ -1,14 +1,10 @@
name: UniLabOS Conda Build
on:
# 在 CI Check 成功后自动触发
# 在 Multi-Platform Conda Build 成功上传 msgs 后自动触发
workflow_run:
workflows: ["CI Check"]
workflows: ["Multi-Platform Conda Build"]
types: [completed]
branches: [main, dev]
# 标签推送时直接触发(发布版本)
push:
tags: ['v*']
# 手动触发
workflow_dispatch:
inputs:
@@ -33,30 +29,30 @@ on:
type: boolean
jobs:
# 等待 CI Check 完成的 job (仅用于 workflow_run 触发)
wait-for-ci:
# 等待上游 msgs 构建完成的 job (仅用于 workflow_run 触发)
wait-for-upstream:
runs-on: ubuntu-latest
if: github.event_name == 'workflow_run'
outputs:
should_continue: ${{ steps.check.outputs.should_continue }}
steps:
- name: Check CI status
- name: Check upstream workflow status
id: check
run: |
if [[ "${{ github.event.workflow_run.conclusion }}" == "success" ]]; then
if [[ "${{ github.event.workflow_run.conclusion }}" == "success" && ( "${{ github.event.workflow_run.event }}" == "release" || "${{ github.event.workflow_run.event }}" == "push" ) ]]; then
echo "should_continue=true" >> $GITHUB_OUTPUT
echo "CI Check passed, proceeding with build"
echo "Multi-Platform Conda Build passed for release/tag, proceeding with UniLabOS build"
else
echo "should_continue=false" >> $GITHUB_OUTPUT
echo "CI Check did not succeed (status: ${{ github.event.workflow_run.conclusion }}), skipping build"
echo "Upstream workflow is not a successful release/tag build (status: ${{ github.event.workflow_run.conclusion }}, event: ${{ github.event.workflow_run.event }}), skipping build"
fi
build:
needs: [wait-for-ci]
# 运行条件workflow_run 触发且 CI 成功,或者其他触发方式
needs: [wait-for-upstream]
# 运行条件workflow_run 触发且上游成功,或者手动触发
if: |
always() &&
(needs.wait-for-ci.result == 'skipped' || needs.wait-for-ci.outputs.should_continue == 'true')
(needs.wait-for-upstream.result == 'skipped' || needs.wait-for-upstream.outputs.should_continue == 'true')
strategy:
fail-fast: false
matrix:
@@ -79,7 +75,7 @@ jobs:
steps:
- uses: actions/checkout@v6
with:
# 如果是 workflow_run 触发,使用触发 CI Check 的 commit
# 如果是 workflow_run 触发,使用上游 conda 包构建的 commit
ref: ${{ github.event.workflow_run.head_sha || github.ref }}
fetch-depth: 0
@@ -96,12 +92,14 @@ jobs:
echo "should_build=false" >> $GITHUB_OUTPUT
fi
- name: Setup Miniconda
- name: Setup Miniforge
if: steps.should_build.outputs.should_build == 'true'
uses: conda-incubator/setup-miniconda@v3
with:
miniconda-version: 'latest'
channels: conda-forge,robostack-staging,uni-lab,defaults
miniforge-version: latest
use-mamba: true
python-version: '3.11.14'
channels: conda-forge,robostack-staging,uni-lab
channel-priority: strict
activate-environment: build-env
auto-update-conda: false
@@ -110,20 +108,22 @@ jobs:
- name: Install rattler-build and anaconda-client
if: steps.should_build.outputs.should_build == 'true'
run: |
conda install -c conda-forge rattler-build anaconda-client
mamba install -n build-env --override-channels -c conda-forge rattler-build anaconda-client -y
- name: Show environment info
if: steps.should_build.outputs.should_build == 'true'
run: |
conda info
conda list | grep -E "(rattler-build|anaconda-client)"
conda list -n build-env | grep -E "(rattler-build|anaconda-client)"
conda run -n build-env rattler-build --version
conda run -n build-env anaconda --version
echo "Platform: ${{ matrix.platform }}"
echo "OS: ${{ matrix.os }}"
echo "Build full package: ${{ github.event.inputs.build_full || 'false' }}"
echo "Build full package: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.build_full == 'true' }}"
echo "Building packages:"
echo " - unilabos-env (environment dependencies)"
echo " - unilabos (with pip package)"
if [[ "${{ github.event.inputs.build_full }}" == "true" ]]; then
if [[ "${{ github.event_name == 'workflow_dispatch' && github.event.inputs.build_full == 'true' }}" == "true" ]]; then
echo " - unilabos-full (complete package)"
fi
@@ -131,14 +131,19 @@ jobs:
if: steps.should_build.outputs.should_build == 'true'
run: |
echo "Building unilabos-env (conda environment dependencies)..."
rattler-build build -r .conda/environment/recipe.yaml -c uni-lab -c robostack-staging -c conda-forge
conda run -n build-env rattler-build build -r .conda/environment/recipe.yaml -c uni-lab -c robostack-staging -c conda-forge
- name: Upload unilabos-env to Anaconda.org (if enabled)
if: steps.should_build.outputs.should_build == 'true' && github.event.inputs.upload_to_anaconda == 'true'
if: |
steps.should_build.outputs.should_build == 'true' &&
(
github.event_name == 'workflow_run' ||
github.event.inputs.upload_to_anaconda == 'true'
)
run: |
echo "Uploading unilabos-env to uni-lab organization..."
for package in $(find ./output -name "unilabos-env*.conda"); do
anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
conda run -n build-env anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
done
- name: Build unilabos (with pip package)
@@ -146,33 +151,40 @@ jobs:
run: |
echo "Building unilabos package..."
# 如果已上传到 Anaconda从 uni-lab channel 获取 unilabos-env否则从本地 output 获取
rattler-build build -r .conda/base/recipe.yaml -c uni-lab -c robostack-staging -c conda-forge --channel ./output
conda run -n build-env rattler-build build -r .conda/base/recipe.yaml -c uni-lab -c robostack-staging -c conda-forge --channel ./output
- name: Upload unilabos to Anaconda.org (if enabled)
if: steps.should_build.outputs.should_build == 'true' && github.event.inputs.upload_to_anaconda == 'true'
if: |
steps.should_build.outputs.should_build == 'true' &&
(
github.event_name == 'workflow_run' ||
github.event.inputs.upload_to_anaconda == 'true'
)
run: |
echo "Uploading unilabos to uni-lab organization..."
for package in $(find ./output -name "unilabos-0*.conda" -o -name "unilabos-[0-9]*.conda"); do
anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
conda run -n build-env anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
done
- name: Build unilabos-full - Only when explicitly requested
if: |
steps.should_build.outputs.should_build == 'true' &&
github.event_name == 'workflow_dispatch' &&
github.event.inputs.build_full == 'true'
run: |
echo "Building unilabos-full package on ${{ matrix.platform }}..."
rattler-build build -r .conda/full/recipe.yaml -c uni-lab -c robostack-staging -c conda-forge --channel ./output
conda run -n build-env rattler-build build -r .conda/full/recipe.yaml -c uni-lab -c robostack-staging -c conda-forge --channel ./output
- name: Upload unilabos-full to Anaconda.org (if enabled)
if: |
steps.should_build.outputs.should_build == 'true' &&
github.event_name == 'workflow_dispatch' &&
github.event.inputs.build_full == 'true' &&
github.event.inputs.upload_to_anaconda == 'true'
run: |
echo "Uploading unilabos-full to uni-lab organization..."
for package in $(find ./output -name "unilabos-full*.conda"); do
anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
conda run -n build-env anaconda -t ${{ secrets.ANACONDA_API_TOKEN }} upload --user uni-lab --force "$package"
done
- name: List built packages

5
.gitignore vendored
View File

@@ -251,4 +251,7 @@ ros-humble-unilabos-msgs-0.9.13-h6403a04_5.tar.bz2
*.bz2
test_config.py
# Local config files with secrets
yibin_coin_cell_only_config.json
yibin_electrolyte_config.json
yibin_electrolyte_only_config.json

View File

@@ -0,0 +1,72 @@
# CSV 导出功能变更概要
## 修改的文件
### 1. [bioyond_cell_workstation.py](file:///d:/UniLabdev/Uni-Lab-OS/unilabos/devices/workstation/bioyond_studio/bioyond_cell/bioyond_cell_workstation.py)
#### 新增导入
- `import csv``import os`L14-15
#### 新增方法
| 方法 | 功能 |
|------|------|
| `_extract_prep_bottle_from_report` | 从 order_finish 报文提取**配液瓶**信息每订单最多1个 |
| `_extract_vial_bottles_from_report` | 从 order_finish 报文提取**分液瓶**信息(每订单可多个,返回数组) |
| `_export_order_csv` | 汇总所有信息写入 CSV 文件 |
#### 配液瓶筛选逻辑 (`_extract_prep_bottle_from_report`)
- `typemode="1"`, `realQuantity=1`, `usedQuantity=1`
- `locationId``3a19deae-2c7a-` 开头(手动传递窗)
- LIMS API 二次确认:`typeName` 含"配液瓶(小)"或"配液瓶(大)"
#### 分液瓶筛选逻辑 (`_extract_vial_bottles_from_report`)
- `typemode="1"`, `realQuantity=1`, `usedQuantity=1`
- `locationId``3a19debc-84b5-``3a19debe-5200` 开头(自动堆栈-左/右)
- LIMS API 二次确认:`typeName` 为"5ml分液瓶"或"20ml分液瓶"
- **返回数组**,支持 1×5ml + n×20ml 的组合
#### 修改的方法
| 方法 | 变更 |
|------|------|
| `_submit_and_wait_orders` | 新增配液瓶+分液瓶提取步骤,将 `prep_bottles``vial_bottles` 存入 `final_result` |
| `create_orders` | 添加 `csv_export_path` 参数,末尾调用 `_export_order_csv` |
| `create_orders_formulation` | 添加 `csv_export_path` 参数,末尾调用 `_export_order_csv` |
#### CSV 输出格式
```
orderCode, orderName, 配液瓶类型, 配液瓶二维码, 分液瓶类型, 分液瓶二维码, 目标配液质量比, 真实配液质量比, 时间
```
- 单个分液瓶时直接写值;多个分液瓶时类型和二维码用 JSON 数组表示
- CSV 编码使用 `utf-8-sig`(兼容 Excel 打开)
- `csv_export_path` 默认为空字符串,不传则不导出(向后兼容)
---
### 2. [bioyond_cell.yaml](file:///d:/UniLabdev/Uni-Lab-OS/unilabos/registry/devices/bioyond_cell.yaml)
为两个 action 注册了 `csv_export_path` 参数:
- `auto-create_orders`: `goal_default` + `schema.properties.goal.properties` 中添加 `csv_export_path`
- `auto-create_orders_formulation`: 同上
---
### 3. [coin_cell_assembly.py](file:///d:/UniLabdev/Uni-Lab-OS/unilabos/devices/workstation/coin_cell_assembly/coin_cell_assembly.py) 的 CSV 改动与全流程追溯
`bioyond_cell_workstation.py``_submit_and_wait_orders` 最后阶段,提取 `prep_bottles`(配液瓶)和 `vial_bottles`(分液瓶)的条码并随 `mass_ratios` 数组一起下发给各下游工站(例如扣电组装站),实现跨站的全流程配方追溯。
并在扣电站生成的 `date_xxx.csv` 中,**替换并新增**了以下列:
- 移除了原有的 `formulation_order_code` 与合并的 `formulation_ratio` 列。
- 新增 `orderName` 导出
- 新增 `prep_bottle_barcode`(奔曜传递的配液瓶二维码)
- 新增 `vial_bottle_barcodes`(奔曜传递的分液瓶二维码,多瓶时存 JSON 数组)
- 新增 `target_mass_ratio` 理论目标质量比
- 新增 `real_mass_ratio` 实际称量真实质量比
*注意:这与操作人员在手套箱内扫码传入扣电站的 `electrolyte_code` 是单独记录的,方便做数据核对。*
## 向后兼容性
- `csv_export_path` 默认值为 `""`(空字符串),现有调用不受影响
- 新增的 `prep_bottles``vial_bottles` 字段为 `final_result``mass_ratios` 内部的新增附属字段,不破坏现有数据结构。

168
CHANGES_2026_03_24.md Normal file
View File

@@ -0,0 +1,168 @@
# 变更说明 2026-03-24
## 问题背景
`BioyondElectrolyteDeck`(原 `BIOYOND_YB_Deck`)迁移后,前端物料未能正常上传/同步。
---
## 修复内容
### 1. `unilabos/resources/bioyond/decks.py`
- 补回 `setup: bool = False` 参数及 `if setup: self.setup()` 逻辑,与旧版 `BIOYOND_YB_Deck` 保持一致
- 工厂函数 `bioyond_electrolyte_deck` 保留显式调用 `deck.setup()`,避免重复初始化
```python
# 修复前(缺少 setup 参数,无法通过 setup=True 触发初始化)
def __init__(self, name, size_x, size_y, size_z, category):
super().__init__(...)
# 修复后
def __init__(self, name, size_x, size_y, size_z, category, setup: bool = False):
super().__init__(...)
if setup:
self.setup()
```
---
### 2. `unilabos/resources/graphio.py`
- 修复 `resource_bioyond_to_plr` 中两处 `bottle.tracker.liquids` 直接赋值导致的崩溃
- `ResourceHolder`(如枪头盒的 TipSpot 槽位)没有 `tracker` 属性,直接访问会抛出 `AttributeError`,阻断整个 Bioyond 同步流程
```python
# 修复前
bottle.tracker.liquids = [...]
# 修复后
if hasattr(bottle, 'tracker') and bottle.tracker is not None:
bottle.tracker.liquids = [...]
```
---
### 3. `unilabos/app/main.py`
- 保留 `file_path is not None` 条件不变(已还原),并补充注释说明原因
- 该逻辑只在**本地文件模式**下有意义:本地 graph 文件只含设备结构远端有已保存物料merge 才能将两者合并
- 远端模式(`file_path=None`)下,`resource_tree_set``request_startup_json` 来自同一份数据merge 为空操作,条件是否加 `file_path is not None` 对结果没有影响
---
### 4. `unilabos/devices/workstation/bioyond_studio/station.py` ⭐ 核心修复
- 当 deck 通过反序列化创建时,不会自动调用 `setup()`,导致 `deck.children` 为空,`warehouses` 始终是 `{}`
- 增加兜底逻辑:仓库扫描后仍为空,则主动调用 `deck.setup()` 初始化仓库
- 这是导致所有物料放置失败(`warehouse '...' 在deck中不存在。可用warehouses: []`)的根本原因
```python
# 新增兜底
if not self.deck.warehouses and hasattr(self.deck, "setup") and callable(self.deck.setup):
logger.info("Deck 无仓库子节点,调用 setup() 初始化仓库")
self.deck.setup()
```
---
---
## 补充修复 2026-03-25依华扣电组装工站子物料未上传
### 问题
`CoinCellAssemblyWorkstation.post_init` 直接上传空 deck未调用 `deck.setup()`,导致:
- 前端子物料(成品弹夹、料盘、瓶架等)不显示
- 运行时 `self.deck.get_resource("成品弹夹")` 抛出 `ResourceNotFoundError`
### 修复文件
**`unilabos/devices/workstation/coin_cell_assembly/YB_YH_materials.py`**
- `YihuaCoinCellDeck.__init__` 补回 `setup: bool = False` 参数及 `if setup: self.setup()` 逻辑
**`unilabos/devices/workstation/coin_cell_assembly/coin_cell_assembly.py`**
- `post_init` 中增加与 Bioyond 工站相同的兜底逻辑deck 无子节点时调用 `deck.setup()` 初始化
```python
# post_init 中新增
if self.deck and not self.deck.children and hasattr(self.deck, "setup") and callable(self.deck.setup):
logger.info("YihuaCoinCellDeck 无子节点,调用 setup() 初始化")
self.deck.setup()
```
### 联动 Bug`MaterialPlate.create_with_holes` 构造顺序错误
**现象**`deck.setup()` 被调用后,启动时抛出:
```
设备后初始化失败: Must specify either `ordered_items` or `ordering`.
```
**根因**`create_with_holes` 原来的逻辑是先构造空的 `MaterialPlate` 实例,再 assign 洞位:
```python
# 旧错误cls(...) 时 ordered_items=None → ItemizedResource.__init__ 立即报错
plate = cls(name=name, ...) # ← 这里就崩了
holes = create_ordered_items_2d(...) # ← 根本没走到这里
for hole_name, hole in holes.items():
plate.assign_child_resource(...)
```
pylabrobot 的 `ItemizedResource.__init__` 强制要求 `ordered_items``ordering` 必须有一个不为 `None`,空构造直接失败。
**修复**:先建洞位,再作为 `ordered_items` 传给构造函数:
```python
# 新(正确):先建洞位,再一次性传入构造函数
holes = create_ordered_items_2d(klass=MaterialHole, num_items_x=4, ...)
return cls(name=name, ..., ordered_items=holes)
```
> 此 bug 此前未被触发,是因为 `deck.setup()` 从未被调用到——正是上面 `post_init` 兜底修复引出的联动问题。
---
## 补充修复 2026-03-253→2→1 转运资源同步失败
### 问题
配液工站Bioyond完成分液后调用 `transfer_3_to_2_to_1_auto` 将分液瓶板转运到扣电工站BatteryStation。物理 LIMS 转运成功,但数字孪生资源树同步始终失败:
```
[资源同步] ❌ 失败: 目标设备 'BatteryStation' 中未找到资源 'bottle_rack_6x2'
```
### 根因
`_get_resource_from_device` 方法负责跨设备查找资源对象,有两个问题:
1. **原始路径完全失效**:尝试 `from unilabos.app.ros2_app import get_device_plr_resource_by_name`,但该模块不存在,`ImportError``except Exception: pass` 静默吞掉
2. **降级路径搜错地方**:遍历 `self._plr_resources`Bioyond 自己的资源),不可能找到 BatteryStation 的 `bottle_rack_6x2`
### 修复文件
**`unilabos/devices/workstation/bioyond_studio/bioyond_cell/bioyond_cell_workstation.py`**
改用全局设备注册表 `registered_devices` 跨设备访问目标 deck
```python
# 修复前(失效)
from unilabos.app.ros2_app import get_device_plr_resource_by_name # 模块不存在
return get_device_plr_resource_by_name(device_id, resource_name)
# 修复后
from unilabos.ros.nodes.base_device_node import registered_devices
device_info = registered_devices.get(device_id)
if device_info is not None:
driver = device_info.get("driver_instance") # TypedDict 是 dict必须用 .get()
if driver is not None:
deck = getattr(driver, "deck", None)
if deck is not None:
res = deck.get_resource(resource_name)
```
关键细节:`DeviceInfoType``TypedDict`(即普通 `dict`),必须用 `device_info.get("driver_instance")` 而非 `getattr(device_info, "driver_instance", None)`——后者对字典永远返回 `None`
---
## 根本原因分析
旧版以**本地文件模式**启动(有 `graph` 文件deck 在启动前已通过 `merge_remote_resources` 获得仓库子节点,反序列化时能正确恢复 warehouses。
新版以**远端模式**启动(`file_path=None`deck 反序列化时没有仓库子节点,`station.py` 扫描为空,所有物料的 warehouse 匹配失败Bioyond 同步的 16 个资源全部无法放置到对应仓库位,前端不显示。

View File

@@ -12,7 +12,7 @@ Uni-Lab 使用 Python 格式的配置文件(`.py`),默认为 `unilabos_dat
**获取方式:**
进入 [Uni-Lab 实验室](https://uni-lab.bohrium.com),点击左下角的头像,在实验室详情中获取所在实验室的 ak 和 sk
进入 [Uni-Lab 实验室](https://leap-lab.bohrium.com),点击左下角的头像,在实验室详情中获取所在实验室的 ak 和 sk
![copy_aksk.gif](image/copy_aksk.gif)
@@ -69,7 +69,7 @@ class WSConfig:
# HTTP配置
class HTTPConfig:
remote_addr = "https://uni-lab.bohrium.com/api/v1" # 远程服务器地址
remote_addr = "https://leap-lab.bohrium.com/api/v1" # 远程服务器地址
# ROS配置
class ROSConfig:
@@ -209,8 +209,8 @@ unilab --ak "key" --sk "secret" --addr "test" --upload_registry --2d_vis -g grap
`--addr` 参数支持以下预设值,会自动转换为对应的完整 URL
- `test``https://uni-lab.test.bohrium.com/api/v1`
- `uat``https://uni-lab.uat.bohrium.com/api/v1`
- `test``https://leap-lab.test.bohrium.com/api/v1`
- `uat``https://leap-lab.uat.bohrium.com/api/v1`
- `local``http://127.0.0.1:48197/api/v1`
- 其他值 → 直接使用作为完整 URL
@@ -248,7 +248,7 @@ unilab --ak "key" --sk "secret" --addr "test" --upload_registry --2d_vis -g grap
`ak``sk` 是必需的认证参数:
1. **获取方式**:在 [Uni-Lab 官网](https://uni-lab.bohrium.com) 注册实验室后获得
1. **获取方式**:在 [Uni-Lab 官网](https://leap-lab.bohrium.com) 注册实验室后获得
2. **配置方式**
- **命令行参数**`--ak "your_key" --sk "your_secret"`(最高优先级,推荐)
- **环境变量**`UNILABOS_BASICCONFIG_AK``UNILABOS_BASICCONFIG_SK`
@@ -275,15 +275,15 @@ WebSocket 是 Uni-Lab 的主要通信方式:
HTTP 客户端配置用于与云端服务通信:
| 参数 | 类型 | 默认值 | 说明 |
| ------------- | ---- | -------------------------------------- | ------------ |
| `remote_addr` | str | `"https://uni-lab.bohrium.com/api/v1"` | 远程服务地址 |
| 参数 | 类型 | 默认值 | 说明 |
| ------------- | ---- | --------------------------------------- | ------------ |
| `remote_addr` | str | `"https://leap-lab.bohrium.com/api/v1"` | 远程服务地址 |
**预设环境地址**
- 生产环境:`https://uni-lab.bohrium.com/api/v1`(默认)
- 测试环境:`https://uni-lab.test.bohrium.com/api/v1`
- UAT 环境:`https://uni-lab.uat.bohrium.com/api/v1`
- 生产环境:`https://leap-lab.bohrium.com/api/v1`(默认)
- 测试环境:`https://leap-lab.test.bohrium.com/api/v1`
- UAT 环境:`https://leap-lab.uat.bohrium.com/api/v1`
- 本地环境:`http://127.0.0.1:48197/api/v1`
### 4. ROSConfig - ROS 配置
@@ -401,7 +401,7 @@ export UNILABOS_WSCONFIG_RECONNECT_INTERVAL="10"
export UNILABOS_WSCONFIG_MAX_RECONNECT_ATTEMPTS="500"
# 设置HTTP配置
export UNILABOS_HTTPCONFIG_REMOTE_ADDR="https://uni-lab.test.bohrium.com/api/v1"
export UNILABOS_HTTPCONFIG_REMOTE_ADDR="https://leap-lab.test.bohrium.com/api/v1"
```
## 配置文件使用方法
@@ -484,13 +484,13 @@ export UNILABOS_WSCONFIG_MAX_RECONNECT_ATTEMPTS=100
```python
class HTTPConfig:
remote_addr = "https://uni-lab.test.bohrium.com/api/v1"
remote_addr = "https://leap-lab.test.bohrium.com/api/v1"
```
**环境变量方式:**
```bash
export UNILABOS_HTTPCONFIG_REMOTE_ADDR=https://uni-lab.test.bohrium.com/api/v1
export UNILABOS_HTTPCONFIG_REMOTE_ADDR=https://leap-lab.test.bohrium.com/api/v1
```
**命令行方式(推荐):**

View File

@@ -23,7 +23,7 @@ Uni-Lab-OS 支持多种部署模式:
```
┌──────────────────────────────────────────────┐
│ Cloud Platform/Self-hosted Platform │
uni-lab.bohrium.com │
leap-lab.bohrium.com │
│ (Resource Management, Task Scheduling, │
│ Monitoring) │
└────────────────────┬─────────────────────────┘
@@ -444,7 +444,7 @@ ros2 daemon stop && ros2 daemon start
```bash
# 测试云端连接
curl https://uni-lab.bohrium.com/api/v1/health
curl https://leap-lab.bohrium.com/api/v1/health
# 测试WebSocket
# 启动Uni-Lab后查看日志

View File

@@ -33,11 +33,11 @@
**选择合适的安装包:**
| 安装包 | 适用场景 | 包含组件 |
|--------|----------|----------|
| `unilabos` | **推荐大多数用户**,生产部署 | 完整安装包,开箱即用 |
| `unilabos-env` | 开发者(可编辑安装) | 仅环境依赖,通过 pip 安装 unilabos |
| `unilabos-full` | 仿真/可视化 | unilabos + 完整 ROS2 桌面版 + Gazebo + MoveIt |
| 安装包 | 适用场景 | 包含组件 |
| --------------- | ---------------------------- | --------------------------------------------- |
| `unilabos` | **推荐大多数用户**,生产部署 | 完整安装包,开箱即用 |
| `unilabos-env` | 开发者(可编辑安装) | 仅环境依赖,通过 pip 安装 unilabos |
| `unilabos-full` | 仿真/可视化 | unilabos + 完整 ROS2 桌面版 + Gazebo + MoveIt |
**关键步骤:**
@@ -66,6 +66,7 @@ mamba install uni-lab::unilabos-full -c robostack-staging -c conda-forge
```
**选择建议:**
- **日常使用/生产部署**:使用 `unilabos`(推荐),完整功能,开箱即用
- **开发者**:使用 `unilabos-env` + `pip install -e .` + `uv pip install -r unilabos/utils/requirements.txt`,代码修改立即生效
- **仿真/可视化**:使用 `unilabos-full`,含 Gazebo、rviz2、MoveIt
@@ -88,7 +89,7 @@ python -c "from unilabos_msgs.msg import Resource; print('ROS msgs OK')"
#### 2.1 注册实验室账号
1. 访问 [https://uni-lab.bohrium.com](https://uni-lab.bohrium.com)
1. 访问 [https://leap-lab.bohrium.com](https://leap-lab.bohrium.com)
2. 注册账号并登录
3. 创建新实验室
@@ -297,7 +298,7 @@ unilab --ak your_ak --sk your_sk -g test/experiments/mock_devices/mock_all.json
#### 5.2 访问 Web 界面
启动系统后,访问[https://uni-lab.bohrium.com](https://uni-lab.bohrium.com)
启动系统后,访问[https://leap-lab.bohrium.com](https://leap-lab.bohrium.com)
#### 5.3 添加设备和物料
@@ -306,12 +307,10 @@ unilab --ak your_ak --sk your_sk -g test/experiments/mock_devices/mock_all.json
**示例场景:** 创建一个简单的液体转移实验
1. **添加工作站(必需):**
- 在"仪器设备"中找到 `work_station`
- 添加 `workstation` x1
2. **添加虚拟转移泵:**
- 在"仪器设备"中找到 `virtual_device`
- 添加 `virtual_transfer_pump` x1
@@ -818,6 +817,7 @@ uv pip install -r unilabos/utils/requirements.txt
```
**为什么使用这种方式?**
- `unilabos-env` 提供 ROS2 核心组件和 uv通过 conda 安装,避免编译)
- `unilabos/utils/requirements.txt` 包含所有运行时需要的 pip 依赖
- `dev_install.py` 自动检测中文环境,中文系统自动使用清华镜像
@@ -1796,32 +1796,27 @@ unilab --ak your_ak --sk your_sk -g graph.json \
**详细步骤:**
1. **需求分析**
- 明确实验流程
- 列出所需设备和物料
- 设计工作流程图
2. **环境搭建**
- 安装 Uni-Lab-OS
- 创建实验室账号
- 准备开发工具IDE、Git
3. **原型验证**
- 使用虚拟设备测试流程
- 验证工作流逻辑
- 调整参数
4. **迭代开发**
- 实现自定义设备驱动(同时撰写单点函数测试)
- 编写注册表
- 单元测试
- 集成测试
5. **测试部署**
- 连接真实硬件
- 空跑测试
- 小规模试验
@@ -1871,7 +1866,7 @@ unilab --ak your_ak --sk your_sk -g graph.json \
#### 14.5 社区支持
- **GitHub Issues**[https://github.com/deepmodeling/Uni-Lab-OS/issues](https://github.com/deepmodeling/Uni-Lab-OS/issues)
- **官方网站**[https://uni-lab.bohrium.com](https://uni-lab.bohrium.com)
- **官方网站**[https://leap-lab.bohrium.com](https://leap-lab.bohrium.com)
---

View File

@@ -626,7 +626,7 @@ unilab
**云端图文件管理**:
1. 登录 https://uni-lab.bohrium.com
1. 登录 https://leap-lab.bohrium.com
2. 进入"设备配置"
3. 创建或编辑配置
4. 保存到云端

View File

@@ -54,7 +54,6 @@ Uni-Lab 的启动过程分为以下几个阶段:
您可以直接跟随 unilabos 的提示进行,无需查阅本节
- **工作目录设置**
- 如果当前目录以 `unilabos_data` 结尾,则使用当前目录
- 否则使用 `当前目录/unilabos_data` 作为工作目录
- 可通过 `--working_dir` 指定自定义工作目录
@@ -68,8 +67,8 @@ Uni-Lab 的启动过程分为以下几个阶段:
支持多种后端环境:
- `--addr test`:测试环境 (`https://uni-lab.test.bohrium.com/api/v1`)
- `--addr uat`UAT 环境 (`https://uni-lab.uat.bohrium.com/api/v1`)
- `--addr test`:测试环境 (`https://leap-lab.test.bohrium.com/api/v1`)
- `--addr uat`UAT 环境 (`https://leap-lab.uat.bohrium.com/api/v1`)
- `--addr local`:本地环境 (`http://127.0.0.1:48197/api/v1`)
- 自定义地址:直接指定完整 URL
@@ -176,7 +175,7 @@ unilab --config path/to/your/config.py
如果是首次使用,系统会:
1. 提示前往 https://uni-lab.bohrium.com 注册实验室
1. 提示前往 https://leap-lab.bohrium.com 注册实验室
2. 引导创建配置文件
3. 设置工作目录
@@ -216,7 +215,7 @@ unilab --ak your_ak --sk your_sk --port 8080 --disable_browser
如果提示 "后续运行必须拥有一个实验室",请确保:
- 已在 https://uni-lab.bohrium.com 注册实验室
- 已在 https://leap-lab.bohrium.com 注册实验室
- 正确设置了 `--ak``--sk` 参数
- 配置文件中包含正确的认证信息

View File

@@ -1,5 +1,5 @@
channel_sources:
- robostack,robostack-staging,conda-forge,defaults
- robostack,robostack-staging,conda-forge
gazebo:
- '11'

View File

@@ -1,6 +1,6 @@
package:
name: ros-humble-unilabos-msgs
version: 0.10.19
version: 0.11.2
source:
path: ../../unilabos_msgs
target_directory: src

View File

@@ -1,6 +1,6 @@
package:
name: unilabos
version: "0.10.19"
version: "0.11.2"
source:
path: ../..

View File

@@ -4,7 +4,7 @@ package_name = 'unilabos'
setup(
name=package_name,
version='0.10.19',
version='0.11.2',
packages=find_packages(),
include_package_data=True,
install_requires=['setuptools'],

View File

@@ -1,296 +0,0 @@
"""
批量转运编译器测试
覆盖单物料退化、刚好一批、多批次、空操作、AGV 配置发现、children dict 状态。
"""
import pytest
import networkx as nx
from unilabos.compile.batch_transfer_protocol import generate_batch_transfer_protocol
from unilabos.compile.agv_transfer_protocol import generate_agv_transfer_protocol
from unilabos.compile._agv_utils import find_agv_config, get_agv_capacity, split_batches
# ============ 构建测试用设备图 ============
def _make_graph(capacity_x=2, capacity_y=1, capacity_z=1):
"""构建包含 AGV 节点的测试设备图"""
G = nx.DiGraph()
# AGV 节点
G.add_node("AGV", **{
"type": "device",
"class_": "agv_transport_station",
"config": {
"protocol_type": ["AGVTransferProtocol", "BatchTransferProtocol"],
"device_roles": {
"navigator": "zhixing_agv",
"arm": "zhixing_ur_arm"
},
"route_table": {
"StationA->StationB": {
"nav_command": '{"target": "LM1"}',
"arm_pick": '{"task_name": "pick.urp"}',
"arm_place": '{"task_name": "place.urp"}'
},
"AGV->StationA": {
"nav_command": '{"target": "LM1"}',
"arm_pick": '{"task_name": "pick.urp"}',
"arm_place": '{"task_name": "place.urp"}'
},
"StationA->StationA": {
"nav_command": '{"target": "LM1"}',
"arm_pick": '{"task_name": "pick.urp"}',
"arm_place": '{"task_name": "place.urp"}'
},
}
}
})
# AGV 子设备
G.add_node("zhixing_agv", type="device", class_="zhixing_agv")
G.add_node("zhixing_ur_arm", type="device", class_="zhixing_ur_arm")
G.add_edge("AGV", "zhixing_agv")
G.add_edge("AGV", "zhixing_ur_arm")
# AGV Warehouse 子资源
G.add_node("agv_platform", **{
"type": "warehouse",
"config": {
"name": "agv_platform",
"num_items_x": capacity_x,
"num_items_y": capacity_y,
"num_items_z": capacity_z,
}
})
G.add_edge("AGV", "agv_platform")
# 来源/目标工站
G.add_node("StationA", type="device", class_="workstation")
G.add_node("StationB", type="device", class_="workstation")
return G
def _make_repos(items_count=2):
"""构建测试用的 from_repo 和 to_repo dict"""
children = {}
for i in range(items_count):
pos = f"A{i + 1:02d}"
children[pos] = {
"id": f"resource_{i + 1}",
"name": f"R{i + 1}",
"parent": "StationA",
"type": "resource",
}
from_repo = {
"StationA": {
"id": "StationA",
"name": "StationA",
"children": children,
}
}
to_repo = {
"StationB": {
"id": "StationB",
"name": "StationB",
"children": {},
}
}
return from_repo, to_repo
def _make_items(count=2):
"""构建 transfer_resources / from_positions / to_positions"""
resources = [
{
"id": f"resource_{i + 1}",
"name": f"R{i + 1}",
"sample_id": f"uuid-{i + 1}",
"parent": "StationA",
"type": "resource",
}
for i in range(count)
]
from_positions = [f"A{i + 1:02d}" for i in range(count)]
to_positions = [f"A{i + 1:02d}" for i in range(count)]
return resources, from_positions, to_positions
# ============ _agv_utils 测试 ============
class TestAGVUtils:
def test_find_agv_config(self):
G = _make_graph()
cfg = find_agv_config(G)
assert cfg["agv_id"] == "AGV"
assert cfg["device_roles"]["navigator"] == "zhixing_agv"
assert cfg["device_roles"]["arm"] == "zhixing_ur_arm"
assert "StationA->StationB" in cfg["route_table"]
def test_find_agv_config_by_id(self):
G = _make_graph()
cfg = find_agv_config(G, agv_id="AGV")
assert cfg["agv_id"] == "AGV"
def test_find_agv_config_not_found(self):
G = nx.DiGraph()
G.add_node("SomeDevice", type="device", class_="pump")
with pytest.raises(ValueError, match="未找到 AGV"):
find_agv_config(G)
def test_get_agv_capacity(self):
G = _make_graph(capacity_x=2, capacity_y=1, capacity_z=1)
assert get_agv_capacity(G, "AGV") == 2
def test_get_agv_capacity_multi_layer(self):
G = _make_graph(capacity_x=1, capacity_y=2, capacity_z=3)
assert get_agv_capacity(G, "AGV") == 6
def test_split_batches_exact(self):
assert split_batches([1, 2], 2) == [[1, 2]]
def test_split_batches_overflow(self):
assert split_batches([1, 2, 3], 2) == [[1, 2], [3]]
def test_split_batches_single(self):
assert split_batches([1], 4) == [[1]]
def test_split_batches_zero_capacity(self):
with pytest.raises(ValueError):
split_batches([1], 0)
# ============ 批量转运编译器测试 ============
class TestBatchTransferProtocol:
def test_empty_items(self):
"""空物料列表返回空 steps"""
G = _make_graph()
from_repo, to_repo = _make_repos(0)
steps = generate_batch_transfer_protocol(G, from_repo, to_repo, [], [], [])
assert steps == []
def test_single_item(self):
"""单物料转运BatchTransfer 退化为单物料)"""
G = _make_graph(capacity_x=2)
from_repo, to_repo = _make_repos(1)
resources, from_pos, to_pos = _make_items(1)
steps = generate_batch_transfer_protocol(G, from_repo, to_repo, resources, from_pos, to_pos)
# 应该有: nav到来源 + 1个pick + nav到目标 + 1个place = 4 steps
assert len(steps) == 4
assert steps[0]["action_name"] == "send_nav_task"
assert steps[1]["action_name"] == "move_pos_task"
assert steps[1]["_transfer_meta"]["phase"] == "pick"
assert steps[2]["action_name"] == "send_nav_task"
assert steps[3]["action_name"] == "move_pos_task"
assert steps[3]["_transfer_meta"]["phase"] == "place"
def test_exact_capacity(self):
"""物料数 = AGV 容量,刚好一批"""
G = _make_graph(capacity_x=2)
from_repo, to_repo = _make_repos(2)
resources, from_pos, to_pos = _make_items(2)
steps = generate_batch_transfer_protocol(G, from_repo, to_repo, resources, from_pos, to_pos)
# nav + 2 pick + nav + 2 place = 6 steps
assert len(steps) == 6
pick_steps = [s for s in steps if s.get("_transfer_meta", {}).get("phase") == "pick"]
place_steps = [s for s in steps if s.get("_transfer_meta", {}).get("phase") == "place"]
assert len(pick_steps) == 2
assert len(place_steps) == 2
def test_multi_batch(self):
"""物料数 > AGV 容量,自动分批"""
G = _make_graph(capacity_x=2)
from_repo, to_repo = _make_repos(3)
resources, from_pos, to_pos = _make_items(3)
steps = generate_batch_transfer_protocol(G, from_repo, to_repo, resources, from_pos, to_pos)
# 批次1: nav + 2 pick + nav + 2 place + nav(返回) = 7
# 批次2: nav + 1 pick + nav + 1 place = 4
# 总计 11 steps
assert len(steps) == 11
nav_steps = [s for s in steps if s["action_name"] == "send_nav_task"]
# 批次1: 2 nav(去来源+去目标) + 1 nav(返回) + 批次2: 2 nav = 5 nav
assert len(nav_steps) == 5
def test_children_dict_updated(self):
"""compile 阶段三方 children dict 状态正确"""
G = _make_graph(capacity_x=2)
from_repo, to_repo = _make_repos(2)
resources, from_pos, to_pos = _make_items(2)
assert "A01" in from_repo["StationA"]["children"]
assert "A02" in from_repo["StationA"]["children"]
assert len(to_repo["StationB"]["children"]) == 0
generate_batch_transfer_protocol(G, from_repo, to_repo, resources, from_pos, to_pos)
# compile 后 from_repo 的 children 应该被 pop 掉
assert "A01" not in from_repo["StationA"]["children"]
assert "A02" not in from_repo["StationA"]["children"]
# to_repo 应该有新物料
assert "A01" in to_repo["StationB"]["children"]
assert "A02" in to_repo["StationB"]["children"]
assert to_repo["StationB"]["children"]["A01"]["id"] == "resource_1"
def test_device_ids_from_config(self):
"""设备 ID 全部从配置读取,不硬编码"""
G = _make_graph()
from_repo, to_repo = _make_repos(1)
resources, from_pos, to_pos = _make_items(1)
steps = generate_batch_transfer_protocol(G, from_repo, to_repo, resources, from_pos, to_pos)
device_ids = {s["device_id"] for s in steps}
assert "zhixing_agv" in device_ids
assert "zhixing_ur_arm" in device_ids
def test_route_not_found(self):
"""路由表中无对应路线时报错"""
G = _make_graph()
from_repo = {"Unknown": {"id": "Unknown", "children": {"A01": {"id": "R1", "parent": "Unknown"}}}}
to_repo = {"Other": {"id": "Other", "children": {}}}
resources = [{"id": "R1", "name": "R1"}]
with pytest.raises(KeyError, match="路由表"):
generate_batch_transfer_protocol(G, from_repo, to_repo, resources, ["A01"], ["B01"])
def test_length_mismatch(self):
"""三个数组长度不一致时报错"""
G = _make_graph()
from_repo, to_repo = _make_repos(2)
resources = [{"id": "R1"}]
with pytest.raises(ValueError, match="长度不一致"):
generate_batch_transfer_protocol(G, from_repo, to_repo, resources, ["A01", "A02"], ["B01"])
# ============ 改造后的 AGV 单物料编译器测试 ============
class TestAGVTransferProtocol:
def test_single_transfer_from_config(self):
"""改造后的单物料编译器从 G 读取配置"""
G = _make_graph()
from_repo = {"StationA": {"id": "StationA", "children": {"A01": {"id": "R1", "parent": "StationA"}}}}
to_repo = {"StationB": {"id": "StationB", "children": {}}}
steps = generate_agv_transfer_protocol(G, from_repo, "A01", to_repo, "B01")
assert len(steps) == 2
assert steps[0]["device_id"] == "zhixing_agv"
assert steps[0]["action_name"] == "send_nav_task"
assert steps[1]["device_id"] == "zhixing_ur_arm"
assert steps[1]["action_name"] == "move_pos_task"
def test_children_updated(self):
"""单物料编译后 children dict 正确更新"""
G = _make_graph()
from_repo = {"StationA": {"id": "StationA", "children": {"A01": {"id": "R1", "parent": "StationA"}}}}
to_repo = {"StationB": {"id": "StationB", "children": {}}}
generate_agv_transfer_protocol(G, from_repo, "A01", to_repo, "B01")
assert "A01" not in from_repo["StationA"]["children"]
assert "B01" in to_repo["StationB"]["children"]
assert to_repo["StationB"]["children"]["B01"]["parent"] == "StationB"

View File

@@ -1,706 +0,0 @@
"""
全链路集成测试ROS Goal 转换 → ResourceTreeSet → get_plr_nested_dict → 编译器 → 动作列表
模拟 workstation.py 中的完整路径:
1. host 返回 raw_data模拟 resource_get 响应)
2. ResourceTreeSet.from_raw_dict_list(raw_data) 构建资源树
3. tree.root_node.get_plr_nested_dict() 生成嵌套 dict
4. protocol_kwargs 传给编译器
5. 编译器返回 action_list验证结构和关键字段
"""
import copy
import json
import pytest
import networkx as nx
from unilabos.resources.resource_tracker import (
ResourceDictInstance,
ResourceTreeSet,
)
from unilabos.compile.utils.resource_helper import (
ensure_resource_instance,
resource_to_dict,
get_resource_id,
get_resource_data,
)
from unilabos.compile.utils.vessel_parser import get_vessel
# ============ 构建模拟设备图 ============
def _build_test_graph():
"""构建一个包含常用设备节点的测试图"""
G = nx.DiGraph()
# 容器
G.add_node("reactor_01", **{
"id": "reactor_01",
"name": "reactor_01",
"type": "device",
"class": "virtual_stirrer",
"data": {},
"config": {},
})
# 搅拌设备
G.add_node("stirrer_1", **{
"id": "stirrer_1",
"name": "stirrer_1",
"type": "device",
"class": "virtual_stirrer",
"data": {},
"config": {},
})
G.add_edge("stirrer_1", "reactor_01")
# 加热设备
G.add_node("heatchill_1", **{
"id": "heatchill_1",
"name": "heatchill_1",
"type": "device",
"class": "virtual_heatchill",
"data": {},
"config": {},
})
G.add_edge("heatchill_1", "reactor_01")
# 试剂容器(液体)
G.add_node("flask_water", **{
"id": "flask_water",
"name": "flask_water",
"type": "container",
"class": "",
"data": {"reagent_name": "water", "liquid": [{"liquid_type": "water", "volume": 500.0}]},
"config": {"reagent": "water"},
})
# 固体加样器
G.add_node("solid_dispenser_1", **{
"id": "solid_dispenser_1",
"name": "solid_dispenser_1",
"type": "device",
"class": "solid_dispenser",
"data": {},
"config": {},
})
# 泵
G.add_node("pump_1", **{
"id": "pump_1",
"name": "pump_1",
"type": "device",
"class": "virtual_pump",
"data": {},
"config": {},
})
G.add_edge("flask_water", "pump_1")
G.add_edge("pump_1", "reactor_01")
return G
# ============ 构建模拟 host 返回数据 ============
def _make_raw_resource(
id="reactor_01",
uuid="uuid-reactor-01",
name="reactor_01",
klass="virtual_stirrer",
type_="device",
parent=None,
parent_uuid=None,
data=None,
config=None,
extra=None,
):
"""模拟 host 返回的单个资源 dict与 resource_get 服务响应一致)"""
return {
"id": id,
"uuid": uuid,
"name": name,
"class": klass,
"type": type_,
"parent": parent,
"parent_uuid": parent_uuid or "",
"description": "",
"config": config or {},
"data": data or {},
"extra": extra or {},
"position": {"x": 0.0, "y": 0.0, "z": 0.0},
}
def _simulate_workstation_resource_enrichment(raw_data_list, field_type="unilabos_msgs/Resource"):
"""
模拟 workstation.py 中 resource enrichment 的核心逻辑:
raw_data → ResourceTreeSet.from_raw_dict_list → get_plr_nested_dict → protocol_kwargs[k]
"""
tree_set = ResourceTreeSet.from_raw_dict_list(raw_data_list)
if field_type == "unilabos_msgs/Resource":
# 单个 Resource取第一棵树的根节点
root_instance = tree_set.trees[0].root_node if tree_set.trees else None
return root_instance.get_plr_nested_dict() if root_instance else {}
else:
# sequence<Resource>:返回列表
return [tree.root_node.get_plr_nested_dict() for tree in tree_set.trees]
# ============ 全链路测试Stir 协议 ============
class TestStirProtocolFullChain:
"""Stir 协议全链路host raw_data → enriched dict → compiler → action_list"""
def test_stir_with_enriched_resource_dict(self):
"""单个 Resource 经过 enrichment 后传给 stir compiler"""
from unilabos.compile.stir_protocol import generate_stir_protocol
raw_data = [_make_raw_resource(
id="reactor_01", uuid="uuid-reactor-01",
klass="virtual_stirrer", type_="device",
)]
# 模拟 workstation enrichment
enriched_vessel = _simulate_workstation_resource_enrichment(raw_data)
assert enriched_vessel["id"] == "reactor_01"
assert enriched_vessel["uuid"] == "uuid-reactor-01"
assert enriched_vessel["class"] == "virtual_stirrer"
# 传给编译器
G = _build_test_graph()
actions = generate_stir_protocol(
G=G,
vessel=enriched_vessel,
time="60",
stir_speed=300.0,
)
assert isinstance(actions, list)
assert len(actions) >= 1
action = actions[0]
assert action["device_id"] == "stirrer_1"
assert action["action_name"] == "stir"
assert "vessel" in action["action_kwargs"]
assert action["action_kwargs"]["vessel"]["id"] == "reactor_01"
def test_stir_with_resource_dict_instance(self):
"""直接用 ResourceDictInstance 传给 stir compiler通过 get_plr_nested_dict 转换)"""
from unilabos.compile.stir_protocol import generate_stir_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
tree_set = ResourceTreeSet.from_raw_dict_list(raw_data)
inst = tree_set.trees[0].root_node
# 通过 resource_to_dict 转换resource_helper 兼容层)
vessel_dict = resource_to_dict(inst)
assert isinstance(vessel_dict, dict)
assert vessel_dict["id"] == "reactor_01"
G = _build_test_graph()
actions = generate_stir_protocol(G=G, vessel=vessel_dict, time="30")
assert len(actions) >= 1
assert actions[0]["action_name"] == "stir"
def test_stir_with_string_vessel(self):
"""兼容旧模式:直接传 vessel 字符串"""
from unilabos.compile.stir_protocol import generate_stir_protocol
G = _build_test_graph()
actions = generate_stir_protocol(G=G, vessel="reactor_01", time="30")
assert len(actions) >= 1
assert actions[0]["device_id"] == "stirrer_1"
assert actions[0]["action_kwargs"]["vessel"]["id"] == "reactor_01"
# ============ 全链路测试HeatChill 协议 ============
class TestHeatChillProtocolFullChain:
"""HeatChill 协议全链路"""
def test_heatchill_with_enriched_resource(self):
from unilabos.compile.heatchill_protocol import generate_heat_chill_protocol
raw_data = [_make_raw_resource(id="reactor_01", klass="virtual_stirrer")]
enriched_vessel = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_heat_chill_protocol(
G=G,
vessel=enriched_vessel,
temp=80.0,
time="300",
)
assert isinstance(actions, list)
assert len(actions) >= 1
action = actions[0]
assert action["device_id"] == "heatchill_1"
assert action["action_name"] == "heat_chill"
assert action["action_kwargs"]["temp"] == 80.0
def test_heatchill_start_with_enriched_resource(self):
from unilabos.compile.heatchill_protocol import generate_heat_chill_start_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched_vessel = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_heat_chill_start_protocol(
G=G,
vessel=enriched_vessel,
temp=60.0,
)
assert len(actions) >= 1
assert actions[0]["action_name"] == "heat_chill_start"
assert actions[0]["action_kwargs"]["temp"] == 60.0
def test_heatchill_stop_with_enriched_resource(self):
from unilabos.compile.heatchill_protocol import generate_heat_chill_stop_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched_vessel = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_heat_chill_stop_protocol(G=G, vessel=enriched_vessel)
assert len(actions) >= 1
assert actions[0]["action_name"] == "heat_chill_stop"
# ============ 全链路测试Add 协议 ============
class TestAddProtocolFullChain:
"""Add 协议全链路vessel enrichment + reagent 查找 + 泵传输"""
def test_add_solid_with_enriched_resource(self):
from unilabos.compile.add_protocol import generate_add_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched_vessel = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_add_protocol(
G=G,
vessel=enriched_vessel,
reagent="NaCl",
mass="5 g",
)
assert isinstance(actions, list)
assert len(actions) >= 1
# 应该包含至少一个 add_solid 或 log_message 动作
action_names = [a.get("action_name", "") for a in actions]
assert any(name in ["add_solid", "log_message"] for name in action_names)
def test_add_liquid_with_enriched_resource(self):
from unilabos.compile.add_protocol import generate_add_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched_vessel = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_add_protocol(
G=G,
vessel=enriched_vessel,
reagent="water",
volume="10 mL",
)
assert isinstance(actions, list)
assert len(actions) >= 1
# ============ 全链路测试ResourceDictInstance 兼容层 ============
class TestResourceDictInstanceCompatibility:
"""验证编译器兼容层对 ResourceDictInstance 的处理"""
def test_get_vessel_from_enriched_dict(self):
"""get_vessel 对 enriched dict 的处理"""
raw_data = [_make_raw_resource(
id="reactor_01",
data={"temperature": 25.0, "liquid": [{"liquid_type": "water", "volume": 10.0}]},
)]
enriched = _simulate_workstation_resource_enrichment(raw_data)
vessel_id, vessel_data = get_vessel(enriched)
assert vessel_id == "reactor_01"
assert vessel_data["temperature"] == 25.0
assert len(vessel_data["liquid"]) == 1
def test_get_vessel_from_resource_instance(self):
"""get_vessel 直接对 ResourceDictInstance 的处理"""
raw_data = [_make_raw_resource(
id="reactor_01",
data={"temperature": 25.0},
)]
tree_set = ResourceTreeSet.from_raw_dict_list(raw_data)
inst = tree_set.trees[0].root_node
vessel_id, vessel_data = get_vessel(inst)
assert vessel_id == "reactor_01"
assert vessel_data["temperature"] == 25.0
def test_ensure_resource_instance_round_trip(self):
"""ensure_resource_instance → resource_to_dict 无损往返"""
raw_data = [_make_raw_resource(
id="reactor_01", uuid="uuid-r01", klass="virtual_stirrer",
data={"temp": 25.0},
)]
enriched = _simulate_workstation_resource_enrichment(raw_data)
# dict → ResourceDictInstance
inst = ensure_resource_instance(enriched)
assert isinstance(inst, ResourceDictInstance)
assert inst.res_content.id == "reactor_01"
assert inst.res_content.uuid == "uuid-r01"
# ResourceDictInstance → dict
d = resource_to_dict(inst)
assert isinstance(d, dict)
assert d["id"] == "reactor_01"
assert d["uuid"] == "uuid-r01"
assert d["class"] == "virtual_stirrer"
# ============ 全链路测试:带 children 的资源树 ============
class TestResourceTreeWithChildren:
"""测试带 children 结构的资源树通过编译器的路径"""
def _make_tree_with_children(self):
"""构建 StationA -> [Flask1, Flask2] 的资源树"""
return [
_make_raw_resource(
id="StationA", uuid="uuid-station-a",
name="StationA", klass="workstation", type_="device",
),
_make_raw_resource(
id="Flask1", uuid="uuid-flask-1",
name="Flask1", klass="", type_="resource",
parent="StationA", parent_uuid="uuid-station-a",
data={"liquid": [{"liquid_type": "water", "volume": 10.0}]},
),
_make_raw_resource(
id="Flask2", uuid="uuid-flask-2",
name="Flask2", klass="", type_="resource",
parent="StationA", parent_uuid="uuid-station-a",
data={"liquid": [{"liquid_type": "ethanol", "volume": 5.0}]},
),
]
def test_enrichment_preserves_children_structure(self):
"""验证 enrichment 后 children 为嵌套 dict"""
raw_data = self._make_tree_with_children()
enriched = _simulate_workstation_resource_enrichment(raw_data)
assert enriched["id"] == "StationA"
assert "children" in enriched
assert isinstance(enriched["children"], dict)
assert "Flask1" in enriched["children"]
assert "Flask2" in enriched["children"]
def test_children_preserve_uuid_and_data(self):
"""验证 children 中的 uuid 和 data 被正确保留"""
raw_data = self._make_tree_with_children()
enriched = _simulate_workstation_resource_enrichment(raw_data)
flask1 = enriched["children"]["Flask1"]
assert flask1["uuid"] == "uuid-flask-1"
assert flask1["data"]["liquid"][0]["liquid_type"] == "water"
assert flask1["data"]["liquid"][0]["volume"] == 10.0
flask2 = enriched["children"]["Flask2"]
assert flask2["uuid"] == "uuid-flask-2"
assert flask2["data"]["liquid"][0]["liquid_type"] == "ethanol"
def test_children_dict_can_be_popped(self):
"""模拟 batch_transfer_protocol 中 pop children 的操作"""
raw_data = self._make_tree_with_children()
enriched = _simulate_workstation_resource_enrichment(raw_data)
# batch_transfer_protocol 中会 pop children
children = enriched["children"]
popped = children.pop("Flask1")
assert popped["id"] == "Flask1"
assert "Flask1" not in enriched["children"]
assert "Flask2" in enriched["children"]
def test_children_dict_usable_as_from_repo(self):
"""模拟 batch_transfer_protocol 中 from_repo 参数"""
raw_data = self._make_tree_with_children()
enriched = _simulate_workstation_resource_enrichment(raw_data)
# 模拟编译器接收的 from_repo 格式
from_repo = {"StationA": enriched}
from_repo_ = list(from_repo.values())[0]
assert from_repo_["id"] == "StationA"
assert "Flask1" in from_repo_["children"]
assert from_repo_["children"]["Flask1"]["uuid"] == "uuid-flask-1"
def test_sequence_resource_enrichment(self):
"""sequence<Resource> 情况:多个独立资源树"""
raw_data1 = [_make_raw_resource(id="R1", uuid="uuid-r1")]
raw_data2 = [_make_raw_resource(id="R2", uuid="uuid-r2")]
tree_set1 = ResourceTreeSet.from_raw_dict_list(raw_data1)
tree_set2 = ResourceTreeSet.from_raw_dict_list(raw_data2)
results = [
tree.root_node.get_plr_nested_dict()
for ts in [tree_set1, tree_set2]
for tree in ts.trees
]
assert len(results) == 2
assert results[0]["id"] == "R1"
assert results[1]["id"] == "R2"
# ============ 全链路测试:动作列表结构验证 ============
class TestActionListStructure:
"""验证编译器返回的 action_list 结构符合 workstation 预期"""
def _validate_action(self, action):
"""验证单个 action dict 的结构"""
if action.get("action_name") == "wait":
# wait 伪动作不需要 device_id
assert "action_kwargs" in action
assert "time" in action["action_kwargs"]
return
if action.get("action_name") == "log_message":
# log 伪动作
assert "action_kwargs" in action
return
# 正常设备动作
assert "device_id" in action, f"action 缺少 device_id: {action}"
assert "action_name" in action, f"action 缺少 action_name: {action}"
assert "action_kwargs" in action, f"action 缺少 action_kwargs: {action}"
assert isinstance(action["action_kwargs"], dict)
def test_stir_action_list_structure(self):
from unilabos.compile.stir_protocol import generate_stir_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_stir_protocol(G=G, vessel=enriched, time="60")
for action in actions:
if isinstance(action, list):
# 并行动作
for sub_action in action:
self._validate_action(sub_action)
else:
self._validate_action(action)
def test_heatchill_action_list_structure(self):
from unilabos.compile.heatchill_protocol import generate_heat_chill_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_heat_chill_protocol(G=G, vessel=enriched, temp=80.0, time="60")
for action in actions:
if isinstance(action, list):
for sub_action in action:
self._validate_action(sub_action)
else:
self._validate_action(action)
def test_add_action_list_structure(self):
from unilabos.compile.add_protocol import generate_add_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
actions = generate_add_protocol(G=G, vessel=enriched, reagent="NaCl", mass="5 g")
for action in actions:
if isinstance(action, list):
for sub_action in action:
self._validate_action(sub_action)
else:
self._validate_action(action)
# ============ 全链路测试message_converter 到 enrichment ============
class TestMessageConverterToEnrichment:
"""模拟从 ROS 消息转换后的 dict 到 enrichment 的完整链路"""
def test_ros_goal_conversion_simulation(self):
"""
模拟 workstation.py 中的完整流程:
1. ROS goal 中的 vessel 字段被 convert_from_ros_msg 转换为浅层 dict
2. workstation 用 resource_id 请求 host 获取完整资源数据
3. ResourceTreeSet.from_raw_dict_list 构建资源树
4. get_plr_nested_dict 生成嵌套 dict 替换 protocol_kwargs[k]
"""
# 步骤1: 模拟 convert_from_ros_msg 的输出(浅层 dict只有 id 等基本字段)
shallow_vessel = {
"id": "reactor_01",
"uuid": "uuid-reactor-01",
"name": "reactor_01",
"type": "device",
"category": "virtual_stirrer",
"children": [],
"parent": "",
"parent_uuid": "",
"config": {},
"data": {},
"extra": {},
"position": {"x": 0.0, "y": 0.0, "z": 0.0},
}
protocol_kwargs = {
"vessel": shallow_vessel,
"time": "300",
"stir_speed": 300.0,
}
# 步骤2: 提取 resource_id
resource_id = protocol_kwargs["vessel"]["id"]
assert resource_id == "reactor_01"
# 步骤3: 模拟 host 返回完整数据(带 children
host_response = [
_make_raw_resource(
id="reactor_01", uuid="uuid-reactor-01",
klass="virtual_stirrer", type_="device",
data={"temperature": 25.0, "pressure": 1.0},
config={"max_temp": 300.0},
),
]
# 步骤4: enrichment
enriched = _simulate_workstation_resource_enrichment(host_response)
protocol_kwargs["vessel"] = enriched
# 验证 enrichment 后的 protocol_kwargs
assert protocol_kwargs["vessel"]["id"] == "reactor_01"
assert protocol_kwargs["vessel"]["uuid"] == "uuid-reactor-01"
assert protocol_kwargs["vessel"]["class"] == "virtual_stirrer"
assert protocol_kwargs["vessel"]["data"]["temperature"] == 25.0
assert protocol_kwargs["vessel"]["config"]["max_temp"] == 300.0
# 步骤5: 传给编译器
from unilabos.compile.stir_protocol import generate_stir_protocol
G = _build_test_graph()
actions = generate_stir_protocol(G=G, **protocol_kwargs)
assert len(actions) >= 1
assert actions[0]["device_id"] == "stirrer_1"
assert actions[0]["action_name"] == "stir"
def test_ros_goal_with_children_enrichment(self):
"""ROS goal → enrichment 带 children 的场景batch transfer"""
# 模拟 host 返回带 children 的数据
host_response = [
_make_raw_resource(
id="StationA", uuid="uuid-sa", klass="workstation", type_="device",
config={"num_items_x": 4, "num_items_y": 2},
),
_make_raw_resource(
id="Plate1", uuid="uuid-p1", type_="resource",
parent="StationA", parent_uuid="uuid-sa",
data={"sample": "sample_A"},
),
_make_raw_resource(
id="Plate2", uuid="uuid-p2", type_="resource",
parent="StationA", parent_uuid="uuid-sa",
data={"sample": "sample_B"},
),
]
enriched = _simulate_workstation_resource_enrichment(host_response)
assert enriched["id"] == "StationA"
assert enriched["class"] == "workstation"
assert len(enriched["children"]) == 2
assert enriched["children"]["Plate1"]["data"]["sample"] == "sample_A"
assert enriched["children"]["Plate2"]["uuid"] == "uuid-p2"
# 模拟 batch_transfer 的 from_repo 格式
from_repo = {"StationA": enriched}
from_repo_ = list(from_repo.values())[0]
assert "Plate1" in from_repo_["children"]
assert from_repo_["children"]["Plate1"]["uuid"] == "uuid-p1"
# ============ 全链路测试:多协议连续调用 ============
class TestMultiProtocolChain:
"""模拟连续执行多个协议(如 add → stir → heatchill"""
def test_sequential_protocol_execution(self):
"""模拟典型合成路径add → stir → heatchill"""
from unilabos.compile.stir_protocol import generate_stir_protocol
from unilabos.compile.heatchill_protocol import generate_heat_chill_protocol
from unilabos.compile.add_protocol import generate_add_protocol
raw_data = [_make_raw_resource(
id="reactor_01", uuid="uuid-reactor-01",
klass="virtual_stirrer", type_="device",
)]
enriched = _simulate_workstation_resource_enrichment(raw_data)
G = _build_test_graph()
# 每次调用用 enriched 的副本,避免编译器修改原数据
all_actions = []
# 步骤1: 添加试剂
add_actions = generate_add_protocol(
G=G, vessel=copy.deepcopy(enriched),
reagent="NaCl", mass="5 g",
)
all_actions.extend(add_actions)
# 步骤2: 搅拌
stir_actions = generate_stir_protocol(
G=G, vessel=copy.deepcopy(enriched),
time="60", stir_speed=300.0,
)
all_actions.extend(stir_actions)
# 步骤3: 加热
heat_actions = generate_heat_chill_protocol(
G=G, vessel=copy.deepcopy(enriched),
temp=80.0, time="300",
)
all_actions.extend(heat_actions)
# 验证总动作列表
assert len(all_actions) >= 3
# 每个协议至少产生一个核心动作
action_names = [a.get("action_name", "") for a in all_actions if isinstance(a, dict)]
assert "stir" in action_names
assert "heat_chill" in action_names
def test_enriched_resource_not_mutated(self):
"""验证编译器不应修改传入的 enriched dict如果需要修改应 deepcopy"""
from unilabos.compile.stir_protocol import generate_stir_protocol
raw_data = [_make_raw_resource(id="reactor_01")]
enriched = _simulate_workstation_resource_enrichment(raw_data)
original_id = enriched["id"]
original_uuid = enriched["uuid"]
G = _build_test_graph()
generate_stir_protocol(G=G, vessel=enriched, time="60")
# 验证 enriched dict 核心字段未被修改
assert enriched["id"] == original_id
assert enriched["uuid"] == original_uuid

View File

@@ -1,538 +0,0 @@
"""
PumpTransfer 和 Separate 全链路测试
构建包含泵/阀门/分液漏斗的完整设备图,
输出完整的中间数据(最短路径、泵骨架、动作列表等)。
"""
import copy
import json
import pprint
import pytest
import networkx as nx
from unilabos.resources.resource_tracker import ResourceTreeSet
from unilabos.compile.utils.resource_helper import get_resource_id, get_resource_data
from unilabos.compile.utils.vessel_parser import get_vessel
def _make_raw_resource(id, uuid=None, name=None, klass="", type_="device",
parent=None, parent_uuid=None, data=None, config=None, extra=None):
return {
"id": id,
"uuid": uuid or f"uuid-{id}",
"name": name or id,
"class": klass,
"type": type_,
"parent": parent,
"parent_uuid": parent_uuid or "",
"description": "",
"config": config or {},
"data": data or {},
"extra": extra or {},
"position": {"x": 0.0, "y": 0.0, "z": 0.0},
}
def _simulate_enrichment(raw_data_list):
tree_set = ResourceTreeSet.from_raw_dict_list(raw_data_list)
root = tree_set.trees[0].root_node if tree_set.trees else None
return root.get_plr_nested_dict() if root else {}
def _build_pump_transfer_graph():
"""
构建带泵/阀门的设备图,用于测试 PumpTransfer:
flask_water (container)
valve_1 (multiway_valve, pump_1 连接)
reactor_01 (device)
同时有: stirrer_1, heatchill_1, separator_1
"""
G = nx.DiGraph()
# 源容器
G.add_node("flask_water", **{
"id": "flask_water", "name": "flask_water",
"type": "container", "class": "",
"data": {"reagent_name": "water", "liquid": [{"liquid_type": "water", "volume": 200.0}]},
"config": {"reagent": "water"},
})
# 多通阀
G.add_node("valve_1", **{
"id": "valve_1", "name": "valve_1",
"type": "device", "class": "multiway_valve",
"data": {}, "config": {},
})
# 注射泵(连接到阀门)
G.add_node("pump_1", **{
"id": "pump_1", "name": "pump_1",
"type": "device", "class": "virtual_pump",
"data": {}, "config": {"max_volume": 25.0},
})
# 目标容器
G.add_node("reactor_01", **{
"id": "reactor_01", "name": "reactor_01",
"type": "device", "class": "virtual_stirrer",
"data": {"liquid": [{"liquid_type": "water", "volume": 50.0}]},
"config": {},
})
# 搅拌器
G.add_node("stirrer_1", **{
"id": "stirrer_1", "name": "stirrer_1",
"type": "device", "class": "virtual_stirrer",
"data": {}, "config": {},
})
# 加热器
G.add_node("heatchill_1", **{
"id": "heatchill_1", "name": "heatchill_1",
"type": "device", "class": "virtual_heatchill",
"data": {}, "config": {},
})
# 分离器
G.add_node("separator_1", **{
"id": "separator_1", "name": "separator_1",
"type": "device", "class": "separator_controller",
"data": {}, "config": {},
})
# 废液容器
G.add_node("waste_workup", **{
"id": "waste_workup", "name": "waste_workup",
"type": "container", "class": "",
"data": {}, "config": {},
})
# 产物收集瓶
G.add_node("product_flask", **{
"id": "product_flask", "name": "product_flask",
"type": "container", "class": "",
"data": {}, "config": {},
})
# DCM溶剂瓶
G.add_node("flask_dcm", **{
"id": "flask_dcm", "name": "flask_dcm",
"type": "container", "class": "",
"data": {"reagent_name": "dcm", "liquid": [{"liquid_type": "dcm", "volume": 500.0}]},
"config": {"reagent": "dcm"},
})
# 边连接 —— flask_water → valve_1 → reactor_01
G.add_edge("flask_water", "valve_1", port={"valve_1": "port_1"})
G.add_edge("valve_1", "reactor_01", port={"valve_1": "port_2"})
# 阀门 → 泵
G.add_edge("valve_1", "pump_1")
G.add_edge("pump_1", "valve_1")
# 搅拌器 ↔ reactor
G.add_edge("stirrer_1", "reactor_01")
# 加热器 ↔ reactor
G.add_edge("heatchill_1", "reactor_01")
# 分离器 ↔ reactor
G.add_edge("separator_1", "reactor_01")
G.add_edge("reactor_01", "separator_1")
# DCM → valve → reactor (同一泵路)
G.add_edge("flask_dcm", "valve_1", port={"valve_1": "port_3"})
# reactor → valve → product/waste
G.add_edge("valve_1", "product_flask", port={"valve_1": "port_4"})
G.add_edge("valve_1", "waste_workup", port={"valve_1": "port_5"})
return G
def _format_action(action, indent=0):
"""格式化单个 action 为可读字符串"""
prefix = " " * indent
if isinstance(action, list):
# 并行动作
lines = [f"{prefix}[PARALLEL]"]
for sub in action:
lines.append(_format_action(sub, indent + 1))
return "\n".join(lines)
name = action.get("action_name", "?")
device = action.get("device_id", "")
kwargs = action.get("action_kwargs", {})
comment = action.get("_comment", "")
meta = action.get("_transfer_meta", "")
parts = [f"{prefix}{device}::{name}"]
if kwargs:
# 精简输出
kw_str = ", ".join(f"{k}={v}" for k, v in kwargs.items()
if k not in ("progress_message",))
if kw_str:
parts.append(f" kwargs: {{{kw_str}}}")
if comment:
parts.append(f" # {comment}")
if meta:
parts.append(f" meta: {meta}")
return "\n".join(f"{prefix}{p}" if i > 0 else p for i, p in enumerate(parts))
def _dump_actions(actions, title=""):
"""打印完整动作列表"""
print(f"\n{'='*70}")
print(f" {title}")
print(f" 总动作数: {len(actions)}")
print(f"{'='*70}")
for i, action in enumerate(actions):
print(f"\n [{i:02d}] {_format_action(action, indent=2)}")
print(f"\n{'='*70}\n")
# ==================== PumpTransfer 全链路 ====================
class TestPumpTransferFullChain:
"""PumpTransfer: 包含图路径查找、泵骨架构建、动作序列生成"""
def test_pump_transfer_basic(self):
"""基础泵转移flask_water → valve_1 → reactor_01"""
from unilabos.compile.pump_protocol import generate_pump_protocol
G = _build_pump_transfer_graph()
# 检查最短路径
path = nx.shortest_path(G, "flask_water", "reactor_01")
print(f"\n最短路径: {path}")
assert "valve_1" in path
# 调用编译器
actions = generate_pump_protocol(
G=G,
from_vessel_id="flask_water",
to_vessel_id="reactor_01",
volume=10.0,
flowrate=2.5,
transfer_flowrate=0.5,
)
_dump_actions(actions, "PumpTransfer: flask_water → reactor_01, 10mL")
# 验证
assert isinstance(actions, list)
assert len(actions) > 0
# 应该有 set_valve_position 和 set_position 动作
flat = [a for a in actions if isinstance(a, dict)]
action_names = [a.get("action_name") for a in flat]
print(f"动作名称列表: {action_names}")
assert "set_valve_position" in action_names
assert "set_position" in action_names
def test_pump_transfer_with_rinsing_enriched_vessel(self):
"""pump_with_rinsing 接收 enriched vessel dict"""
from unilabos.compile.pump_protocol import generate_pump_protocol_with_rinsing
G = _build_pump_transfer_graph()
# 模拟 enrichment
from_raw = [_make_raw_resource(
id="flask_water", klass="", type_="container",
data={"reagent_name": "water", "liquid": [{"liquid_type": "water", "volume": 200.0}]},
)]
to_raw = [_make_raw_resource(
id="reactor_01", klass="virtual_stirrer", type_="device",
)]
from_enriched = _simulate_enrichment(from_raw)
to_enriched = _simulate_enrichment(to_raw)
print(f"\nfrom_vessel enriched: {json.dumps(from_enriched, indent=2, ensure_ascii=False)[:300]}...")
print(f"to_vessel enriched: {json.dumps(to_enriched, indent=2, ensure_ascii=False)[:300]}...")
# get_vessel 兼容
fid, fdata = get_vessel(from_enriched)
tid, tdata = get_vessel(to_enriched)
print(f"from_vessel_id={fid}, to_vessel_id={tid}")
assert fid == "flask_water"
assert tid == "reactor_01"
actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=from_enriched,
to_vessel=to_enriched,
volume=15.0,
flowrate=2.5,
transfer_flowrate=0.5,
)
_dump_actions(actions, "PumpTransferWithRinsing: flask_water → reactor_01, 15mL (enriched)")
assert isinstance(actions, list)
assert len(actions) > 0
def test_pump_transfer_multi_batch(self):
"""体积 > max_volume 时自动分批"""
from unilabos.compile.pump_protocol import generate_pump_protocol
G = _build_pump_transfer_graph()
# pump_1 的 max_volume = 25mL转 60mL 应该分 3 批
actions = generate_pump_protocol(
G=G,
from_vessel_id="flask_water",
to_vessel_id="reactor_01",
volume=60.0,
flowrate=2.5,
transfer_flowrate=0.5,
)
_dump_actions(actions, "PumpTransfer 分批: 60mL (max_volume=25mL, 预期 3 批)")
assert len(actions) > 0
# 应该有多轮 set_position
flat = [a for a in actions if isinstance(a, dict)]
set_position_count = sum(1 for a in flat if a.get("action_name") == "set_position")
print(f"set_position 动作数: {set_position_count}")
# 3批 × 2次 (吸液 + 排液) = 6 次 set_position
assert set_position_count >= 6
def test_pump_transfer_no_path(self):
"""无路径时返回空"""
from unilabos.compile.pump_protocol import generate_pump_protocol
G = _build_pump_transfer_graph()
G.add_node("isolated_flask", type="container")
actions = generate_pump_protocol(
G=G,
from_vessel_id="isolated_flask",
to_vessel_id="reactor_01",
volume=10.0,
)
print(f"\n无路径时的动作列表: {actions}")
assert actions == []
def test_pump_backbone_filtering(self):
"""验证泵骨架过滤逻辑(电磁阀被跳过)"""
from unilabos.compile.pump_protocol import generate_pump_protocol
G = _build_pump_transfer_graph()
# 添加电磁阀到路径中
G.add_node("solenoid_valve_1", **{
"type": "device", "class": "solenoid_valve",
"data": {}, "config": {},
})
# flask_water → solenoid_valve_1 → valve_1 → reactor_01
G.remove_edge("flask_water", "valve_1")
G.add_edge("flask_water", "solenoid_valve_1")
G.add_edge("solenoid_valve_1", "valve_1")
path = nx.shortest_path(G, "flask_water", "reactor_01")
print(f"\n含电磁阀的路径: {path}")
assert "solenoid_valve_1" in path
actions = generate_pump_protocol(
G=G,
from_vessel_id="flask_water",
to_vessel_id="reactor_01",
volume=10.0,
)
_dump_actions(actions, "PumpTransfer 含电磁阀: flask_water → solenoid → valve_1 → reactor_01")
# 电磁阀应被跳过,泵骨架只有 valve_1
assert len(actions) > 0
# ==================== Separate 全链路 ====================
class TestSeparateProtocolFullChain:
"""Separate: 包含 bug 确认和正常路径测试"""
def test_separate_bug_line_128_fixed(self):
"""验证 separate_protocol.py:128 的 bug 已修复(不再 crash"""
from unilabos.compile.separate_protocol import generate_separate_protocol
G = _build_pump_transfer_graph()
raw_data = [_make_raw_resource(
id="reactor_01", klass="virtual_stirrer",
data={"liquid": [{"liquid_type": "water", "volume": 100.0}]},
)]
enriched = _simulate_enrichment(raw_data)
# 修复前final_vessel_id, _ = vessel_id 会 crash字符串解包
# 修复后final_vessel_id = vessel_id正常返回 action 列表
result = generate_separate_protocol(
G=G,
vessel=enriched,
purpose="extract",
product_phase="top",
product_vessel="product_flask",
waste_vessel="waste_workup",
solvent="dcm",
volume="100 mL",
)
assert isinstance(result, list)
assert len(result) > 0
def test_separate_manual_workaround(self):
"""
绕过 line 128 bug手动测试分离编译器中可以工作的子函数
"""
from unilabos.compile.separate_protocol import (
find_separator_device,
find_separation_vessel_bottom,
)
from unilabos.compile.utils.vessel_parser import (
find_connected_stirrer,
find_solvent_vessel,
)
from unilabos.compile.utils.unit_parser import parse_volume_input
from unilabos.compile.utils.resource_helper import get_resource_liquid_volume as get_vessel_liquid_volume
G = _build_pump_transfer_graph()
# 1. get_vessel 解析 enriched dict
raw_data = [_make_raw_resource(
id="reactor_01", klass="virtual_stirrer",
data={"liquid": [{"liquid_type": "water", "volume": 100.0}]},
)]
enriched = _simulate_enrichment(raw_data)
vessel_id, vessel_data = get_vessel(enriched)
print(f"\nvessel_id: {vessel_id}")
print(f"vessel_data: {vessel_data}")
assert vessel_id == "reactor_01"
assert vessel_data["liquid"][0]["volume"] == 100.0
# 2. find_separator_device
sep = find_separator_device(G, vessel_id)
print(f"分离器设备: {sep}")
assert sep == "separator_1"
# 3. find_connected_stirrer
stirrer = find_connected_stirrer(G, vessel_id)
print(f"搅拌器设备: {stirrer}")
assert stirrer == "stirrer_1"
# 4. find_solvent_vessel
solvent_v = find_solvent_vessel(G, "dcm")
print(f"DCM溶剂容器: {solvent_v}")
assert solvent_v == "flask_dcm"
# 5. parse_volume_input
vol = parse_volume_input("200 mL")
print(f"体积解析: '200 mL'{vol}")
assert vol == 200.0
vol2 = parse_volume_input("1.5 L")
print(f"体积解析: '1.5 L'{vol2}")
assert vol2 == 1500.0
# 6. get_vessel_liquid_volume
liq_vol = get_vessel_liquid_volume(enriched)
print(f"液体体积 (enriched dict): {liq_vol}")
assert liq_vol == 100.0
# 7. find_separation_vessel_bottom
bottom = find_separation_vessel_bottom(G, vessel_id)
print(f"分离容器底部: {bottom}")
# 当前图中没有命名匹配的底部容器
def test_pump_transfer_for_separate_subflow(self):
"""测试 separate 中调用的 pump 子流程(溶剂添加 → 分液漏斗)"""
from unilabos.compile.pump_protocol import generate_pump_protocol_with_rinsing
G = _build_pump_transfer_graph()
# 模拟分离前的溶剂添加步骤
actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel="flask_dcm",
to_vessel="reactor_01",
volume=100.0,
flowrate=2.5,
transfer_flowrate=0.5,
)
_dump_actions(actions, "Separate 子流程: flask_dcm → reactor_01, 100mL DCM")
assert isinstance(actions, list)
assert len(actions) > 0
# 模拟分离后产物转移
actions2 = generate_pump_protocol_with_rinsing(
G=G,
from_vessel="reactor_01",
to_vessel="product_flask",
volume=50.0,
flowrate=2.5,
transfer_flowrate=0.5,
)
_dump_actions(actions2, "Separate 子流程: reactor_01 → product_flask, 50mL 产物")
assert len(actions2) > 0
# 废液转移
actions3 = generate_pump_protocol_with_rinsing(
G=G,
from_vessel="reactor_01",
to_vessel="waste_workup",
volume=50.0,
flowrate=2.5,
transfer_flowrate=0.5,
)
_dump_actions(actions3, "Separate 子流程: reactor_01 → waste_workup, 50mL 废液")
assert len(actions3) > 0
# ==================== 图路径可视化 ====================
class TestGraphPathVisualization:
"""输出图中关键路径信息"""
def test_all_shortest_paths(self):
"""输出所有容器之间的最短路径"""
G = _build_pump_transfer_graph()
containers = [n for n in G.nodes() if G.nodes[n].get("type") == "container"]
devices = [n for n in G.nodes() if G.nodes[n].get("type") == "device"]
print(f"\n{'='*70}")
print(f" 设备图概览")
print(f"{'='*70}")
print(f" 容器节点 ({len(containers)}): {containers}")
print(f" 设备节点 ({len(devices)}): {devices}")
print(f" 边数: {G.number_of_edges()}")
print(f" 边列表:")
for u, v, data in G.edges(data=True):
port_info = data.get("port", "")
print(f" {u}{v} {port_info if port_info else ''}")
print(f"\n 关键路径:")
pairs = [
("flask_water", "reactor_01"),
("flask_dcm", "reactor_01"),
("reactor_01", "product_flask"),
("reactor_01", "waste_workup"),
("flask_water", "product_flask"),
]
for src, dst in pairs:
try:
path = nx.shortest_path(G, src, dst)
length = len(path) - 1
# 标注路径上的节点类型
annotated = []
for n in path:
ntype = G.nodes[n].get("type", "?")
nclass = G.nodes[n].get("class", "")
annotated.append(f"{n}({ntype}{'/' + nclass if nclass else ''})")
print(f" {src}{dst}: 距离={length}")
print(f" 路径: {''.join(annotated)}")
except nx.NetworkXNoPath:
print(f" {src}{dst}: 无路径!")
print(f"{'='*70}\n")

View File

@@ -1,324 +0,0 @@
"""
ROS Goal → Resource 转换 → 编译器路径的集成测试
覆盖:
1. Resource.msg 新字段(uuid, klass, extra)的往返转换
2. dict → ROS Resource → dict 往返无损
3. ResourceTreeSet → get_plr_nested_dict 保留 children 结构
4. resource_helper 兼容 dict / ResourceDictInstance
5. vessel_parser.get_vessel 兼容 ResourceDictInstance
"""
import json
import pytest
# 不依赖 ROS 的测试 —— 直接测试 resource 处理路径
from unilabos.resources.resource_tracker import (
ResourceDict,
ResourceDictInstance,
ResourceTreeInstance,
ResourceTreeSet,
)
from unilabos.compile.utils.resource_helper import (
ensure_resource_instance,
resource_to_dict,
get_resource_id,
get_resource_data,
get_resource_display_info,
get_resource_liquid_volume,
)
from unilabos.compile.utils.vessel_parser import get_vessel
# ============ 构建测试数据 ============
def _make_resource_dict(
id="reactor_01",
uuid="uuid-reactor-01",
name="reactor_01",
klass="virtual_stirrer",
type_="device",
parent=None,
parent_uuid=None,
data=None,
config=None,
extra=None,
):
return {
"id": id,
"uuid": uuid,
"name": name,
"class": klass,
"type": type_,
"parent": parent,
"parent_uuid": parent_uuid or "",
"description": "",
"config": config or {},
"data": data or {},
"extra": extra or {},
"position": {"x": 1.0, "y": 2.0, "z": 3.0},
}
def _make_resource_instance(id="reactor_01", **kwargs):
d = _make_resource_dict(id=id, **kwargs)
return ResourceDictInstance.get_resource_instance_from_dict(d)
def _make_tree_with_children():
"""构建 StationA -> [R1, R2] 的资源树"""
raw_data = [
_make_resource_dict(
id="StationA",
uuid="uuid-station-a",
name="StationA",
klass="workstation",
type_="device",
),
_make_resource_dict(
id="R1",
uuid="uuid-r1",
name="R1",
klass="",
type_="resource",
parent="StationA",
parent_uuid="uuid-station-a",
data={"liquid": [{"liquid_type": "water", "volume": 10.0}]},
),
_make_resource_dict(
id="R2",
uuid="uuid-r2",
name="R2",
klass="",
type_="resource",
parent="StationA",
parent_uuid="uuid-station-a",
data={"liquid": [{"liquid_type": "ethanol", "volume": 5.0}]},
),
]
tree_set = ResourceTreeSet.from_raw_dict_list(raw_data)
return tree_set
# ============ resource_helper 测试 ============
class TestResourceHelper:
"""测试 resource_helper 对 dict / ResourceDictInstance 的兼容性"""
def test_ensure_resource_instance_from_dict(self):
d = _make_resource_dict()
inst = ensure_resource_instance(d)
assert isinstance(inst, ResourceDictInstance)
assert inst.res_content.id == "reactor_01"
assert inst.res_content.uuid == "uuid-reactor-01"
def test_ensure_resource_instance_passthrough(self):
inst = _make_resource_instance()
result = ensure_resource_instance(inst)
assert result is inst # 同一个对象,不复制
def test_ensure_resource_instance_none(self):
assert ensure_resource_instance(None) is None
def test_get_resource_id_from_dict(self):
d = _make_resource_dict(id="my_device")
assert get_resource_id(d) == "my_device"
def test_get_resource_id_from_instance(self):
inst = _make_resource_instance(id="my_device")
assert get_resource_id(inst) == "my_device"
def test_get_resource_id_from_string(self):
assert get_resource_id("my_device") == "my_device"
def test_get_resource_id_from_wrapped_dict(self):
"""兼容 {station_id: {...}} 格式"""
d = {"StationA": {"id": "StationA", "name": "StationA"}}
assert get_resource_id(d) == "StationA"
def test_get_resource_data_from_dict(self):
d = _make_resource_dict(data={"temperature": 25.0})
assert get_resource_data(d) == {"temperature": 25.0}
def test_get_resource_data_from_instance(self):
inst = _make_resource_instance(data={"temperature": 25.0})
data = get_resource_data(inst)
assert data["temperature"] == 25.0
def test_get_resource_display_info_from_dict(self):
d = _make_resource_dict(id="reactor_01", name="Reactor #1")
info = get_resource_display_info(d)
assert "reactor_01" in info
assert "Reactor #1" in info
def test_get_resource_display_info_from_instance(self):
inst = _make_resource_instance(id="reactor_01", name="Reactor #1")
info = get_resource_display_info(inst)
assert "reactor_01" in info
def test_get_resource_display_info_from_string(self):
assert get_resource_display_info("reactor_01") == "reactor_01"
def test_get_resource_liquid_volume(self):
d = _make_resource_dict(data={"liquid": [{"liquid_type": "water", "volume": 15.5}]})
assert get_resource_liquid_volume(d) == pytest.approx(15.5)
def test_resource_to_dict_from_instance(self):
inst = _make_resource_instance(id="reactor_01", klass="virtual_stirrer")
d = resource_to_dict(inst)
assert isinstance(d, dict)
assert d["id"] == "reactor_01"
assert d["class"] == "virtual_stirrer"
def test_resource_to_dict_passthrough(self):
d = _make_resource_dict()
result = resource_to_dict(d)
assert result is d # 同一个 dict
# ============ vessel_parser 兼容性测试 ============
class TestVesselParser:
"""测试 vessel_parser.get_vessel 对 ResourceDictInstance 的兼容"""
def test_get_vessel_from_dict(self):
d = _make_resource_dict(id="reactor_01", data={"temperature": 25.0})
vessel_id, vessel_data = get_vessel(d)
assert vessel_id == "reactor_01"
assert vessel_data["temperature"] == 25.0
def test_get_vessel_from_string(self):
vessel_id, vessel_data = get_vessel("reactor_01")
assert vessel_id == "reactor_01"
assert vessel_data == {}
def test_get_vessel_from_resource_instance(self):
inst = _make_resource_instance(id="reactor_01", data={"temperature": 25.0})
vessel_id, vessel_data = get_vessel(inst)
assert vessel_id == "reactor_01"
assert vessel_data["temperature"] == 25.0
def test_get_vessel_from_wrapped_dict(self):
"""兼容 {station_id: {id: ..., data: {...}}} 格式"""
d = {"StationA": {"id": "StationA", "data": {"vol": 100}}}
vessel_id, vessel_data = get_vessel(d)
assert vessel_id == "StationA"
# ============ ResourceTreeSet → get_plr_nested_dict 测试 ============
class TestResourceTreeRoundTrip:
"""测试 ResourceTreeSet → get_plr_nested_dict 保留树结构和关键字段"""
def test_tree_preserves_children(self):
tree_set = _make_tree_with_children()
assert len(tree_set.trees) == 1
root = tree_set.trees[0].root_node
assert root.res_content.id == "StationA"
assert len(root.children) == 2
def test_plr_nested_dict_has_children(self):
tree_set = _make_tree_with_children()
root = tree_set.trees[0].root_node
nested = root.get_plr_nested_dict()
assert isinstance(nested, dict)
assert "children" in nested
assert isinstance(nested["children"], dict)
assert "R1" in nested["children"]
assert "R2" in nested["children"]
def test_plr_nested_dict_preserves_uuid(self):
tree_set = _make_tree_with_children()
root = tree_set.trees[0].root_node
nested = root.get_plr_nested_dict()
assert nested["uuid"] == "uuid-station-a"
assert nested["children"]["R1"]["uuid"] == "uuid-r1"
def test_plr_nested_dict_preserves_klass(self):
tree_set = _make_tree_with_children()
root = tree_set.trees[0].root_node
nested = root.get_plr_nested_dict()
assert nested["class"] == "workstation"
def test_plr_nested_dict_preserves_data(self):
tree_set = _make_tree_with_children()
root = tree_set.trees[0].root_node
nested = root.get_plr_nested_dict()
r1_data = nested["children"]["R1"]["data"]
assert "liquid" in r1_data
assert r1_data["liquid"][0]["volume"] == 10.0
def test_plr_nested_dict_usable_by_get_vessel(self):
"""get_plr_nested_dict 的结果可以直接传给 get_vessel"""
tree_set = _make_tree_with_children()
root = tree_set.trees[0].root_node
nested = root.get_plr_nested_dict()
vessel_id, vessel_data = get_vessel(nested)
assert vessel_id == "StationA"
def test_dump_vs_plr_nested_dict(self):
"""dump() 是扁平化的get_plr_nested_dict 保留树结构"""
tree_set = _make_tree_with_children()
# dump 返回扁平列表
dumped = tree_set.dump()
assert isinstance(dumped[0], list)
assert len(dumped[0]) == 3 # StationA + R1 + R2全部扁平
# get_plr_nested_dict 保留嵌套
root = tree_set.trees[0].root_node
nested = root.get_plr_nested_dict()
assert isinstance(nested["children"], dict)
assert len(nested["children"]) == 2 # 嵌套的 children
# ============ 模拟 workstation 路径测试 ============
class TestWorkstationPath:
"""模拟 workstation.py 中的关键路径:
raw_data → ResourceTreeSet.from_raw_dict_list → get_plr_nested_dict → compiler
"""
def test_single_resource_path(self):
"""单个 Resource: 取第一棵树的根节点"""
raw_data = [
_make_resource_dict(id="reactor_01", uuid="uuid-r01", klass="virtual_stirrer"),
]
tree_set = ResourceTreeSet.from_raw_dict_list(raw_data)
root = tree_set.trees[0].root_node
result = root.get_plr_nested_dict()
assert result["id"] == "reactor_01"
assert result["uuid"] == "uuid-r01"
assert result["class"] == "virtual_stirrer"
def test_resource_with_children_path(self):
"""Resource 带 children: AGV/batch transfer 场景"""
tree_set = _make_tree_with_children()
root = tree_set.trees[0].root_node
nested = root.get_plr_nested_dict()
# 模拟编译器接收到的参数
from_repo = {"StationA": nested}
assert "A01" not in from_repo["StationA"]["children"] # children 按 id 索引
assert "R1" in from_repo["StationA"]["children"]
assert from_repo["StationA"]["children"]["R1"]["uuid"] == "uuid-r1"
def test_multiple_resource_path(self):
"""多个 Resource: 每棵树取根节点"""
raw_data1 = [_make_resource_dict(id="R1", uuid="uuid-r1")]
raw_data2 = [_make_resource_dict(id="R2", uuid="uuid-r2")]
# 模拟 host 返回多棵树
tree_set1 = ResourceTreeSet.from_raw_dict_list(raw_data1)
tree_set2 = ResourceTreeSet.from_raw_dict_list(raw_data2)
results = [
tree.root_node.get_plr_nested_dict()
for ts in [tree_set1, tree_set2]
for tree in ts.trees
]
assert len(results) == 2
assert results[0]["id"] == "R1"
assert results[1]["id"] == "R2"

View File

@@ -1,137 +0,0 @@
"""
AGVTransportStation driver 测试
覆盖初始化、carrier property、slot 查询、路由查询、capacity 计算。
"""
import pytest
from unittest.mock import MagicMock, patch
from unilabos.devices.transport.agv_workstation import AGVTransportStation
from unilabos.resources.warehouse import WareHouse, warehouse_factory
class TestAGVTransportStation:
def _make_driver(self, route_table=None, device_roles=None):
"""创建一个 AGVTransportStation 实例"""
return AGVTransportStation(
deck=None,
route_table=route_table or {
"A->B": {"nav_command": '{"target":"LM1"}', "arm_pick": "pick.urp", "arm_place": "place.urp"}
},
device_roles=device_roles or {"navigator": "agv_nav", "arm": "agv_arm"},
)
def _make_warehouse(self, name="agv_platform", nx=2, ny=1, nz=1):
"""创建一个测试用 Warehouse"""
return warehouse_factory(name=name, num_items_x=nx, num_items_y=ny, num_items_z=nz)
def test_init_deck_none(self):
"""AGVTransportStation 初始化时 deck=None"""
driver = self._make_driver()
assert driver.deck is None
def test_init_route_table(self):
"""路由表正确存储"""
driver = self._make_driver()
assert "A->B" in driver.route_table
def test_init_device_roles(self):
"""设备角色正确存储"""
driver = self._make_driver()
assert driver.device_roles["navigator"] == "agv_nav"
assert driver.device_roles["arm"] == "agv_arm"
def test_carrier_without_ros_node(self):
"""未 post_init 时 carrier 返回 None"""
driver = self._make_driver()
assert driver.carrier is None
def test_carrier_with_warehouse(self):
"""post_init 后 carrier 返回正确的 WareHouse"""
driver = self._make_driver()
wh = self._make_warehouse()
# 模拟 ros_node 和 resource_tracker
mock_ros_node = MagicMock()
mock_ros_node.resource_tracker.resources = [wh]
mock_ros_node.device_id = "AGV"
driver.post_init(mock_ros_node)
assert driver.carrier is wh
assert isinstance(driver.carrier, WareHouse)
def test_capacity(self):
"""容量计算正确"""
driver = self._make_driver()
wh = self._make_warehouse(nx=2, ny=1, nz=1)
mock_ros_node = MagicMock()
mock_ros_node.resource_tracker.resources = [wh]
mock_ros_node.device_id = "AGV"
driver.post_init(mock_ros_node)
assert driver.capacity == 2
def test_capacity_multi_layer(self):
"""多层 Warehouse 容量"""
driver = self._make_driver()
wh = self._make_warehouse(nx=1, ny=2, nz=3)
mock_ros_node = MagicMock()
mock_ros_node.resource_tracker.resources = [wh]
mock_ros_node.device_id = "AGV"
driver.post_init(mock_ros_node)
assert driver.capacity == 6
def test_capacity_no_carrier(self):
"""无 carrier 时容量为 0"""
driver = self._make_driver()
assert driver.capacity == 0
def test_free_slots(self):
"""空载时所有 slot 为空闲"""
driver = self._make_driver()
wh = self._make_warehouse(nx=2, ny=1, nz=1)
mock_ros_node = MagicMock()
mock_ros_node.resource_tracker.resources = [wh]
mock_ros_node.device_id = "AGV"
driver.post_init(mock_ros_node)
free = driver.free_slots
assert len(free) == 2
def test_occupied_slots_empty(self):
"""空载时 occupied_slots 为空"""
driver = self._make_driver()
wh = self._make_warehouse(nx=2, ny=1, nz=1)
mock_ros_node = MagicMock()
mock_ros_node.resource_tracker.resources = [wh]
mock_ros_node.device_id = "AGV"
driver.post_init(mock_ros_node)
assert len(driver.occupied_slots) == 0
def test_resolve_route(self):
"""路由查询返回正确的指令"""
driver = self._make_driver()
route = driver.resolve_route("A", "B")
assert route["nav_command"] == '{"target":"LM1"}'
assert route["arm_pick"] == "pick.urp"
def test_resolve_route_not_found(self):
"""查询不存在的路线时抛出 KeyError"""
driver = self._make_driver()
with pytest.raises(KeyError, match="路由表"):
driver.resolve_route("X", "Y")
def test_get_device_id(self):
"""获取子设备 ID"""
driver = self._make_driver()
assert driver.get_device_id("navigator") == "agv_nav"
assert driver.get_device_id("arm") == "agv_arm"
def test_get_device_id_not_found(self):
"""获取不存在的角色时抛出 KeyError"""
driver = self._make_driver()
with pytest.raises(KeyError, match="未配置设备角色"):
driver.get_device_id("gripper")

View File

@@ -1 +1 @@
__version__ = "0.10.19"
__version__ = "0.11.2"

View File

@@ -12,6 +12,15 @@ from typing import Dict, Any, List
import networkx as nx
import yaml
# Windows 中文系统 stdout 默认 GBK无法编码 banner / emoji 日志中的 Unicode 字符
# 强制 stdout/stderr 用 UTF-8避免 print 触发 UnicodeEncodeError 导致进程崩溃
if sys.platform == "win32":
for _stream in (sys.stdout, sys.stderr):
try:
_stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]
except (AttributeError, OSError):
pass
# 首先添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
unilabos_dir = os.path.dirname(os.path.dirname(current_dir))
@@ -233,7 +242,7 @@ def parse_args():
parser.add_argument(
"--addr",
type=str,
default="https://uni-lab.bohrium.com/api/v1",
default="https://leap-lab.bohrium.com/api/v1",
help="Laboratory backend address",
)
parser.add_argument(
@@ -438,10 +447,10 @@ def main():
if args.addr != parser.get_default("addr"):
if args.addr == "test":
print_status("使用测试环境地址", "info")
HTTPConfig.remote_addr = "https://uni-lab.test.bohrium.com/api/v1"
HTTPConfig.remote_addr = "https://leap-lab.test.bohrium.com/api/v1"
elif args.addr == "uat":
print_status("使用uat环境地址", "info")
HTTPConfig.remote_addr = "https://uni-lab.uat.bohrium.com/api/v1"
HTTPConfig.remote_addr = "https://leap-lab.uat.bohrium.com/api/v1"
elif args.addr == "local":
print_status("使用本地环境地址", "info")
HTTPConfig.remote_addr = "http://127.0.0.1:48197/api/v1"
@@ -553,13 +562,8 @@ def main():
os._exit(0)
if not BasicConfig.ak or not BasicConfig.sk:
if BasicConfig.test_mode:
print_status("测试模式:跳过 ak/sk 检查,使用占位凭据", "warning")
BasicConfig.ak = BasicConfig.ak or "test_ak"
BasicConfig.sk = BasicConfig.sk or "test_sk"
else:
print_status("后续运行必须拥有一个实验室,请前往 https://uni-lab.bohrium.com 注册实验室!", "warning")
os._exit(1)
print_status("后续运行必须拥有一个实验室,请前往 https://leap-lab.bohrium.com 注册实验室!", "warning")
os._exit(1)
graph: nx.Graph
resource_tree_set: ResourceTreeSet
resource_links: List[Dict[str, Any]]
@@ -626,6 +630,8 @@ def main():
continue
# 如果从远端获取了物料信息,则与本地物料进行同步
# 仅在本地文件模式下有意义:本地文件只含设备结构,远端有已保存的物料,需要 merge
# 远端模式下 resource_tree_set 与 request_startup_json 来自同一份数据merge 为空操作
if file_path is not None and request_startup_json and "nodes" in request_startup_json:
print_status("开始同步远端物料到本地...", "info")
remote_tree_set = ResourceTreeSet.from_raw_dict_list(request_startup_json["nodes"])

View File

@@ -59,6 +59,7 @@ class JobAddReq(BaseModel):
task_id: str = Field(examples=["task_id"], description="task uuid (auto-generated if empty)", default="")
job_id: str = Field(examples=["job_id"], description="goal uuid (auto-generated if empty)", default="")
node_id: str = Field(examples=["node_id"], description="node uuid", default="")
notebook_id: str = Field(examples=["notebook_id"], description="notebook uuid", default="")
server_info: dict = Field(
examples=[{"send_timestamp": 1717000000.0}],
description="server info (auto-generated if empty)",

View File

@@ -10,29 +10,170 @@ import shutil
import sys
_PATCH_MARKER = "# UniLabOS DLL Patch"
_PATCH_END_MARKER = "# End UniLabOS DLL Patch"
# 75 = EX_TEMPFAIL: 临时失败、重试即可,避免与业务退出码冲突
_RESTART_EXIT_CODE = 75
def _build_dll_patch(lib_bin: str, preload_pyd: str = "") -> str:
"""生成一段加在目标文件顶部的 DLL 加载补丁源码。
- 始终把 ``lib_bin`` 加入 DLL 搜索路径,并把 handle 挂在模块属性上,
防止 GC 清掉搜索路径(``os.add_dll_directory`` 的句柄被回收时
目录会被移除)。
- 可选地用 ``ctypes.CDLL`` 预加载一个 .pyd把它的依赖 DLL 提前装入
进程内存,作为 ``rclpy._rclpy_pybind11`` 这类首次加载点的兜底。
"""
# 用 repr() 序列化路径Python 解析 repr 的结果会还原成原始字符串,
# 不需要也不能再叠加 raw-string 前缀(叠了反而会让 \\ 变成两个反斜杠)。
lines = [
_PATCH_MARKER,
"import os as _ulab_os",
f"_ulab_p = {lib_bin!r}",
'if hasattr(_ulab_os, "add_dll_directory") and _ulab_os.path.isdir(_ulab_p):',
" try: _UNILAB_DLL_HANDLE = _ulab_os.add_dll_directory(_ulab_p)",
" except Exception: _UNILAB_DLL_HANDLE = None",
]
if preload_pyd:
lines.extend(
[
"import ctypes as _ulab_ctypes",
f"try: _ulab_ctypes.CDLL({preload_pyd!r})",
"except Exception: pass",
]
)
lines.append(_PATCH_END_MARKER)
return "\n".join(lines) + "\n"
def _apply_dll_patch(file_path: str, lib_bin: str, preload_pyd: str = "") -> bool:
"""把 DLL 补丁前置到 ``file_path``。文件不存在或已打过补丁则返回 False。"""
if not os.path.isfile(file_path):
return False
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
if _PATCH_MARKER in content:
return False
shutil.copy2(file_path, file_path + ".bak")
with open(file_path, "w", encoding="utf-8") as f:
f.write(_build_dll_patch(lib_bin, preload_pyd) + content)
return True
def _print_restart_banner(patched_files):
"""打印重启提示并以 EX_TEMPFAIL 退出。
- 不使用 ANSI 颜色码Windows 旧版 cmd / PowerShell 5 默认不开 VT 处理,
会把 ``\\033[1;33m`` 当做字面字符显示,反而让用户看不到正文。
- 同时写入 stderr 与 stdout某些上层 launcher / supervisor 只重定向
其中一路,写两遍能保证用户至少看到一份。
- 写入前防御性把流切到 UTF-8 with replace``main.py`` 里已经做过一次,
但本模块也可能被绕过 ``main.py`` 的代码路径直接 importreconfigure
失败也只是退回 errors=replace不影响整体流程。
"""
if sys.platform == "win32":
for _stream in (sys.stdout, sys.stderr):
try:
_stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]
except (AttributeError, OSError):
pass
bar = "#" * 78
files_lines = [f"[UniLabOS] - {p}" for p in patched_files]
body = "\n".join(
[
"",
bar,
bar,
"##",
"## [UniLabOS] Windows + conda 下检测到 DLL 加载失败,已自动打补丁。",
"## [UniLabOS] DLL load failure detected on Windows + conda;",
"## [UniLabOS] the following files have been auto-patched:",
"##",
*[f"## {line}" for line in files_lines],
"##",
"## [UniLabOS] 当前进程的 rclpy 状态已损坏,补丁需要在新进程才生效。",
"## [UniLabOS] The current process is unusable; the patch only takes",
"## [UniLabOS] effect on a fresh process.",
"##",
"## >>> 请重新运行刚才的命令 / Please re-run the same command. <<<",
"##",
bar,
bar,
"",
]
)
for stream in (sys.stderr, sys.stdout):
try:
stream.write(body)
stream.flush()
except Exception:
try:
print(body, file=stream)
except Exception:
pass
sys.exit(_RESTART_EXIT_CODE)
def patch_rclpy_dll_windows():
"""在 Windows + conda 环境下 rclpy 打 DLL 加载补丁"""
"""在 Windows + conda 环境下修复 rclpy / rosidl typesupport 的 DLL 加载。
背景conda 安装的 ros 系列包,其原生扩展依赖 ``$CONDA_PREFIX/Library/bin``
下的 DLL只有 conda 环境被正确激活、且 PATH 中含 ``Library/bin`` 时,
``os.add_dll_directory`` 才能找到它们。当从快捷方式 / IDE / 子进程 /
没激活的 shell 启动 ``unilab`` 时,会出现 ``DLL load failed``。
本函数会:
1) 修补 ``rclpy/impl/implementation_singleton.py`` —— rclpy 自身的 C 扩展入口;
2) 修补 ``rpyutils/add_dll_directories.py`` —— 所有 ``*_s__rosidl_typesupport_c.pyd``
``geometry_msgs`` / ``std_msgs`` / ``sensor_msgs`` 等)的统一加载入口。
打完补丁后**必须重启进程**才能生效(当前进程的 rclpy 已经发生过
``ImportError``,子模块仍处于损坏状态)。因此函数会主动退出,并在
stdout/stderr 同时打印明显的重启提示,避免用户被后续报错淹没。
"""
if sys.platform != "win32" or not os.environ.get("CONDA_PREFIX"):
return
try:
import rclpy
import rclpy # noqa: F401
return
except ImportError as e:
if not str(e).startswith("DLL load failed"):
return
cp = os.environ["CONDA_PREFIX"]
impl = os.path.join(cp, "Lib", "site-packages", "rclpy", "impl", "implementation_singleton.py")
pyd = glob.glob(os.path.join(cp, "Lib", "site-packages", "rclpy", "_rclpy_pybind11*.pyd"))
if not os.path.exists(impl) or not pyd:
lib_bin = os.path.join(cp, "Library", "bin")
site_packages = os.path.join(cp, "Lib", "site-packages")
if not os.path.isdir(lib_bin):
return
with open(impl, "r", encoding="utf-8") as f:
content = f.read()
lib_bin = os.path.join(cp, "Library", "bin").replace("\\", "/")
patch = f'# UniLabOS DLL Patch\nimport os,ctypes\nos.add_dll_directory("{lib_bin}") if hasattr(os,"add_dll_directory") else None\ntry: ctypes.CDLL("{pyd[0].replace(chr(92),"/")}")\nexcept: pass\n# End Patch\n'
shutil.copy2(impl, impl + ".bak")
with open(impl, "w", encoding="utf-8") as f:
f.write(patch + content)
patched = []
# 1) rclpy 自身的入口
rclpy_impl = os.path.join(site_packages, "rclpy", "impl", "implementation_singleton.py")
rclpy_pyd_matches = glob.glob(os.path.join(site_packages, "rclpy", "_rclpy_pybind11*.pyd"))
rclpy_pyd = rclpy_pyd_matches[0] if rclpy_pyd_matches else ""
if rclpy_pyd and _apply_dll_patch(rclpy_impl, lib_bin, preload_pyd=rclpy_pyd):
patched.append(rclpy_impl)
# 2) rpyutils —— 所有 rosidl typesupport pyd 的加载点;放在 rclpy 之后
# 例geometry_msgs/geometry_msgs_s__rosidl_typesupport_c.pyd
rpyutils_dll = os.path.join(site_packages, "rpyutils", "add_dll_directories.py")
if _apply_dll_patch(rpyutils_dll, lib_bin):
patched.append(rpyutils_dll)
if not patched:
# 已经打过补丁但 rclpy 仍然加载失败:原因不是缺 DLL 搜索路径,
# 不要再次打补丁污染文件,让上层看到真实的 ImportError。
return
_print_restart_banner(patched)
patch_rclpy_dll_windows()

View File

@@ -36,6 +36,9 @@ class HTTPClient:
auth_secret = BasicConfig.auth_secret()
self.auth = auth_secret
info(f"正在使用ak sk作为授权信息[{auth_secret}]")
# 复用 TCP/TLS 连接,避免每次请求重新握手
self._session = requests.Session()
self._session.headers.update({"Authorization": f"Lab {self.auth}"})
info(f"HTTPClient 初始化完成: remote_addr={self.remote_addr}")
def resource_edge_add(self, resources: List[Dict[str, Any]]) -> requests.Response:
@@ -48,7 +51,7 @@ class HTTPClient:
Returns:
Response: API响应对象
"""
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/edge/material/edge",
json={
"edges": resources,
@@ -75,25 +78,28 @@ class HTTPClient:
Returns:
Dict[str, str]: 旧UUID到新UUID的映射关系 {old_uuid: new_uuid}
"""
with open(os.path.join(BasicConfig.working_dir, "req_resource_tree_add.json"), "w", encoding="utf-8") as f:
payload = {"nodes": [x for xs in resources.dump() for x in xs], "mount_uuid": mount_uuid}
f.write(json.dumps(payload, indent=4))
# 从序列化数据中提取所有节点的UUID保存旧UUID
# dump() 只调用一次,复用给文件保存和 HTTP 请求
nodes_info = [x for xs in resources.dump() for x in xs]
old_uuids = {n.res_content.uuid: n for n in resources.all_nodes}
payload = {"nodes": nodes_info, "mount_uuid": mount_uuid}
body_bytes = _fast_dumps(payload)
with open(os.path.join(BasicConfig.working_dir, "req_resource_tree_add.json"), "wb") as f:
f.write(_fast_dumps_pretty(payload))
http_headers = {"Content-Type": "application/json"}
if not self.initialized or first_add:
self.initialized = True
info(f"首次添加资源,当前远程地址: {self.remote_addr}")
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/edge/material",
json={"nodes": [x for xs in resources.dump() for x in xs], "mount_uuid": mount_uuid},
headers={"Authorization": f"Lab {self.auth}"},
data=body_bytes,
headers=http_headers,
timeout=60,
)
else:
response = requests.put(
response = self._session.put(
f"{self.remote_addr}/edge/material",
json={"nodes": [x for xs in resources.dump() for x in xs], "mount_uuid": mount_uuid},
headers={"Authorization": f"Lab {self.auth}"},
data=body_bytes,
headers=http_headers,
timeout=10,
)
@@ -111,6 +117,7 @@ class HTTPClient:
uuid_mapping[i["uuid"]] = i["cloud_uuid"]
else:
logger.error(f"添加物料失败: {response.text}")
logger.trace(f"添加物料失败: {nodes_info}")
for u, n in old_uuids.items():
if u in uuid_mapping:
n.res_content.uuid = uuid_mapping[u]
@@ -131,7 +138,7 @@ class HTTPClient:
"""
with open(os.path.join(BasicConfig.working_dir, "req_resource_tree_get.json"), "w", encoding="utf-8") as f:
f.write(json.dumps({"uuids": uuid_list, "with_children": with_children}, indent=4))
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/edge/material/query",
json={"uuids": uuid_list, "with_children": with_children},
headers={"Authorization": f"Lab {self.auth}"},
@@ -145,6 +152,7 @@ class HTTPClient:
logger.error(f"查询物料失败: {response.text}")
else:
data = res["data"]["nodes"]
logger.trace(f"resource_tree_get查询到物料: {data}")
return data
else:
logger.error(f"查询物料失败: {response.text}")
@@ -162,14 +170,14 @@ class HTTPClient:
if not self.initialized:
self.initialized = True
info(f"首次添加资源,当前远程地址: {self.remote_addr}")
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/lab/material",
json={"nodes": resources},
headers={"Authorization": f"Lab {self.auth}"},
timeout=100,
)
else:
response = requests.put(
response = self._session.put(
f"{self.remote_addr}/lab/material",
json={"nodes": resources},
headers={"Authorization": f"Lab {self.auth}"},
@@ -196,7 +204,7 @@ class HTTPClient:
"""
with open(os.path.join(BasicConfig.working_dir, "req_resource_get.json"), "w", encoding="utf-8") as f:
f.write(json.dumps({"id": id, "with_children": with_children}, indent=4))
response = requests.get(
response = self._session.get(
f"{self.remote_addr}/lab/material",
params={"id": id, "with_children": with_children},
headers={"Authorization": f"Lab {self.auth}"},
@@ -237,14 +245,14 @@ class HTTPClient:
if not self.initialized:
self.initialized = True
info(f"首次添加资源,当前远程地址: {self.remote_addr}")
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/lab/material",
json={"nodes": resources},
headers={"Authorization": f"Lab {self.auth}"},
timeout=100,
)
else:
response = requests.put(
response = self._session.put(
f"{self.remote_addr}/lab/material",
json={"nodes": resources},
headers={"Authorization": f"Lab {self.auth}"},
@@ -274,7 +282,7 @@ class HTTPClient:
with open(file_path, "rb") as file:
files = {"files": file}
logger.info(f"上传文件: {file_path}{scene}")
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/api/account/file_upload/{scene}",
files=files,
headers={"Authorization": f"Lab {self.auth}"},
@@ -314,7 +322,7 @@ class HTTPClient:
"Content-Type": "application/json",
"Content-Encoding": "gzip",
}
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/lab/resource",
data=compressed_body,
headers=headers,
@@ -348,7 +356,7 @@ class HTTPClient:
Returns:
Response: API响应对象
"""
response = requests.get(
response = self._session.get(
f"{self.remote_addr}/edge/material/download",
headers={"Authorization": f"Lab {self.auth}"},
timeout=(3, 30),
@@ -409,7 +417,7 @@ class HTTPClient:
with open(os.path.join(BasicConfig.working_dir, "req_workflow_upload.json"), "w", encoding="utf-8") as f:
f.write(json.dumps(payload, indent=4, ensure_ascii=False))
response = requests.post(
response = self._session.post(
f"{self.remote_addr}/lab/workflow/owner/import",
json=payload,
headers={"Authorization": f"Lab {self.auth}"},

View File

@@ -320,6 +320,7 @@ def job_add(req: JobAddReq) -> JobData:
action_name=action_name,
task_id=task_id,
job_id=job_id,
notebook_id=req.notebook_id,
device_action_key=device_action_key,
)

View File

@@ -59,6 +59,7 @@ class QueueItem:
action_name: str
task_id: str
job_id: str
notebook_id: str
device_action_key: str
next_run_time: float = 0 # 下次执行时间戳
retry_count: int = 0 # 重试次数
@@ -71,6 +72,7 @@ class JobInfo:
job_id: str
task_id: str
device_id: str
notebook_id: str
action_name: str
device_action_key: str
status: JobStatus
@@ -539,7 +541,10 @@ class MessageProcessor:
self.reconnect_count += 1
backoff = WSConfig.reconnect_interval
logger.info(
f"[MessageProcessor] 即将在 {backoff} 秒后重连 (已尝试 {self.reconnect_count}/{WSConfig.max_reconnect_attempts})"
"[MessageProcessor] 即将在 %s 秒后重连 (已尝试 %s/%s)",
backoff,
self.reconnect_count,
WSConfig.max_reconnect_attempts,
)
await asyncio.sleep(backoff)
else:
@@ -703,6 +708,7 @@ class MessageProcessor:
action_name = data.get("action_name", "")
task_id = data.get("task_id", "")
job_id = data.get("job_id", "")
notebook_id = data.get("notebook_id", "")
if not all([device_id, action_name, task_id, job_id]):
logger.error("[MessageProcessor] Missing required fields in query_action_state")
@@ -718,6 +724,7 @@ class MessageProcessor:
job_id=job_id,
task_id=task_id,
device_id=device_id,
notebook_id=notebook_id,
action_name=action_name,
device_action_key=device_action_key,
status=JobStatus.QUEUE,
@@ -732,13 +739,27 @@ class MessageProcessor:
if can_start_immediately:
# 可以立即开始
await self._send_action_state_response(
device_id, action_name, task_id, job_id, "query_action_status", True, 0
device_id,
action_name,
task_id,
job_id,
"query_action_status",
True,
0,
notebook_id=notebook_id,
)
logger.trace(f"[MessageProcessor] Job {job_log} can start immediately")
else:
# 需要排队
await self._send_action_state_response(
device_id, action_name, task_id, job_id, "query_action_status", False, 10
device_id,
action_name,
task_id,
job_id,
"query_action_status",
False,
10,
notebook_id=notebook_id,
)
logger.trace(f"[MessageProcessor] Job {job_log} queued")
@@ -768,6 +789,7 @@ class MessageProcessor:
job_id=req.job_id,
task_id=req.task_id,
device_id=req.device_id,
notebook_id=req.notebook_id,
action_name=action_name,
device_action_key=device_action_key,
status=JobStatus.QUEUE,
@@ -775,11 +797,16 @@ class MessageProcessor:
always_free=True,
)
self.device_manager.add_queue_request(job_info)
existing_job = job_info
logger.info(f"[MessageProcessor] Job {job_log} always_free, auto-registered from direct job_start")
else:
logger.error(f"[MessageProcessor] Job {job_log} not registered (missing query_action_state)")
return
if existing_job and req.notebook_id and not existing_job.notebook_id:
existing_job.notebook_id = req.notebook_id
notebook_id = req.notebook_id or (existing_job.notebook_id if existing_job else "")
success = self.device_manager.start_job(req.job_id)
if not success:
logger.error(f"[MessageProcessor] Failed to start job {job_log}")
@@ -795,6 +822,7 @@ class MessageProcessor:
action_name=req.action,
task_id=req.task_id,
job_id=req.job_id,
notebook_id=notebook_id,
device_action_key=device_action_key,
)
@@ -834,6 +862,7 @@ class MessageProcessor:
"job_id": req.job_id,
"task_id": req.task_id,
"device_id": req.device_id,
"notebook_id": queue_item.notebook_id,
"action_name": req.action,
"status": "failed",
"feedback_data": {},
@@ -855,6 +884,7 @@ class MessageProcessor:
"query_action_status",
True,
0,
notebook_id=next_job.notebook_id,
)
next_job_log = format_job_log(
next_job.job_id, next_job.task_id, next_job.device_id, next_job.action_name
@@ -1101,7 +1131,15 @@ class MessageProcessor:
logger.info(f"[MessageProcessor] Restart cleanup scheduled")
async def _send_action_state_response(
self, device_id: str, action_name: str, task_id: str, job_id: str, typ: str, free: bool, need_more: int
self,
device_id: str,
action_name: str,
task_id: str,
job_id: str,
typ: str,
free: bool,
need_more: int,
notebook_id: str = "",
):
"""发送动作状态响应"""
message = {
@@ -1112,8 +1150,9 @@ class MessageProcessor:
"action_name": action_name,
"task_id": task_id,
"job_id": job_id,
"notebook_id": notebook_id,
"free": free,
"need_more": need_more,
"need_more": need_more + 1,
},
}
@@ -1194,6 +1233,7 @@ class QueueProcessor:
action_name=timeout_job.action_name,
task_id=timeout_job.task_id,
job_id=timeout_job.job_id,
notebook_id=timeout_job.notebook_id,
device_action_key=timeout_job.device_action_key,
)
# 发布超时失败状态这会触发正常的job完成流程
@@ -1252,8 +1292,9 @@ class QueueProcessor:
"action_name": job_info.action_name,
"task_id": job_info.task_id,
"job_id": job_info.job_id,
"notebook_id": job_info.notebook_id,
"free": False,
"need_more": 10,
"need_more": 10 + 1,
},
}
self.message_processor.send_message(message)
@@ -1269,7 +1310,13 @@ class QueueProcessor:
if not queued_jobs:
return
logger.debug(f"[QueueProcessor] Sending busy status for {len(queued_jobs)} queued jobs")
queue_summary = {}
for j in queued_jobs:
key = f"{j.device_id}/{j.action_name}"
queue_summary[key] = queue_summary.get(key, 0) + 1
logger.debug(
f"[QueueProcessor] Sending busy status for {len(queued_jobs)} queued jobs: {queue_summary}"
)
for job_info in queued_jobs:
# 快照可能已过期:在遍历过程中 end_job() 可能已将此 job 移至 READY
@@ -1285,8 +1332,9 @@ class QueueProcessor:
"action_name": job_info.action_name,
"task_id": job_info.task_id,
"job_id": job_info.job_id,
"notebook_id": job_info.notebook_id,
"free": False,
"need_more": 10,
"need_more": 10 + 1,
},
}
success = self.message_processor.send_message(message)
@@ -1330,12 +1378,15 @@ class QueueProcessor:
"action_name": next_job.action_name,
"task_id": next_job.task_id,
"job_id": next_job.job_id,
"notebook_id": next_job.notebook_id,
"free": True,
"need_more": 0,
},
}
self.message_processor.send_message(message)
# next_job_log = format_job_log(next_job.job_id, next_job.task_id, next_job.device_id, next_job.action_name)
# next_job_log = format_job_log(
# next_job.job_id, next_job.task_id, next_job.device_id, next_job.action_name
# )
# logger.debug(f"[QueueProcessor] Notified next job {next_job_log} can start")
# 立即触发下一轮状态检查
@@ -1369,6 +1420,10 @@ class WebSocketClient(BaseCommunicationClient):
self.message_processor = MessageProcessor(self.websocket_url, self.send_queue, self.device_manager)
self.queue_processor = QueueProcessor(self.device_manager, self.message_processor)
# running状态debounce缓存: {job_id: (last_send_timestamp, last_feedback_data)}
self._job_running_last_sent: Dict[str, tuple] = {}
self._job_running_debounce_interval: float = 10.0 # 秒
# 设置相互引用
self.message_processor.set_queue_processor(self.queue_processor)
self.message_processor.set_websocket_client(self)
@@ -1468,28 +1523,39 @@ class WebSocketClient(BaseCommunicationClient):
logger.debug(f"[WebSocketClient] Not connected, cannot publish job status for job_id: {item.job_id}")
return
job_log = format_job_log(item.job_id, item.task_id, item.device_id, item.action_name)
# 拦截最终结果状态,与原版本逻辑一致
if status in ["success", "failed"]:
self._job_running_last_sent.pop(item.job_id, None)
host_node = HostNode.get_instance(0)
if host_node:
# 从HostNode的device_action_status中移除job_id
try:
host_node._device_action_status[item.device_action_key].job_ids.pop(item.job_id, None)
except (KeyError, AttributeError):
logger.warning(f"[WebSocketClient] Failed to remove job {item.job_id} from HostNode status")
# logger.debug(f"[WebSocketClient] Intercepting final status for job_id: {item.job_id} - {status}")
# 通知队列处理器job完成包括timeout的job
self.queue_processor.handle_job_completed(item.job_id, status)
# 发送job状态消息
# running状态按job_id做debounce内容变化时仍然上报
if status == "running":
now = time.time()
cached = self._job_running_last_sent.get(item.job_id)
if cached is not None:
last_ts, last_data = cached
if now - last_ts < self._job_running_debounce_interval and last_data == feedback_data:
logger.trace(f"[WebSocketClient] Job status debounced (skip): {job_log} - {status}")
return
self._job_running_last_sent[item.job_id] = (now, feedback_data)
message = {
"action": "job_status",
"data": {
"job_id": item.job_id,
"task_id": item.task_id,
"device_id": item.device_id,
"notebook_id": item.notebook_id,
"action_name": item.action_name,
"status": status,
"feedback_data": feedback_data,
@@ -1499,7 +1565,6 @@ class WebSocketClient(BaseCommunicationClient):
}
self.message_processor.send_message(message)
job_log = format_job_log(item.job_id, item.task_id, item.device_id, item.action_name)
logger.trace(f"[WebSocketClient] Job status published: {job_log} - {status}")
def send_ping(self, ping_id: str, timestamp: float) -> None:

View File

@@ -5,7 +5,6 @@ from .separate_protocol import generate_separate_protocol
from .evaporate_protocol import generate_evaporate_protocol
from .evacuateandrefill_protocol import generate_evacuateandrefill_protocol
from .agv_transfer_protocol import generate_agv_transfer_protocol
from .batch_transfer_protocol import generate_batch_transfer_protocol
from .add_protocol import generate_add_protocol
from .centrifuge_protocol import generate_centrifuge_protocol
from .filter_protocol import generate_filter_protocol
@@ -32,7 +31,6 @@ from .hydrogenate_protocol import generate_hydrogenate_protocol
action_protocol_generators = {
AddProtocol: generate_add_protocol,
AGVTransferProtocol: generate_agv_transfer_protocol,
BatchTransferProtocol: generate_batch_transfer_protocol,
AdjustPHProtocol: generate_adjust_ph_protocol,
CentrifugeProtocol: generate_centrifuge_protocol,
CleanProtocol: generate_clean_protocol,

View File

@@ -1,127 +0,0 @@
"""
AGV 编译器共用工具函数
从 physical_setup_graph 中发现 AGV 节点配置,
供 agv_transfer_protocol 和 batch_transfer_protocol 复用。
"""
from typing import Any, Dict, List, Optional
import networkx as nx
def find_agv_config(G: nx.Graph, agv_id: Optional[str] = None) -> Dict[str, Any]:
"""从设备图中发现 AGV 节点,返回其配置
查找策略:
1. 如果指定 agv_id直接读取该节点
2. 否则查找 class 为 "agv_transport_station" 的节点
3. 兜底查找 config 中包含 device_roles 的 workstation 节点
Returns:
{
"agv_id": str,
"device_roles": {"navigator": "...", "arm": "..."},
"route_table": {"A->B": {"nav_command": ..., "arm_pick": ..., "arm_place": ...}},
"capacity": int,
}
"""
if agv_id and agv_id in G.nodes:
node_data = G.nodes[agv_id]
config = _extract_config(node_data)
if config and "device_roles" in config:
return _build_agv_cfg(agv_id, config, G)
# 查找 agv_transport_station 类型
for nid, ndata in G.nodes(data=True):
node_class = _get_node_class(ndata)
if node_class == "agv_transport_station":
config = _extract_config(ndata)
return _build_agv_cfg(nid, config or {}, G)
# 兜底:查找带有 device_roles 的 workstation
for nid, ndata in G.nodes(data=True):
node_class = _get_node_class(ndata)
if node_class == "workstation":
config = _extract_config(ndata)
if config and "device_roles" in config:
return _build_agv_cfg(nid, config, G)
raise ValueError("设备图中未找到 AGV 节点(需 class=agv_transport_station 或 config.device_roles")
def get_agv_capacity(G: nx.Graph, agv_id: str) -> int:
"""从 AGV 的 Warehouse 子节点计算载具容量"""
for neighbor in G.successors(agv_id) if G.is_directed() else G.neighbors(agv_id):
ndata = G.nodes[neighbor]
node_type = _get_node_type(ndata)
if node_type == "warehouse":
config = _extract_config(ndata)
if config:
x = config.get("num_items_x", 1)
y = config.get("num_items_y", 1)
z = config.get("num_items_z", 1)
return x * y * z
# 如果没有 warehouse 子节点,尝试从配置中读取
return 0
def split_batches(items: list, capacity: int) -> List[list]:
"""按 AGV 容量分批
Args:
items: 待转运的物料列表
capacity: AGV 单批次容量
Returns:
分批后的列表的列表
"""
if capacity <= 0:
raise ValueError(f"AGV 容量必须 > 0当前: {capacity}")
return [items[i:i + capacity] for i in range(0, len(items), capacity)]
def _extract_config(node_data: dict) -> Optional[dict]:
"""从节点数据中提取 config 字段,兼容多种格式"""
# 直接 config 字段
config = node_data.get("config")
if isinstance(config, dict):
return config
# res_content 嵌套格式
res_content = node_data.get("res_content")
if hasattr(res_content, "config"):
return res_content.config if isinstance(res_content.config, dict) else None
if isinstance(res_content, dict):
return res_content.get("config")
return None
def _get_node_class(node_data: dict) -> str:
"""获取节点的 class 字段"""
res_content = node_data.get("res_content")
if hasattr(res_content, "model_dump"):
d = res_content.model_dump()
return d.get("class_", d.get("class", ""))
if isinstance(res_content, dict):
return res_content.get("class_", res_content.get("class", ""))
return node_data.get("class_", node_data.get("class", ""))
def _get_node_type(node_data: dict) -> str:
"""获取节点的 type 字段"""
res_content = node_data.get("res_content")
if hasattr(res_content, "type"):
return res_content.type or ""
if isinstance(res_content, dict):
return res_content.get("type", "")
return node_data.get("type", "")
def _build_agv_cfg(agv_id: str, config: dict, G: nx.Graph) -> Dict[str, Any]:
"""构建标准化的 AGV 配置"""
return {
"agv_id": agv_id,
"device_roles": config.get("device_roles", {}),
"route_table": config.get("route_table", {}),
"capacity": get_agv_capacity(G, agv_id),
}

View File

@@ -2,13 +2,20 @@ from functools import partial
import networkx as nx
import re
import logging
from typing import List, Dict, Any, Union
from .utils.unit_parser import parse_volume_input, parse_mass_input, parse_time_input
from .utils.vessel_parser import get_vessel, find_solid_dispenser, find_connected_stirrer, find_reagent_vessel
from .utils.logger_util import action_log, debug_print
from .utils.logger_util import action_log
from .pump_protocol import generate_pump_protocol_with_rinsing
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[ADD] {message}")
# 🆕 创建进度日志动作
create_action_log = partial(action_log, prefix="[ADD]")

View File

@@ -1,12 +1,14 @@
from functools import partial
import networkx as nx
import logging
from typing import List, Dict, Any, Union
from .utils.vessel_parser import get_vessel, find_connected_stirrer
from .utils.logger_util import action_log, debug_print
from .utils.vessel_parser import get_vessel
from .pump_protocol import generate_pump_protocol_with_rinsing
create_action_log = partial(action_log, prefix="[ADJUST_PH]")
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[ADJUST_PH] {message}")
def find_acid_base_vessel(G: nx.DiGraph, reagent: str) -> str:
"""
@@ -19,6 +21,8 @@ def find_acid_base_vessel(G: nx.DiGraph, reagent: str) -> str:
Returns:
str: 试剂容器ID
"""
debug_print(f"🔍 正在查找试剂 '{reagent}' 的容器...")
# 常见酸碱试剂的别名映射
reagent_aliases = {
"hydrochloric acid": ["HCl", "hydrochloric_acid", "hcl", "muriatic_acid"],
@@ -32,13 +36,17 @@ def find_acid_base_vessel(G: nx.DiGraph, reagent: str) -> str:
# 构建搜索名称列表
search_names = [reagent.lower()]
debug_print(f"📋 基础搜索名称: {reagent.lower()}")
# 添加别名
for base_name, aliases in reagent_aliases.items():
if reagent.lower() in base_name.lower() or base_name.lower() in reagent.lower():
search_names.extend([alias.lower() for alias in aliases])
debug_print(f"🔗 添加别名: {aliases}")
break
debug_print(f"📝 完整搜索列表: {search_names}")
# 构建可能的容器名称
possible_names = []
for name in search_names:
@@ -53,15 +61,17 @@ def find_acid_base_vessel(G: nx.DiGraph, reagent: str) -> str:
name_clean
])
debug_print(f"搜索容器: {len(possible_names)} 个候选名称")
debug_print(f"🎯 可能的容器名称 (前5个): {possible_names[:5]}... (共{len(possible_names)}个)")
# 第一步:通过容器名称匹配
debug_print(f"📋 方法1: 精确名称匹配...")
for vessel_name in possible_names:
if vessel_name in G.nodes():
debug_print(f"通过名称匹配找到容器: {vessel_name}")
debug_print(f"通过名称匹配找到容器: {vessel_name} 🎯")
return vessel_name
# 第二步:通过模糊匹配
debug_print(f"📋 方法2: 模糊名称匹配...")
for node_id in G.nodes():
if G.nodes[node_id].get('type') == 'container':
node_name = G.nodes[node_id].get('name', '').lower()
@@ -69,10 +79,11 @@ def find_acid_base_vessel(G: nx.DiGraph, reagent: str) -> str:
# 检查是否包含任何搜索名称
for search_name in search_names:
if search_name in node_id.lower() or search_name in node_name:
debug_print(f"通过模糊匹配找到容器: {node_id}")
debug_print(f"通过模糊匹配找到容器: {node_id} 🔍")
return node_id
# 第三步:通过液体类型匹配
debug_print(f"📋 方法3: 液体类型匹配...")
for node_id in G.nodes():
if G.nodes[node_id].get('type') == 'container':
vessel_data = G.nodes[node_id].get('data', {})
@@ -85,15 +96,56 @@ def find_acid_base_vessel(G: nx.DiGraph, reagent: str) -> str:
for search_name in search_names:
if search_name in liquid_type or search_name in reagent_name:
debug_print(f"通过液体类型匹配找到容器: {node_id}")
debug_print(f"通过液体类型匹配找到容器: {node_id} 💧")
return node_id
# 列出可用容器帮助调试
available_containers = [node_id for node_id in G.nodes()
if G.nodes[node_id].get('type') == 'container']
debug_print(f"所有匹配方法失败,可用容器: {available_containers}")
debug_print(f"📊 列出可用容器帮助调试...")
available_containers = []
for node_id in G.nodes():
if G.nodes[node_id].get('type') == 'container':
vessel_data = G.nodes[node_id].get('data', {})
liquids = vessel_data.get('liquid', [])
liquid_types = [liquid.get('liquid_type', '') or liquid.get('name', '')
for liquid in liquids if isinstance(liquid, dict)]
available_containers.append({
'id': node_id,
'name': G.nodes[node_id].get('name', ''),
'liquids': liquid_types,
'reagent_name': vessel_data.get('reagent_name', '')
})
debug_print(f"📋 可用容器列表:")
for container in available_containers:
debug_print(f" - 🧪 {container['id']}: {container['name']}")
debug_print(f" 💧 液体: {container['liquids']}")
debug_print(f" 🏷️ 试剂: {container['reagent_name']}")
debug_print(f"❌ 所有匹配方法都失败了")
raise ValueError(f"找不到试剂 '{reagent}' 对应的容器。尝试了: {possible_names[:10]}...")
def find_connected_stirrer(G: nx.DiGraph, vessel: str) -> str:
"""查找与容器相连的搅拌器"""
debug_print(f"🔍 查找连接到容器 '{vessel}' 的搅拌器...")
stirrer_nodes = [node for node in G.nodes()
if (G.nodes[node].get('class') or '') == 'virtual_stirrer']
debug_print(f"📊 发现 {len(stirrer_nodes)} 个搅拌器: {stirrer_nodes}")
for stirrer in stirrer_nodes:
if G.has_edge(stirrer, vessel) or G.has_edge(vessel, stirrer):
debug_print(f"✅ 找到连接的搅拌器: {stirrer} 🔗")
return stirrer
if stirrer_nodes:
debug_print(f"⚠️ 未找到直接连接的搅拌器,使用第一个: {stirrer_nodes[0]} 🔄")
return stirrer_nodes[0]
debug_print(f"❌ 未找到任何搅拌器")
return None
def calculate_reagent_volume(target_ph_value: float, reagent: str, vessel_volume: float = 100.0) -> float:
"""
估算需要的试剂体积来调节pH
@@ -106,30 +158,44 @@ def calculate_reagent_volume(target_ph_value: float, reagent: str, vessel_volume
Returns:
float: 估算的试剂体积 (mL)
"""
debug_print(f"计算试剂体积: pH={target_ph_value}, reagent={reagent}, vessel={vessel_volume}mL")
# 简化的pH调节体积估算
debug_print(f"🧮 计算试剂体积...")
debug_print(f" 📍 目标pH: {target_ph_value}")
debug_print(f" 🧪 试剂: {reagent}")
debug_print(f" 📏 容器体积: {vessel_volume}mL")
# 简化的pH调节体积估算实际应用中需要更精确的计算
if "acid" in reagent.lower() or "hcl" in reagent.lower():
debug_print(f"🍋 检测到酸性试剂")
# 酸性试剂pH越低需要的体积越大
if target_ph_value < 3:
volume = vessel_volume * 0.05
volume = vessel_volume * 0.05 # 5%
debug_print(f" 💪 强酸性 (pH<3): 使用 5% 体积")
elif target_ph_value < 5:
volume = vessel_volume * 0.02
volume = vessel_volume * 0.02 # 2%
debug_print(f" 🔸 中酸性 (pH<5): 使用 2% 体积")
else:
volume = vessel_volume * 0.01
volume = vessel_volume * 0.01 # 1%
debug_print(f" 🔹 弱酸性 (pH≥5): 使用 1% 体积")
elif "hydroxide" in reagent.lower() or "naoh" in reagent.lower():
debug_print(f"🧂 检测到碱性试剂")
# 碱性试剂pH越高需要的体积越大
if target_ph_value > 11:
volume = vessel_volume * 0.05
volume = vessel_volume * 0.05 # 5%
debug_print(f" 💪 强碱性 (pH>11): 使用 5% 体积")
elif target_ph_value > 9:
volume = vessel_volume * 0.02
volume = vessel_volume * 0.02 # 2%
debug_print(f" 🔸 中碱性 (pH>9): 使用 2% 体积")
else:
volume = vessel_volume * 0.01
volume = vessel_volume * 0.01 # 1%
debug_print(f" 🔹 弱碱性 (pH≤9): 使用 1% 体积")
else:
# 未知试剂,使用默认值
volume = vessel_volume * 0.01
debug_print(f"估算试剂体积: {volume:.2f}mL")
debug_print(f"❓ 未知试剂类型,使用默认 1% 体积")
debug_print(f"📊 计算结果: {volume:.2f}mL")
return volume
def generate_adjust_ph_protocol(
@@ -154,67 +220,96 @@ def generate_adjust_ph_protocol(
"""
vessel_id, vessel_data = get_vessel(vessel)
if not vessel_id:
debug_print(f"❌ vessel 参数无效必须包含id字段或直接提供容器ID. vessel: {vessel}")
raise ValueError("vessel 参数无效必须包含id字段或直接提供容器ID")
debug_print(f"pH调节协议: vessel={vessel_id}, ph={ph_value}, reagent='{reagent}'")
debug_print("=" * 60)
debug_print("🧪 开始生成pH调节协议")
debug_print(f"📋 原始参数:")
debug_print(f" 🥼 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 📊 ph_value: {ph_value}")
debug_print(f" 🧪 reagent: '{reagent}'")
debug_print(f" 📦 kwargs: {kwargs}")
debug_print("=" * 60)
action_sequence = []
# 从kwargs中获取可选参数
volume = kwargs.get('volume', 0.0)
stir = kwargs.get('stir', True)
stir_speed = kwargs.get('stir_speed', 300.0)
stir_time = kwargs.get('stir_time', 60.0)
settling_time = kwargs.get('settling_time', 30.0)
# 从kwargs中获取可选参数,如果没有则使用默认值
volume = kwargs.get('volume', 0.0) # 自动估算体积
stir = kwargs.get('stir', True) # 默认搅拌
stir_speed = kwargs.get('stir_speed', 300.0) # 默认搅拌速度
stir_time = kwargs.get('stir_time', 60.0) # 默认搅拌时间
settling_time = kwargs.get('settling_time', 30.0) # 默认平衡时间
debug_print(f"🔧 处理后的参数:")
debug_print(f" 📏 volume: {volume}mL (0.0表示自动估算)")
debug_print(f" 🌪️ stir: {stir}")
debug_print(f" 🔄 stir_speed: {stir_speed}rpm")
debug_print(f" ⏱️ stir_time: {stir_time}s")
debug_print(f" ⏳ settling_time: {settling_time}s")
# 开始处理
action_sequence.append(create_action_log(f"开始调节pH至 {ph_value}", "🧪"))
action_sequence.append(create_action_log(f"目标容器: {vessel_id}", "🥼"))
action_sequence.append(create_action_log(f"使用试剂: {reagent}", "⚗️"))
# 1. 验证目标容器存在
debug_print(f"🔍 步骤1: 验证目标容器...")
if vessel_id not in G.nodes():
debug_print(f"❌ 目标容器 '{vessel_id}' 不存在于系统中")
raise ValueError(f"目标容器 '{vessel_id}' 不存在于系统中")
debug_print(f"✅ 目标容器验证通过")
action_sequence.append(create_action_log("目标容器验证通过", ""))
# 2. 查找酸碱试剂容器
debug_print(f"🔍 步骤2: 查找试剂容器...")
action_sequence.append(create_action_log("正在查找试剂容器...", "🔍"))
try:
reagent_vessel = find_acid_base_vessel(G, reagent)
debug_print(f"✅ 找到试剂容器: {reagent_vessel}")
action_sequence.append(create_action_log(f"找到试剂容器: {reagent_vessel}", "🧪"))
except ValueError as e:
debug_print(f"❌ 无法找到试剂容器: {str(e)}")
action_sequence.append(create_action_log(f"试剂容器查找失败: {str(e)}", ""))
raise ValueError(f"无法找到试剂 '{reagent}': {str(e)}")
# 3. 体积估算
debug_print(f"🔍 步骤3: 体积处理...")
if volume <= 0:
action_sequence.append(create_action_log("开始自动估算试剂体积", "🧮"))
# 获取目标容器的体积信息
vessel_data = G.nodes[vessel_id].get('data', {})
vessel_volume = vessel_data.get('max_volume', 100.0)
vessel_volume = vessel_data.get('max_volume', 100.0) # 默认100mL
debug_print(f"📏 容器最大体积: {vessel_volume}mL")
estimated_volume = calculate_reagent_volume(ph_value, reagent, vessel_volume)
volume = estimated_volume
debug_print(f"✅ 自动估算试剂体积: {volume:.2f} mL")
action_sequence.append(create_action_log(f"估算试剂体积: {volume:.2f}mL", "📊"))
else:
debug_print(f"📏 使用指定体积: {volume}mL")
action_sequence.append(create_action_log(f"使用指定体积: {volume}mL", "📏"))
# 4. 验证路径存在
debug_print(f"🔍 步骤4: 路径验证...")
action_sequence.append(create_action_log("验证转移路径...", "🛤️"))
try:
path = nx.shortest_path(G, source=reagent_vessel, target=vessel_id)
action_sequence.append(create_action_log(f"找到转移路径: {' -> '.join(path)}", "🛤️"))
debug_print(f"找到路径: {' '.join(path)}")
action_sequence.append(create_action_log(f"找到转移路径: {''.join(path)}", "🛤️"))
except nx.NetworkXNoPath:
debug_print(f"❌ 无法找到转移路径")
action_sequence.append(create_action_log("转移路径不存在", ""))
raise ValueError(f"从试剂容器 '{reagent_vessel}' 到目标容器 '{vessel_id}' 没有可用路径")
# 5. 搅拌器设置
debug_print(f"🔍 步骤5: 搅拌器设置...")
stirrer_id = None
if stir:
action_sequence.append(create_action_log("准备启动搅拌器", "🌪️"))
@@ -223,6 +318,7 @@ def generate_adjust_ph_protocol(
stirrer_id = find_connected_stirrer(G, vessel_id)
if stirrer_id:
debug_print(f"✅ 找到搅拌器 {stirrer_id},启动搅拌")
action_sequence.append(create_action_log(f"启动搅拌器 {stirrer_id} (速度: {stir_speed}rpm)", "🔄"))
action_sequence.append({
@@ -242,18 +338,23 @@ def generate_adjust_ph_protocol(
"action_kwargs": {"time": 5}
})
else:
debug_print(f"⚠️ 未找到搅拌器,继续执行")
action_sequence.append(create_action_log("未找到搅拌器,跳过搅拌", "⚠️"))
except Exception as e:
debug_print(f"❌ 搅拌器配置出错: {str(e)}")
action_sequence.append(create_action_log(f"搅拌器配置失败: {str(e)}", ""))
else:
debug_print(f"📋 跳过搅拌设置")
action_sequence.append(create_action_log("跳过搅拌设置", "⏭️"))
# 6. 试剂添加
debug_print(f"🔍 步骤6: 试剂添加...")
action_sequence.append(create_action_log(f"开始添加试剂 {volume:.2f}mL", "🚰"))
# 计算添加时间pH调节需要缓慢添加
addition_time = max(30.0, volume * 2.0)
addition_time = max(30.0, volume * 2.0) # 至少30秒每mL需要2秒
debug_print(f"⏱️ 计算添加时间: {addition_time}s (缓慢注入)")
action_sequence.append(create_action_log(f"设置添加时间: {addition_time:.0f}s (缓慢注入)", "⏱️"))
try:
@@ -276,28 +377,35 @@ def generate_adjust_ph_protocol(
)
action_sequence.extend(pump_actions)
debug_print(f"✅ 泵协议生成完成,添加了 {len(pump_actions)} 个动作")
action_sequence.append(create_action_log(f"试剂转移完成 ({len(pump_actions)} 个操作)", ""))
# 体积运算 - 试剂添加成功后更新容器液体体积
# 🔧 修复体积运算 - 试剂添加成功后更新容器液体体积
debug_print(f"🔧 更新容器液体体积...")
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
debug_print(f"📊 添加前容器体积: {current_volume}")
# 处理不同的体积数据格式
if isinstance(current_volume, list):
if len(current_volume) > 0:
# 增加体积(添加试剂)
vessel["data"]["liquid_volume"][0] += volume
debug_print(f"📊 添加后容器体积: {vessel['data']['liquid_volume'][0]:.2f}mL (+{volume:.2f}mL)")
else:
# 如果列表为空,创建新的体积记录
vessel["data"]["liquid_volume"] = [volume]
debug_print(f"📊 初始化容器体积: {volume:.2f}mL")
elif isinstance(current_volume, (int, float)):
# 直接数值类型
vessel["data"]["liquid_volume"] += volume
debug_print(f"📊 添加后容器体积: {vessel['data']['liquid_volume']:.2f}mL (+{volume:.2f}mL)")
else:
debug_print(f"未知的体积数据格式: {type(current_volume)}")
debug_print(f"⚠️ 未知的体积数据格式: {type(current_volume)}")
# 创建新的体积记录
vessel["data"]["liquid_volume"] = volume
else:
debug_print(f"📊 容器无液体体积数据,创建新记录: {volume:.2f}mL")
# 确保vessel有data字段
if "data" not in vessel:
vessel["data"] = {}
@@ -315,16 +423,19 @@ def generate_adjust_ph_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = current_node_volume + volume
debug_print(f"✅ 图节点体积数据已更新")
action_sequence.append(create_action_log(f"容器体积已更新 (+{volume:.2f}mL)", "📊"))
except Exception as e:
debug_print(f"生成泵协议时出错: {str(e)}")
debug_print(f"生成泵协议时出错: {str(e)}")
action_sequence.append(create_action_log(f"泵协议生成失败: {str(e)}", ""))
raise ValueError(f"生成泵协议时出错: {str(e)}")
# 7. 混合搅拌
if stir and stirrer_id:
debug_print(f"🔍 步骤7: 混合搅拌...")
action_sequence.append(create_action_log(f"开始混合搅拌 {stir_time:.0f}s", "🌀"))
action_sequence.append({
@@ -337,10 +448,14 @@ def generate_adjust_ph_protocol(
"purpose": f"pH调节: 混合试剂目标pH={ph_value}"
}
})
debug_print(f"✅ 混合搅拌设置完成")
else:
debug_print(f"⏭️ 跳过混合搅拌")
action_sequence.append(create_action_log("跳过混合搅拌", "⏭️"))
# 8. 等待平衡
debug_print(f"🔍 步骤8: 反应平衡...")
action_sequence.append(create_action_log(f"等待pH平衡 {settling_time:.0f}s", "⚖️"))
action_sequence.append({
@@ -353,7 +468,17 @@ def generate_adjust_ph_protocol(
# 9. 完成总结
total_time = addition_time + stir_time + settling_time
debug_print(f"pH调节协议完成: {len(action_sequence)} 个动作, {total_time:.0f}s, {volume:.2f}mL {reagent}{vessel_id} pH {ph_value}")
debug_print("=" * 60)
debug_print(f"🎉 pH调节协议生成完成")
debug_print(f"📊 协议统计:")
debug_print(f" 📋 总动作数: {len(action_sequence)}")
debug_print(f" ⏱️ 预计总时间: {total_time:.0f}s ({total_time/60:.1f}分钟)")
debug_print(f" 🧪 试剂: {reagent}")
debug_print(f" 📏 体积: {volume:.2f}mL")
debug_print(f" 📊 目标pH: {ph_value}")
debug_print(f" 🥼 目标容器: {vessel_id}")
debug_print("=" * 60)
# 添加完成日志
summary_msg = f"pH调节协议完成: {vessel_id} → pH {ph_value} (使用 {volume:.2f}mL {reagent})"
@@ -385,18 +510,28 @@ def generate_adjust_ph_protocol_stepwise(
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id = vessel["id"]
debug_print(f"分步pH调节: vessel={vessel_id}, ph={ph_value}, reagent={reagent}, max_volume={max_volume}mL, steps={steps}")
debug_print("=" * 60)
debug_print(f"🔄 开始分步pH调节")
debug_print(f"📋 分步参数:")
debug_print(f" 🥼 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 📊 ph_value: {ph_value}")
debug_print(f" 🧪 reagent: {reagent}")
debug_print(f" 📏 max_volume: {max_volume}mL")
debug_print(f" 🔢 steps: {steps}")
debug_print("=" * 60)
action_sequence = []
# 每步添加的体积
step_volume = max_volume / steps
debug_print(f"📊 每步体积: {step_volume:.2f}mL")
action_sequence.append(create_action_log(f"开始分步pH调节 ({steps}步)", "🔄"))
action_sequence.append(create_action_log(f"每步添加: {step_volume:.2f}mL", "📏"))
for i in range(steps):
debug_print(f"🔄 执行第 {i+1}/{steps} 步,添加 {step_volume:.2f}mL")
action_sequence.append(create_action_log(f"{i+1}/{steps} 步开始", "🚀"))
# 生成单步协议
@@ -413,10 +548,12 @@ def generate_adjust_ph_protocol_stepwise(
)
action_sequence.extend(step_actions)
debug_print(f"✅ 第 {i+1}/{steps} 步完成,添加了 {len(step_actions)} 个动作")
action_sequence.append(create_action_log(f"{i+1}/{steps} 步完成", ""))
# 步骤间等待
if i < steps - 1:
debug_print(f"⏳ 步骤间等待30s")
action_sequence.append(create_action_log("步骤间等待...", ""))
action_sequence.append({
"action_name": "wait",
@@ -426,7 +563,7 @@ def generate_adjust_ph_protocol_stepwise(
}
})
debug_print(f"分步pH调节完成: {len(action_sequence)} 个动作")
debug_print(f"🎉 分步pH调节完成,共 {len(action_sequence)} 个动作")
action_sequence.append(create_action_log("分步pH调节全部完成", "🎉"))
return action_sequence
@@ -440,7 +577,7 @@ def generate_acidify_protocol(
) -> List[Dict[str, Any]]:
"""酸化协议"""
vessel_id = vessel["id"]
debug_print(f"酸化协议: {vessel_id} → pH {target_ph} ({acid})")
debug_print(f"🍋 生成酸化协议: {vessel_id} → pH {target_ph} (使用 {acid})")
return generate_adjust_ph_protocol(
G, vessel, target_ph, acid
)
@@ -453,7 +590,7 @@ def generate_basify_protocol(
) -> List[Dict[str, Any]]:
"""碱化协议"""
vessel_id = vessel["id"]
debug_print(f"碱化协议: {vessel_id} → pH {target_ph} ({base})")
debug_print(f"🧂 生成碱化协议: {vessel_id} → pH {target_ph} (使用 {base})")
return generate_adjust_ph_protocol(
G, vessel, target_ph, base
)
@@ -465,7 +602,7 @@ def generate_neutralize_protocol(
) -> List[Dict[str, Any]]:
"""中和协议pH=7"""
vessel_id = vessel["id"]
debug_print(f"中和协议: {vessel_id} → pH 7.0 ({reagent})")
debug_print(f"⚖️ 生成中和协议: {vessel_id} → pH 7.0 (使用 {reagent})")
return generate_adjust_ph_protocol(
G, vessel, 7.0, reagent
)
@@ -473,7 +610,10 @@ def generate_neutralize_protocol(
# 测试函数
def test_adjust_ph_protocol():
"""测试pH调节协议"""
debug_print("=== ADJUST PH PROTOCOL 增强版测试 ===")
# 测试体积计算
debug_print("🧮 测试体积计算...")
test_cases = [
(2.0, "hydrochloric acid", 100.0),
(4.0, "hydrochloric acid", 100.0),
@@ -481,12 +621,12 @@ def test_adjust_ph_protocol():
(10.0, "sodium hydroxide", 100.0),
(7.0, "unknown reagent", 100.0)
]
for ph, reagent, volume in test_cases:
result = calculate_reagent_volume(ph, reagent, volume)
debug_print(f"{reagent} → pH {ph}: {result:.2f}mL")
debug_print("测试完成")
debug_print(f"📊 {reagent} → pH {ph}: {result:.2f}mL")
debug_print("测试完成")
if __name__ == "__main__":
test_adjust_ph_protocol()

View File

@@ -1,12 +1,4 @@
"""
AGV 单物料转运编译器
从 physical_setup_graph 中查询 AGV 配置device_roles, route_table
不再硬编码 device_id 和路由表。
"""
import networkx as nx
from unilabos.compile._agv_utils import find_agv_config
def generate_agv_transfer_protocol(
@@ -25,32 +17,37 @@ def generate_agv_transfer_protocol(
from_repo_id = from_repo_["id"]
to_repo_id = to_repo_["id"]
# 从 G 中查询 AGV 配置
agv_cfg = find_agv_config(G)
device_roles = agv_cfg["device_roles"]
route_table = agv_cfg["route_table"]
wf_list = {
("AiChemEcoHiWo", "zhixing_agv"): {"nav_command" : '{"target" : "LM14"}',
"arm_command": '{"task_name" : "camera/250111_biaozhi.urp"}'},
("AiChemEcoHiWo", "AGV"): {"nav_command" : '{"target" : "LM14"}',
"arm_command": '{"task_name" : "camera/250111_biaozhi.urp"}'},
route_key = f"{from_repo_id}->{to_repo_id}"
if route_key not in route_table:
raise KeyError(f"AGV 路由表中未找到路线: {route_key},可用路线: {list(route_table.keys())}")
("zhixing_agv", "Revvity"): {"nav_command" : '{"target" : "LM13"}',
"arm_command": '{"task_name" : "camera/250111_put_board.urp"}'},
route = route_table[route_key]
nav_device = device_roles.get("navigator", device_roles.get("nav"))
arm_device = device_roles.get("arm")
("AGV", "Revvity"): {"nav_command" : '{"target" : "LM13"}',
"arm_command": '{"task_name" : "camera/250111_put_board.urp"}'},
("Revvity", "HPLC"): {"nav_command": '{"target" : "LM13"}',
"arm_command": '{"task_name" : "camera/250111_hplc.urp"}'},
("HPLC", "Revvity"): {"nav_command": '{"target" : "LM13"}',
"arm_command": '{"task_name" : "camera/250111_lfp.urp"}'},
}
return [
{
"device_id": nav_device,
"device_id": "zhixing_agv",
"action_name": "send_nav_task",
"action_kwargs": {
"command": route["nav_command"]
"command": wf_list[(from_repo_id, to_repo_id)]["nav_command"]
}
},
{
"device_id": arm_device,
"device_id": "zhixing_ur_arm",
"action_name": "move_pos_task",
"action_kwargs": {
"command": route.get("arm_command", route.get("arm_place", ""))
"command": wf_list[(from_repo_id, to_repo_id)]["arm_command"]
}
}
]

View File

@@ -1,228 +0,0 @@
"""
批量物料转运编译器
将 BatchTransferProtocol 编译为多批次的 nav → pick × N → nav → place × N 动作序列。
自动按 AGV 容量分批,全程维护三方 children dict 的物料系统一致性。
"""
import copy
from typing import Any, Dict, List
import networkx as nx
from unilabos.compile._agv_utils import find_agv_config, split_batches
def generate_batch_transfer_protocol(
G: nx.Graph,
from_repo: dict,
to_repo: dict,
transfer_resources: list,
from_positions: list,
to_positions: list,
) -> List[Dict[str, Any]]:
"""编译批量转运协议为可执行的 action steps
Args:
G: 设备图 (physical_setup_graph)
from_repo: 来源工站资源 dict{station_id: {..., children: {...}}}
to_repo: 目标工站资源 dict含堆栈和位置信息
transfer_resources: 被转运的物料列表Resource dict
from_positions: 来源 slot 位置列表(与 transfer_resources 平行)
to_positions: 目标 slot 位置列表(与 transfer_resources 平行)
Returns:
action steps 列表ROS2WorkstationNode 按序执行
"""
if not transfer_resources:
return []
n = len(transfer_resources)
if len(from_positions) != n or len(to_positions) != n:
raise ValueError(
f"transfer_resources({n}), from_positions({len(from_positions)}), "
f"to_positions({len(to_positions)}) 长度不一致"
)
# 组合为内部 transfer_items 便于分批处理
transfer_items = []
for i in range(n):
res = transfer_resources[i] if isinstance(transfer_resources[i], dict) else {}
transfer_items.append({
"resource_id": res.get("id", res.get("name", "")),
"resource_uuid": res.get("sample_id", ""),
"from_position": from_positions[i],
"to_position": to_positions[i],
"resource": res,
})
# 查询 AGV 配置
agv_cfg = find_agv_config(G)
agv_id = agv_cfg["agv_id"]
device_roles = agv_cfg["device_roles"]
route_table = agv_cfg["route_table"]
capacity = agv_cfg["capacity"]
if capacity <= 0:
raise ValueError(f"AGV {agv_id} 容量为 0请检查 Warehouse 子节点配置")
nav_device = device_roles.get("navigator", device_roles.get("nav"))
arm_device = device_roles.get("arm")
if not nav_device or not arm_device:
raise ValueError(f"AGV {agv_id} device_roles 缺少 navigator 或 arm: {device_roles}")
from_repo_ = list(from_repo.values())[0]
to_repo_ = list(to_repo.values())[0]
from_station_id = from_repo_["id"]
to_station_id = to_repo_["id"]
# 查找路由
route_to_source = _find_route(route_table, agv_id, from_station_id)
route_to_target = _find_route(route_table, from_station_id, to_station_id)
# 构建 AGV carrier 的 children dict用于 compile 阶段状态追踪)
agv_carrier_children: Dict[str, Any] = {}
# 计算 slot 名称A01, A02, B01, ...
agv_slot_names = _get_agv_slot_names(G, agv_cfg)
# 分批
batches = split_batches(transfer_items, capacity)
steps: List[Dict[str, Any]] = []
for batch_idx, batch in enumerate(batches):
is_last_batch = (batch_idx == len(batches) - 1)
# 阶段 1: AGV 导航到来源工站
steps.append({
"device_id": nav_device,
"action_name": "send_nav_task",
"action_kwargs": {
"command": route_to_source.get("nav_command", "")
},
"_comment": f"批次{batch_idx + 1}/{len(batches)}: AGV 导航至来源 {from_station_id}"
})
# 阶段 2: 逐个 pick
for item_idx, item in enumerate(batch):
from_pos = item["from_position"]
slot = agv_slot_names[item_idx] if item_idx < len(agv_slot_names) else f"S{item_idx + 1}"
# compile 阶段更新 children dict
if from_pos in from_repo_.get("children", {}):
resource_data = from_repo_["children"].pop(from_pos)
resource_data["parent"] = agv_id
agv_carrier_children[slot] = resource_data
steps.append({
"device_id": arm_device,
"action_name": "move_pos_task",
"action_kwargs": {
"command": route_to_source.get("arm_pick", route_to_source.get("arm_command", ""))
},
"_transfer_meta": {
"phase": "pick",
"resource_uuid": item.get("resource_uuid", ""),
"resource_id": item.get("resource_id", ""),
"from_parent": from_station_id,
"from_position": from_pos,
"agv_slot": slot,
},
"_comment": f"Pick {item.get('resource_id', from_pos)} → AGV.{slot}"
})
# 阶段 3: AGV 导航到目标工站
steps.append({
"device_id": nav_device,
"action_name": "send_nav_task",
"action_kwargs": {
"command": route_to_target.get("nav_command", "")
},
"_comment": f"批次{batch_idx + 1}: AGV 导航至目标 {to_station_id}"
})
# 阶段 4: 逐个 place
for item_idx, item in enumerate(batch):
to_pos = item["to_position"]
slot = agv_slot_names[item_idx] if item_idx < len(agv_slot_names) else f"S{item_idx + 1}"
# compile 阶段更新 children dict
if slot in agv_carrier_children:
resource_data = agv_carrier_children.pop(slot)
resource_data["parent"] = to_repo_["id"]
to_repo_["children"][to_pos] = resource_data
steps.append({
"device_id": arm_device,
"action_name": "move_pos_task",
"action_kwargs": {
"command": route_to_target.get("arm_place", route_to_target.get("arm_command", ""))
},
"_transfer_meta": {
"phase": "place",
"resource_uuid": item.get("resource_uuid", ""),
"resource_id": item.get("resource_id", ""),
"to_parent": to_station_id,
"to_position": to_pos,
"agv_slot": slot,
},
"_comment": f"Place AGV.{slot}{to_station_id}.{to_pos}"
})
# 如果还有下一批AGV 需要返回来源取料
if not is_last_batch:
steps.append({
"device_id": nav_device,
"action_name": "send_nav_task",
"action_kwargs": {
"command": route_to_source.get("nav_command", "")
},
"_comment": f"AGV 返回来源 {from_station_id} 取下一批"
})
return steps
def _find_route(route_table: Dict[str, Any], from_id: str, to_id: str) -> Dict[str, str]:
"""在路由表中查找路线,支持 A->B 和 (A, B) 两种 key 格式"""
# 优先 "A->B" 格式
key = f"{from_id}->{to_id}"
if key in route_table:
return route_table[key]
# 兼容 tuple keyJSON 中以逗号分隔字符串表示)
tuple_key = f"({from_id}, {to_id})"
if tuple_key in route_table:
return route_table[tuple_key]
raise KeyError(f"路由表中未找到: {key},可用路线: {list(route_table.keys())}")
def _get_agv_slot_names(G: nx.Graph, agv_cfg: dict) -> List[str]:
"""从设备图中获取 AGV Warehouse 的 slot 名称列表"""
agv_id = agv_cfg["agv_id"]
neighbors = G.successors(agv_id) if G.is_directed() else G.neighbors(agv_id)
for neighbor in neighbors:
ndata = G.nodes[neighbor]
node_type = ndata.get("type", "")
res_content = ndata.get("res_content")
if hasattr(res_content, "type"):
node_type = res_content.type or node_type
elif isinstance(res_content, dict):
node_type = res_content.get("type", node_type)
if node_type == "warehouse":
config = ndata.get("config", {})
if hasattr(res_content, "config") and isinstance(res_content.config, dict):
config = res_content.config
elif isinstance(res_content, dict):
config = res_content.get("config", config)
num_x = config.get("num_items_x", 1)
num_y = config.get("num_items_y", 1)
num_z = config.get("num_items_z", 1)
# 与 warehouse_factory 一致的命名
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
len_x = num_x if num_z == 1 else (num_y if num_x == 1 else num_x)
len_y = num_y if num_z == 1 else (num_z if num_x == 1 else num_z)
return [f"{letters[j]}{i + 1:02d}" for i in range(len_x) for j in range(len_y)]
# 兜底生成通用名称
capacity = agv_cfg.get("capacity", 4)
return [f"S{i + 1}" for i in range(capacity)]

View File

@@ -1,9 +1,7 @@
from typing import List, Dict, Any
import networkx as nx
from .utils.vessel_parser import get_vessel, find_solvent_vessel, find_connected_heatchill
from .utils.logger_util import debug_print
from .utils.vessel_parser import get_vessel, find_solvent_vessel
from .pump_protocol import generate_pump_protocol
from .utils.resource_helper import get_resource_liquid_volume
def find_solvent_vessel_by_any_match(G: nx.DiGraph, solvent: str) -> str:
@@ -19,23 +17,43 @@ def find_waste_vessel(G: nx.DiGraph) -> str:
"""
possible_waste_names = [
"waste_workup",
"flask_waste",
"flask_waste",
"bottle_waste",
"waste",
"waste_vessel",
"waste_container"
]
for waste_name in possible_waste_names:
if waste_name in G.nodes():
return waste_name
raise ValueError(f"未找到废液容器。尝试了以下名称: {possible_waste_names}")
def find_connected_heatchill(G: nx.DiGraph, vessel: str) -> str:
"""
查找与指定容器相连的加热冷却设备
"""
# 查找所有加热冷却设备节点
heatchill_nodes = [node for node in G.nodes()
if (G.nodes[node].get('class') or '') == 'virtual_heatchill']
# 检查哪个加热设备与目标容器相连(机械连接)
for heatchill in heatchill_nodes:
if G.has_edge(heatchill, vessel) or G.has_edge(vessel, heatchill):
return heatchill
# 如果没有直接连接,返回第一个可用的加热设备
if heatchill_nodes:
return heatchill_nodes[0]
return None # 没有加热设备也可以工作,只是不能加热
def generate_clean_vessel_protocol(
G: nx.DiGraph,
vessel: dict,
vessel: dict, # 🔧 修改:从字符串改为字典类型
solvent: str,
volume: float,
temp: float,
@@ -43,7 +61,7 @@ def generate_clean_vessel_protocol(
) -> List[Dict[str, Any]]:
"""
生成容器清洗操作的协议序列,复用 pump_protocol 的成熟算法
清洗流程:
1. 查找溶剂容器和废液容器
2. 如果需要加热,启动加热设备
@@ -52,50 +70,63 @@ def generate_clean_vessel_protocol(
b. (可选) 等待清洗作用时间
c. 使用 pump_protocol 将清洗液从目标容器转移到废液容器
4. 如果加热了,停止加热
Args:
G: 有向图,节点为设备和容器,边为流体管道
vessel: 要清洗的容器字典包含id字段
solvent: 用于清洗的溶剂名称
solvent: 用于清洗的溶剂名称
volume: 每次清洗使用的溶剂体积
temp: 清洗时的温度
repeats: 清洗操作的重复次数,默认为 1
Returns:
List[Dict[str, Any]]: 容器清洗操作的动作序列
Raises:
ValueError: 当找不到必要的容器或设备时抛出异常
Examples:
clean_protocol = generate_clean_vessel_protocol(G, {"id": "main_reactor"}, "water", 100.0, 60.0, 2)
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
action_sequence = []
debug_print(f"开始生成容器清洗协议: vessel={vessel_id}, solvent={solvent}, volume={volume}mL, temp={temp}°C, repeats={repeats}")
print(f"CLEAN_VESSEL: 开始生成容器清洗协议")
print(f" - 目标容器: {vessel} (ID: {vessel_id})")
print(f" - 清洗溶剂: {solvent}")
print(f" - 清洗体积: {volume} mL")
print(f" - 清洗温度: {temp}°C")
print(f" - 重复次数: {repeats}")
# 验证目标容器存在
if vessel_id not in G.nodes():
raise ValueError(f"目标容器 '{vessel_id}' 不存在于系统中")
# 查找溶剂容器
try:
solvent_vessel = find_solvent_vessel(G, solvent)
debug_print(f"找到溶剂容器: {solvent_vessel}")
print(f"CLEAN_VESSEL: 找到溶剂容器: {solvent_vessel}")
except ValueError as e:
raise ValueError(f"无法找到溶剂容器: {str(e)}")
# 查找废液容器
try:
waste_vessel = find_waste_vessel(G)
debug_print(f"找到废液容器: {waste_vessel}")
print(f"CLEAN_VESSEL: 找到废液容器: {waste_vessel}")
except ValueError as e:
raise ValueError(f"无法找到废液容器: {str(e)}")
# 查找加热设备(可选)
heatchill_id = find_connected_heatchill(G, vessel_id)
heatchill_id = find_connected_heatchill(G, vessel_id) # 🔧 使用 vessel_id
if heatchill_id:
debug_print(f"找到加热设备: {heatchill_id}")
print(f"CLEAN_VESSEL: 找到加热设备: {heatchill_id}")
else:
debug_print(f"未找到加热设备,将在室温下清洗")
# 记录清洗前的容器状态
print(f"CLEAN_VESSEL: 未找到加热设备,将在室温下清洗")
# 🔧 新增:记录清洗前的容器状态
print(f"CLEAN_VESSEL: 记录清洗前容器状态...")
original_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -103,69 +134,79 @@ def generate_clean_vessel_protocol(
original_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
original_liquid_volume = current_volume
print(f"CLEAN_VESSEL: 清洗前液体体积: {original_liquid_volume:.2f}mL")
# 第一步:如果需要加热且有加热设备,启动加热
if temp > 25.0 and heatchill_id:
debug_print(f"启动加热至 {temp}°C")
print(f"CLEAN_VESSEL: 启动加热至 {temp}°C")
heatchill_start_action = {
"device_id": heatchill_id,
"action_name": "heat_chill_start",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
"temp": temp,
"purpose": f"cleaning with {solvent}"
}
}
action_sequence.append(heatchill_start_action)
# 等待温度稳定
wait_action = {
"action_name": "wait",
"action_kwargs": {"time": 30}
"action_name": "wait",
"action_kwargs": {"time": 30} # 等待30秒让温度稳定
}
action_sequence.append(wait_action)
# 第二步:重复清洗操作
for repeat in range(repeats):
debug_print(f"执行第 {repeat + 1}/{repeats} 次清洗")
print(f"CLEAN_VESSEL: 执行第 {repeat + 1} 次清洗")
# 2a. 使用 pump_protocol 将溶剂转移到目标容器
print(f"CLEAN_VESSEL: 将 {volume} mL {solvent} 转移到 {vessel_id}")
try:
# 调用成熟的 pump_protocol 算法
add_solvent_actions = generate_pump_protocol(
G=G,
from_vessel=solvent_vessel,
to_vessel=vessel_id,
to_vessel=vessel_id, # 🔧 使用 vessel_id
volume=volume,
flowrate=2.5,
flowrate=2.5, # 适中的流速,避免飞溅
transfer_flowrate=2.5
)
action_sequence.extend(add_solvent_actions)
# 更新容器体积(添加清洗溶剂)
# 🔧 新增:更新容器体积(添加清洗溶剂)
print(f"CLEAN_VESSEL: 更新容器体积 - 添加清洗溶剂 {volume:.2f}mL")
if "data" not in vessel:
vessel["data"] = {}
if "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
if len(current_volume) > 0:
vessel["data"]["liquid_volume"][0] += volume
print(f"CLEAN_VESSEL: 添加溶剂后体积: {vessel['data']['liquid_volume'][0]:.2f}mL (+{volume:.2f}mL)")
else:
vessel["data"]["liquid_volume"] = [volume]
print(f"CLEAN_VESSEL: 初始化清洗体积: {volume:.2f}mL")
elif isinstance(current_volume, (int, float)):
vessel["data"]["liquid_volume"] += volume
print(f"CLEAN_VESSEL: 添加溶剂后体积: {vessel['data']['liquid_volume']:.2f}mL (+{volume:.2f}mL)")
else:
vessel["data"]["liquid_volume"] = volume
print(f"CLEAN_VESSEL: 重置体积为: {volume:.2f}mL")
else:
vessel["data"]["liquid_volume"] = volume
# 同时更新图中的容器数据
print(f"CLEAN_VESSEL: 创建新体积记录: {volume:.2f}mL")
# 🔧 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] += volume
@@ -173,48 +214,58 @@ def generate_clean_vessel_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = current_node_volume + volume
print(f"CLEAN_VESSEL: 图节点体积数据已更新")
except Exception as e:
raise ValueError(f"无法将溶剂转移到容器: {str(e)}")
# 2b. 等待清洗作用时间
cleaning_wait_time = 60 if temp > 50.0 else 30
# 2b. 等待清洗作用时间(让溶剂充分清洗容器)
cleaning_wait_time = 60 if temp > 50.0 else 30 # 高温下等待更久
print(f"CLEAN_VESSEL: 等待清洗作用 {cleaning_wait_time}")
wait_action = {
"action_name": "wait",
"action_name": "wait",
"action_kwargs": {"time": cleaning_wait_time}
}
action_sequence.append(wait_action)
# 2c. 使用 pump_protocol 将清洗液转移到废液容器
print(f"CLEAN_VESSEL: 将清洗液从 {vessel_id} 转移到废液容器")
try:
# 调用成熟的 pump_protocol 算法
remove_waste_actions = generate_pump_protocol(
G=G,
from_vessel=vessel_id,
from_vessel=vessel_id, # 🔧 使用 vessel_id
to_vessel=waste_vessel,
volume=volume,
flowrate=2.5,
flowrate=2.5, # 适中的流速
transfer_flowrate=2.5
)
action_sequence.extend(remove_waste_actions)
# 更新容器体积(移除清洗液)
# 🔧 新增:更新容器体积(移除清洗液)
print(f"CLEAN_VESSEL: 更新容器体积 - 移除清洗液 {volume:.2f}mL")
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
if len(current_volume) > 0:
vessel["data"]["liquid_volume"][0] = max(0.0, vessel["data"]["liquid_volume"][0] - volume)
print(f"CLEAN_VESSEL: 移除清洗液后体积: {vessel['data']['liquid_volume'][0]:.2f}mL (-{volume:.2f}mL)")
else:
vessel["data"]["liquid_volume"] = [0.0]
print(f"CLEAN_VESSEL: 重置体积为0mL")
elif isinstance(current_volume, (int, float)):
vessel["data"]["liquid_volume"] = max(0.0, current_volume - volume)
print(f"CLEAN_VESSEL: 移除清洗液后体积: {vessel['data']['liquid_volume']:.2f}mL (-{volume:.2f}mL)")
else:
vessel["data"]["liquid_volume"] = 0.0
# 同时更新图中的容器数据
print(f"CLEAN_VESSEL: 重置体积为0mL")
# 🔧 同时更新图中的容器数据
if vessel_id in G.nodes():
vessel_node_data = G.nodes[vessel_id].get('data', {})
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = max(0.0, current_node_volume[0] - volume)
@@ -222,30 +273,34 @@ def generate_clean_vessel_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [0.0]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = max(0.0, current_node_volume - volume)
print(f"CLEAN_VESSEL: 图节点体积数据已更新")
except Exception as e:
raise ValueError(f"无法将清洗液转移到废液容器: {str(e)}")
# 2d. 清洗循环间的短暂等待
if repeat < repeats - 1:
if repeat < repeats - 1: # 不是最后一次清洗
print(f"CLEAN_VESSEL: 清洗循环间等待")
wait_action = {
"action_name": "wait",
"action_name": "wait",
"action_kwargs": {"time": 10}
}
action_sequence.append(wait_action)
# 第三步:如果加热了,停止加热
if temp > 25.0 and heatchill_id:
print(f"CLEAN_VESSEL: 停止加热")
heatchill_stop_action = {
"device_id": heatchill_id,
"action_name": "heat_chill_stop",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
}
}
action_sequence.append(heatchill_stop_action)
# 清洗完成后的状态
# 🔧 新增:清洗完成后的状态报告
final_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -253,17 +308,20 @@ def generate_clean_vessel_protocol(
final_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
final_liquid_volume = current_volume
debug_print(f"清洗完成: {len(action_sequence)} 个动作, 体积 {original_liquid_volume:.2f} -> {final_liquid_volume:.2f}mL")
print(f"CLEAN_VESSEL: 清洗完成")
print(f" - 清洗前体积: {original_liquid_volume:.2f}mL")
print(f" - 清洗后体积: {final_liquid_volume:.2f}mL")
print(f" - 生成了 {len(action_sequence)} 个动作")
return action_sequence
# 便捷函数
# 便捷函数:常用清洗方案
def generate_quick_clean_protocol(
G: nx.DiGraph,
vessel: dict,
solvent: str = "water",
G: nx.DiGraph,
vessel: dict, # 🔧 修改:从字符串改为字典类型
solvent: str = "water",
volume: float = 100.0
) -> List[Dict[str, Any]]:
"""快速清洗:室温,单次清洗"""
@@ -271,9 +329,9 @@ def generate_quick_clean_protocol(
def generate_thorough_clean_protocol(
G: nx.DiGraph,
vessel: dict,
solvent: str = "water",
G: nx.DiGraph,
vessel: dict, # 🔧 修改:从字符串改为字典类型
solvent: str = "water",
volume: float = 150.0,
temp: float = 60.0
) -> List[Dict[str, Any]]:
@@ -282,13 +340,13 @@ def generate_thorough_clean_protocol(
def generate_organic_clean_protocol(
G: nx.DiGraph,
vessel: dict,
G: nx.DiGraph,
vessel: dict, # 🔧 修改:从字符串改为字典类型
volume: float = 100.0
) -> List[Dict[str, Any]]:
"""有机清洗:先用有机溶剂,再用水清洗"""
action_sequence = []
# 第一步:有机溶剂清洗
try:
organic_actions = generate_clean_vessel_protocol(
@@ -296,71 +354,96 @@ def generate_organic_clean_protocol(
)
action_sequence.extend(organic_actions)
except ValueError:
# 如果没有丙酮,尝试乙醇
try:
organic_actions = generate_clean_vessel_protocol(
G, vessel, "ethanol", volume, 25.0, 2
)
action_sequence.extend(organic_actions)
except ValueError:
debug_print("未找到有机溶剂,跳过有机清洗步骤")
print("警告:未找到有机溶剂,跳过有机清洗步骤")
# 第二步:水清洗
water_actions = generate_clean_vessel_protocol(
G, vessel, "water", volume, 25.0, 2
)
action_sequence.extend(water_actions)
return action_sequence
def get_vessel_liquid_volume(G: nx.DiGraph, vessel: str) -> float:
"""获取容器中的液体体积(修复版)"""
if vessel not in G.nodes():
return 0.0
vessel_data = G.nodes[vessel].get('data', {})
liquids = vessel_data.get('liquid', [])
total_volume = 0.0
for liquid in liquids:
if isinstance(liquid, dict):
# 支持两种格式:新格式 (name, volume) 和旧格式 (liquid_type, liquid_volume)
volume = liquid.get('volume') or liquid.get('liquid_volume', 0.0)
total_volume += volume
return total_volume
def get_vessel_liquid_types(G: nx.DiGraph, vessel: str) -> List[str]:
"""获取容器中所有液体的类型"""
if vessel not in G.nodes():
return []
vessel_data = G.nodes[vessel].get('data', {})
liquids = vessel_data.get('liquid', [])
liquid_types = []
for liquid in liquids:
if isinstance(liquid, dict):
# 支持两种格式的液体类型字段
liquid_type = liquid.get('liquid_type') or liquid.get('name', '')
if liquid_type:
liquid_types.append(liquid_type)
return liquid_types
def find_vessel_by_content(G: nx.DiGraph, content: str) -> List[str]:
"""
根据内容物查找所有匹配的容器
返回匹配容器的ID列表
"""
matching_vessels = []
for node_id in G.nodes():
if G.nodes[node_id].get('type') == 'container':
# 检查容器名称匹配
node_name = G.nodes[node_id].get('name', '').lower()
if content.lower() in node_id.lower() or content.lower() in node_name:
matching_vessels.append(node_id)
continue
# 检查液体类型匹配
vessel_data = G.nodes[node_id].get('data', {})
liquids = vessel_data.get('liquid', [])
config_data = G.nodes[node_id].get('config', {})
# 检查 reagent_name 和 config.reagent
reagent_name = vessel_data.get('reagent_name', '').lower()
config_reagent = config_data.get('reagent', '').lower()
if (content.lower() == reagent_name or
if (content.lower() == reagent_name or
content.lower() == config_reagent):
matching_vessels.append(node_id)
continue
# 检查液体列表
for liquid in liquids:
if isinstance(liquid, dict):
liquid_type = liquid.get('liquid_type') or liquid.get('name', '')
if liquid_type.lower() == content.lower():
matching_vessels.append(node_id)
break
return matching_vessels
return matching_vessels

View File

@@ -1,19 +1,402 @@
from functools import partial
import networkx as nx
import re
import logging
from typing import List, Dict, Any, Union
from .utils.logger_util import debug_print, action_log
from .utils.unit_parser import parse_volume_input, parse_mass_input, parse_time_input, parse_temperature_input
from .utils.vessel_parser import get_vessel, find_solvent_vessel, find_connected_heatchill, find_connected_stirrer, find_solid_dispenser
from .utils.vessel_parser import get_vessel
from .utils.logger_util import action_log
from .pump_protocol import generate_pump_protocol_with_rinsing
logger = logging.getLogger(__name__)
# 创建进度日志动作
def debug_print(message):
"""调试输出"""
logger.info(f"[DISSOLVE] {message}")
# 🆕 创建进度日志动作
create_action_log = partial(action_log, prefix="[DISSOLVE]")
def parse_volume_input(volume_input: Union[str, float]) -> float:
"""
解析体积输入,支持带单位的字符串
Args:
volume_input: 体积输入(如 "10 mL", "?", 10.0
Returns:
float: 体积(毫升)
"""
if isinstance(volume_input, (int, float)):
debug_print(f"📏 体积输入为数值: {volume_input}")
return float(volume_input)
if not volume_input or not str(volume_input).strip():
debug_print(f"⚠️ 体积输入为空返回0.0mL")
return 0.0
volume_str = str(volume_input).lower().strip()
debug_print(f"🔍 解析体积输入: '{volume_str}'")
# 处理未知体积
if volume_str in ['?', 'unknown', 'tbd', 'to be determined']:
default_volume = 50.0 # 默认50mL
debug_print(f"❓ 检测到未知体积,使用默认值: {default_volume}mL 🎯")
return default_volume
# 移除空格并提取数字和单位
volume_clean = re.sub(r'\s+', '', volume_str)
# 匹配数字和单位的正则表达式
match = re.match(r'([0-9]*\.?[0-9]+)\s*(ml|l|μl|ul|microliter|milliliter|liter)?', volume_clean)
if not match:
debug_print(f"❌ 无法解析体积: '{volume_str}'使用默认值50mL")
return 50.0
value = float(match.group(1))
unit = match.group(2) or 'ml' # 默认单位为毫升
# 转换为毫升
if unit in ['l', 'liter']:
volume = value * 1000.0 # L -> mL
debug_print(f"🔄 体积转换: {value}L → {volume}mL")
elif unit in ['μl', 'ul', 'microliter']:
volume = value / 1000.0 # μL -> mL
debug_print(f"🔄 体积转换: {value}μL → {volume}mL")
else: # ml, milliliter 或默认
volume = value # 已经是mL
debug_print(f"✅ 体积已为mL: {volume}mL")
return volume
def parse_mass_input(mass_input: Union[str, float]) -> float:
"""
解析质量输入,支持带单位的字符串
Args:
mass_input: 质量输入(如 "2.9 g", "?", 2.5
Returns:
float: 质量(克)
"""
if isinstance(mass_input, (int, float)):
debug_print(f"⚖️ 质量输入为数值: {mass_input}g")
return float(mass_input)
if not mass_input or not str(mass_input).strip():
debug_print(f"⚠️ 质量输入为空返回0.0g")
return 0.0
mass_str = str(mass_input).lower().strip()
debug_print(f"🔍 解析质量输入: '{mass_str}'")
# 处理未知质量
if mass_str in ['?', 'unknown', 'tbd', 'to be determined']:
default_mass = 1.0 # 默认1g
debug_print(f"❓ 检测到未知质量,使用默认值: {default_mass}g 🎯")
return default_mass
# 移除空格并提取数字和单位
mass_clean = re.sub(r'\s+', '', mass_str)
# 匹配数字和单位的正则表达式
match = re.match(r'([0-9]*\.?[0-9]+)\s*(g|mg|kg|gram|milligram|kilogram)?', mass_clean)
if not match:
debug_print(f"❌ 无法解析质量: '{mass_str}'返回0.0g")
return 0.0
value = float(match.group(1))
unit = match.group(2) or 'g' # 默认单位为克
# 转换为克
if unit in ['mg', 'milligram']:
mass = value / 1000.0 # mg -> g
debug_print(f"🔄 质量转换: {value}mg → {mass}g")
elif unit in ['kg', 'kilogram']:
mass = value * 1000.0 # kg -> g
debug_print(f"🔄 质量转换: {value}kg → {mass}g")
else: # g, gram 或默认
mass = value # 已经是g
debug_print(f"✅ 质量已为g: {mass}g")
return mass
def parse_time_input(time_input: Union[str, float]) -> float:
"""
解析时间输入,支持带单位的字符串
Args:
time_input: 时间输入(如 "30 min", "1 h", "?", 60.0
Returns:
float: 时间(秒)
"""
if isinstance(time_input, (int, float)):
debug_print(f"⏱️ 时间输入为数值: {time_input}")
return float(time_input)
if not time_input or not str(time_input).strip():
debug_print(f"⚠️ 时间输入为空返回0秒")
return 0.0
time_str = str(time_input).lower().strip()
debug_print(f"🔍 解析时间输入: '{time_str}'")
# 处理未知时间
if time_str in ['?', 'unknown', 'tbd']:
default_time = 600.0 # 默认10分钟
debug_print(f"❓ 检测到未知时间,使用默认值: {default_time}s (10分钟) ⏰")
return default_time
# 移除空格并提取数字和单位
time_clean = re.sub(r'\s+', '', time_str)
# 匹配数字和单位的正则表达式
match = re.match(r'([0-9]*\.?[0-9]+)\s*(s|sec|second|min|minute|h|hr|hour|d|day)?', time_clean)
if not match:
debug_print(f"❌ 无法解析时间: '{time_str}'返回0s")
return 0.0
value = float(match.group(1))
unit = match.group(2) or 's' # 默认单位为秒
# 转换为秒
if unit in ['min', 'minute']:
time_sec = value * 60.0 # min -> s
debug_print(f"🔄 时间转换: {value}分钟 → {time_sec}")
elif unit in ['h', 'hr', 'hour']:
time_sec = value * 3600.0 # h -> s
debug_print(f"🔄 时间转换: {value}小时 → {time_sec}")
elif unit in ['d', 'day']:
time_sec = value * 86400.0 # d -> s
debug_print(f"🔄 时间转换: {value}天 → {time_sec}")
else: # s, sec, second 或默认
time_sec = value # 已经是s
debug_print(f"✅ 时间已为秒: {time_sec}")
return time_sec
def parse_temperature_input(temp_input: Union[str, float]) -> float:
"""
解析温度输入,支持带单位的字符串
Args:
temp_input: 温度输入(如 "60 °C", "room temperature", "?", 25.0
Returns:
float: 温度(摄氏度)
"""
if isinstance(temp_input, (int, float)):
debug_print(f"🌡️ 温度输入为数值: {temp_input}°C")
return float(temp_input)
if not temp_input or not str(temp_input).strip():
debug_print(f"⚠️ 温度输入为空使用默认室温25°C")
return 25.0 # 默认室温
temp_str = str(temp_input).lower().strip()
debug_print(f"🔍 解析温度输入: '{temp_str}'")
# 处理特殊温度描述
temp_aliases = {
'room temperature': 25.0,
'rt': 25.0,
'ambient': 25.0,
'cold': 4.0,
'ice': 0.0,
'reflux': 80.0, # 默认回流温度
'?': 25.0,
'unknown': 25.0
}
if temp_str in temp_aliases:
result = temp_aliases[temp_str]
debug_print(f"🏷️ 温度别名解析: '{temp_str}'{result}°C")
return result
# 移除空格并提取数字和单位
temp_clean = re.sub(r'\s+', '', temp_str)
# 匹配数字和单位的正则表达式
match = re.match(r'([0-9]*\.?[0-9]+)\s*(°c|c|celsius|°f|f|fahrenheit|k|kelvin)?', temp_clean)
if not match:
debug_print(f"❌ 无法解析温度: '{temp_str}'使用默认值25°C")
return 25.0
value = float(match.group(1))
unit = match.group(2) or 'c' # 默认单位为摄氏度
# 转换为摄氏度
if unit in ['°f', 'f', 'fahrenheit']:
temp_c = (value - 32) * 5/9 # F -> C
debug_print(f"🔄 温度转换: {value}°F → {temp_c:.1f}°C")
elif unit in ['k', 'kelvin']:
temp_c = value - 273.15 # K -> C
debug_print(f"🔄 温度转换: {value}K → {temp_c:.1f}°C")
else: # °c, c, celsius 或默认
temp_c = value # 已经是C
debug_print(f"✅ 温度已为°C: {temp_c}°C")
return temp_c
def find_solvent_vessel(G: nx.DiGraph, solvent: str) -> str:
"""增强版溶剂容器查找,支持多种匹配模式"""
debug_print(f"🔍 开始查找溶剂 '{solvent}' 的容器...")
# 🔧 方法1直接搜索 data.reagent_name 和 config.reagent
debug_print(f"📋 方法1: 搜索reagent字段...")
for node in G.nodes():
node_data = G.nodes[node].get('data', {})
node_type = G.nodes[node].get('type', '')
config_data = G.nodes[node].get('config', {})
# 只搜索容器类型的节点
if node_type == 'container':
reagent_name = node_data.get('reagent_name', '').lower()
config_reagent = config_data.get('reagent', '').lower()
# 精确匹配
if reagent_name == solvent.lower() or config_reagent == solvent.lower():
debug_print(f"✅ 通过reagent字段精确匹配到容器: {node} 🎯")
return node
# 模糊匹配
if (solvent.lower() in reagent_name and reagent_name) or \
(solvent.lower() in config_reagent and config_reagent):
debug_print(f"✅ 通过reagent字段模糊匹配到容器: {node} 🔍")
return node
# 🔧 方法2常见的容器命名规则
debug_print(f"📋 方法2: 使用命名规则查找...")
solvent_clean = solvent.lower().replace(' ', '_').replace('-', '_')
possible_names = [
solvent_clean,
f"flask_{solvent_clean}",
f"bottle_{solvent_clean}",
f"vessel_{solvent_clean}",
f"{solvent_clean}_flask",
f"{solvent_clean}_bottle",
f"solvent_{solvent_clean}",
f"reagent_{solvent_clean}",
f"reagent_bottle_{solvent_clean}",
f"reagent_bottle_1", # 通用试剂瓶
f"reagent_bottle_2",
f"reagent_bottle_3"
]
debug_print(f"🔍 尝试的容器名称: {possible_names[:5]}... (共{len(possible_names)}个)")
for name in possible_names:
if name in G.nodes():
node_type = G.nodes[name].get('type', '')
if node_type == 'container':
debug_print(f"✅ 通过命名规则找到容器: {name} 📝")
return name
# 🔧 方法3节点名称模糊匹配
debug_print(f"📋 方法3: 节点名称模糊匹配...")
for node_id in G.nodes():
node_data = G.nodes[node_id]
if node_data.get('type') == 'container':
# 检查节点名称是否包含溶剂名称
if solvent_clean in node_id.lower():
debug_print(f"✅ 通过节点名称模糊匹配到容器: {node_id} 🔍")
return node_id
# 检查液体类型匹配
vessel_data = node_data.get('data', {})
liquids = vessel_data.get('liquid', [])
for liquid in liquids:
if isinstance(liquid, dict):
liquid_type = liquid.get('liquid_type') or liquid.get('name', '')
if liquid_type.lower() == solvent.lower():
debug_print(f"✅ 通过液体类型匹配到容器: {node_id} 💧")
return node_id
# 🔧 方法4使用第一个试剂瓶作为备选
debug_print(f"📋 方法4: 查找备选试剂瓶...")
for node_id in G.nodes():
node_data = G.nodes[node_id]
if (node_data.get('type') == 'container' and
('reagent' in node_id.lower() or 'bottle' in node_id.lower() or 'flask' in node_id.lower())):
debug_print(f"⚠️ 未找到专用容器,使用备选试剂瓶: {node_id} 🔄")
return node_id
debug_print(f"❌ 所有方法都失败了,无法找到容器!")
raise ValueError(f"找不到溶剂 '{solvent}' 对应的容器")
def find_connected_heatchill(G: nx.DiGraph, vessel: str) -> str:
"""查找连接到指定容器的加热搅拌器"""
debug_print(f"🔍 查找连接到容器 '{vessel}' 的加热搅拌器...")
heatchill_nodes = []
for node in G.nodes():
node_class = G.nodes[node].get('class', '').lower()
if 'heatchill' in node_class:
heatchill_nodes.append(node)
debug_print(f"📋 发现加热搅拌器: {node}")
debug_print(f"📊 共找到 {len(heatchill_nodes)} 个加热搅拌器")
# 查找连接到容器的加热器
for heatchill in heatchill_nodes:
if G.has_edge(heatchill, vessel) or G.has_edge(vessel, heatchill):
debug_print(f"✅ 找到连接的加热搅拌器: {heatchill} 🔗")
return heatchill
# 返回第一个加热器
if heatchill_nodes:
debug_print(f"⚠️ 未找到直接连接的加热搅拌器,使用第一个: {heatchill_nodes[0]} 🔄")
return heatchill_nodes[0]
debug_print(f"❌ 未找到任何加热搅拌器")
return ""
def find_connected_stirrer(G: nx.DiGraph, vessel: str) -> str:
"""查找连接到指定容器的搅拌器"""
debug_print(f"🔍 查找连接到容器 '{vessel}' 的搅拌器...")
stirrer_nodes = []
for node in G.nodes():
node_class = G.nodes[node].get('class', '').lower()
if 'stirrer' in node_class:
stirrer_nodes.append(node)
debug_print(f"📋 发现搅拌器: {node}")
debug_print(f"📊 共找到 {len(stirrer_nodes)} 个搅拌器")
# 查找连接到容器的搅拌器
for stirrer in stirrer_nodes:
if G.has_edge(stirrer, vessel) or G.has_edge(vessel, stirrer):
debug_print(f"✅ 找到连接的搅拌器: {stirrer} 🔗")
return stirrer
# 返回第一个搅拌器
if stirrer_nodes:
debug_print(f"⚠️ 未找到直接连接的搅拌器,使用第一个: {stirrer_nodes[0]} 🔄")
return stirrer_nodes[0]
debug_print(f"❌ 未找到任何搅拌器")
return ""
def find_solid_dispenser(G: nx.DiGraph) -> str:
"""查找固体加样器"""
debug_print(f"🔍 查找固体加样器...")
for node in G.nodes():
node_class = G.nodes[node].get('class', '').lower()
if 'solid_dispenser' in node_class or 'dispenser' in node_class:
debug_print(f"✅ 找到固体加样器: {node} 🥄")
return node
debug_print(f"❌ 未找到固体加样器")
return ""
def generate_dissolve_protocol(
G: nx.DiGraph,
vessel: dict, # 🔧 修改:从字符串改为字典类型
@@ -53,21 +436,43 @@ def generate_dissolve_protocol(
- mol: "0.12 mol", "16.2 mmol"
"""
# 从字典中提取容器ID
# 🔧 核心修改:从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
debug_print(f"溶解协议: vessel={vessel_id}, solvent='{solvent}', volume={volume}, "
f"mass={mass}, temp={temp}, time={time}")
debug_print("=" * 60)
debug_print("🧪 开始生成溶解协议")
debug_print(f"📋 原始参数:")
debug_print(f" 🥼 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 💧 solvent: '{solvent}'")
debug_print(f" 📏 volume: {volume} (类型: {type(volume)})")
debug_print(f" ⚖️ mass: {mass} (类型: {type(mass)})")
debug_print(f" 🌡️ temp: {temp} (类型: {type(temp)})")
debug_print(f" ⏱️ time: {time} (类型: {type(time)})")
debug_print(f" 🧪 reagent: '{reagent}'")
debug_print(f" 🧬 mol: '{mol}'")
debug_print(f" 🎯 event: '{event}'")
debug_print(f" 📦 kwargs: {kwargs}") # 显示额外参数
debug_print("=" * 60)
action_sequence = []
# === 参数验证 ===
debug_print("🔍 步骤1: 参数验证...")
action_sequence.append(create_action_log(f"开始溶解操作 - 容器: {vessel_id}", "🎬"))
if not vessel_id:
debug_print("❌ vessel 参数不能为空")
raise ValueError("vessel 参数不能为空")
if vessel_id not in G.nodes():
debug_print(f"❌ 容器 '{vessel_id}' 不存在于系统中")
raise ValueError(f"容器 '{vessel_id}' 不存在于系统中")
# 记录溶解前的容器状态
debug_print("✅ 基本参数验证通过")
action_sequence.append(create_action_log("参数验证通过", ""))
# 🔧 新增:记录溶解前的容器状态
debug_print("🔍 记录溶解前容器状态...")
original_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -75,16 +480,30 @@ def generate_dissolve_protocol(
original_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
original_liquid_volume = current_volume
# === 参数解析 ===
debug_print(f"📊 溶解前液体体积: {original_liquid_volume:.2f}mL")
# === 🔧 关键修复:参数解析 ===
debug_print("🔍 步骤2: 参数解析...")
action_sequence.append(create_action_log("正在解析溶解参数...", "🔍"))
# 解析各种参数为数值
final_volume = parse_volume_input(volume)
final_mass = parse_mass_input(mass)
final_temp = parse_temperature_input(temp)
final_time = parse_time_input(time)
debug_print(f"参数解析: vol={final_volume}mL, mass={final_mass}g, temp={final_temp}°C, time={final_time}s")
debug_print(f"📊 解析结果:")
debug_print(f" 📏 体积: {final_volume}mL")
debug_print(f" ⚖️ 质量: {final_mass}g")
debug_print(f" 🌡️ 温度: {final_temp}°C")
debug_print(f" ⏱️ 时间: {final_time}s")
debug_print(f" 🧪 试剂: '{reagent}'")
debug_print(f" 🧬 摩尔: '{mol}'")
debug_print(f" 🎯 事件: '{event}'")
# === 判断溶解类型 ===
debug_print("🔍 步骤3: 判断溶解类型...")
action_sequence.append(create_action_log("正在判断溶解类型...", "🔍"))
# 判断是固体溶解还是液体溶解
is_solid_dissolve = (final_mass > 0 or (mol and mol.strip() != "") or (reagent and reagent.strip() != ""))
@@ -96,31 +515,49 @@ def generate_dissolve_protocol(
final_volume = 50.0
if not solvent:
solvent = "water" # 默认溶剂
debug_print("未明确指定溶解参数默认为50mL水溶解")
debug_print("⚠️ 未明确指定溶解参数默认为50mL水溶解")
dissolve_type = "固体溶解" if is_solid_dissolve else "液体溶解"
debug_print(f"溶解类型: {dissolve_type}")
action_sequence.append(create_action_log(f"溶解类型: {dissolve_type}", "📋"))
dissolve_emoji = "🧂" if is_solid_dissolve else "💧"
debug_print(f"📋 溶解类型: {dissolve_type} {dissolve_emoji}")
action_sequence.append(create_action_log(f"确定溶解类型: {dissolve_type} {dissolve_emoji}", "📋"))
# === 查找设备 ===
debug_print("🔍 步骤4: 查找设备...")
action_sequence.append(create_action_log("正在查找相关设备...", "🔍"))
# 查找加热搅拌器
heatchill_id = find_connected_heatchill(G, vessel_id)
stirrer_id = find_connected_stirrer(G, vessel_id)
# 优先使用加热搅拌器,否则使用独立搅拌器
stir_device_id = heatchill_id or stirrer_id
debug_print(f"设备: heatchill='{heatchill_id}', stirrer='{stirrer_id}'")
if not stir_device_id:
debug_print(f"📊 设备映射:")
debug_print(f" 🔥 加热器: '{heatchill_id}'")
debug_print(f" 🌪️ 搅拌器: '{stirrer_id}'")
debug_print(f" 🎯 使用设备: '{stir_device_id}'")
if heatchill_id:
action_sequence.append(create_action_log(f"找到加热搅拌器: {heatchill_id}", "🔥"))
elif stirrer_id:
action_sequence.append(create_action_log(f"找到搅拌器: {stirrer_id}", "🌪️"))
else:
action_sequence.append(create_action_log("未找到搅拌设备,将跳过搅拌", "⚠️"))
# === 执行溶解流程 ===
debug_print("🔍 步骤5: 执行溶解流程...")
try:
# 启动加热搅拌(如果需要)
# 步骤5.1: 启动加热搅拌(如果需要)
if stir_device_id and (final_temp > 25.0 or final_time > 0 or stir_speed > 0):
debug_print(f"🔍 5.1: 启动加热搅拌,温度: {final_temp}°C")
action_sequence.append(create_action_log(f"准备加热搅拌 (目标温度: {final_temp}°C)", "🔥"))
if heatchill_id and (final_temp > 25.0 or final_time > 0):
# 使用加热搅拌器
action_sequence.append(create_action_log(f"启动加热搅拌器 {heatchill_id}", "🔥"))
heatchill_action = {
"device_id": heatchill_id,
@@ -136,6 +573,7 @@ def generate_dissolve_protocol(
# 等待温度稳定
if final_temp > 25.0:
wait_time = min(60, abs(final_temp - 25.0) * 1.5)
action_sequence.append(create_action_log(f"等待温度稳定 ({wait_time:.0f}秒)", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": wait_time}
@@ -143,6 +581,7 @@ def generate_dissolve_protocol(
elif stirrer_id:
# 使用独立搅拌器
action_sequence.append(create_action_log(f"启动搅拌器 {stirrer_id} (速度: {stir_speed}rpm)", "🌪️"))
stir_action = {
"device_id": stirrer_id,
@@ -154,8 +593,9 @@ def generate_dissolve_protocol(
}
}
action_sequence.append(stir_action)
# 等待搅拌稳定
action_sequence.append(create_action_log("等待搅拌稳定...", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 5}
@@ -163,8 +603,12 @@ def generate_dissolve_protocol(
if is_solid_dissolve:
# === 固体溶解路径 ===
debug_print(f"🔍 5.2: 使用固体溶解路径")
action_sequence.append(create_action_log("开始固体溶解流程", "🧂"))
solid_dispenser = find_solid_dispenser(G)
if solid_dispenser:
action_sequence.append(create_action_log(f"找到固体加样器: {solid_dispenser}", "🥄"))
# 固体加样
add_kwargs = {
@@ -176,27 +620,42 @@ def generate_dissolve_protocol(
if final_mass > 0:
add_kwargs["mass"] = str(final_mass)
action_sequence.append(create_action_log(f"准备添加固体: {final_mass}g", "⚖️"))
if mol and mol.strip():
add_kwargs["mol"] = mol
action_sequence.append(create_action_log(f"按摩尔数添加: {mol}", "🧬"))
action_sequence.append(create_action_log("开始固体加样操作", "🥄"))
action_sequence.append({
"device_id": solid_dispenser,
"action_name": "add_solid",
"action_kwargs": add_kwargs
})
# 固体溶解体积运算 - 固体本身不会显著增加体积
debug_print(f"✅ 固体加样完成")
action_sequence.append(create_action_log("固体加样完成", ""))
# 🔧 新增:固体溶解体积运算 - 固体本身不会显著增加体积,但可能有少量变化
debug_print(f"🔧 固体溶解 - 体积变化很小,主要是质量变化")
# 固体通常不会显著改变液体体积,这里只记录日志
action_sequence.append(create_action_log(f"固体已添加: {final_mass}g", "📊"))
else:
debug_print("未找到固体加样器,跳过固体添加")
debug_print("⚠️ 未找到固体加样器,跳过固体添加")
action_sequence.append(create_action_log("未找到固体加样器,无法添加固体", ""))
elif is_liquid_dissolve:
# === 液体溶解路径 ===
debug_print(f"🔍 5.3: 使用液体溶解路径")
action_sequence.append(create_action_log("开始液体溶解流程", "💧"))
# 查找溶剂容器
action_sequence.append(create_action_log("正在查找溶剂容器...", "🔍"))
try:
solvent_vessel = find_solvent_vessel(G, solvent)
action_sequence.append(create_action_log(f"找到溶剂容器: {solvent_vessel}", "🧪"))
except ValueError as e:
debug_print(f"溶剂容器查找失败: {str(e)},跳过溶剂添加")
debug_print(f"⚠️ {str(e)},跳过溶剂添加")
action_sequence.append(create_action_log(f"溶剂容器查找失败: {str(e)}", ""))
solvent_vessel = None
@@ -204,7 +663,10 @@ def generate_dissolve_protocol(
# 计算流速 - 溶解时通常用较慢的速度,避免飞溅
flowrate = 1.0 # 较慢的注入速度
transfer_flowrate = 0.5 # 较慢的转移速度
action_sequence.append(create_action_log(f"设置流速: {flowrate}mL/min (缓慢注入)", ""))
action_sequence.append(create_action_log(f"开始转移 {final_volume}mL {solvent}", "🚰"))
# 调用pump protocol
pump_actions = generate_pump_protocol_with_rinsing(
G=G,
@@ -226,9 +688,12 @@ def generate_dissolve_protocol(
**kwargs
)
action_sequence.extend(pump_actions)
# 液体溶解体积运算 - 添加溶剂后更新容器体积
debug_print(f"✅ 溶剂转移完成,添加了 {len(pump_actions)} 个动作")
action_sequence.append(create_action_log(f"溶剂转移完成 ({len(pump_actions)} 个操作)", ""))
# 🔧 新增:液体溶解体积运算 - 添加溶剂后更新容器体积
debug_print(f"🔧 更新容器液体体积 - 添加溶剂 {final_volume:.2f}mL")
# 确保vessel有data字段
if "data" not in vessel:
vessel["data"] = {}
@@ -238,14 +703,19 @@ def generate_dissolve_protocol(
if isinstance(current_volume, list):
if len(current_volume) > 0:
vessel["data"]["liquid_volume"][0] += final_volume
debug_print(f"📊 添加溶剂后体积: {vessel['data']['liquid_volume'][0]:.2f}mL (+{final_volume:.2f}mL)")
else:
vessel["data"]["liquid_volume"] = [final_volume]
debug_print(f"📊 初始化溶解体积: {final_volume:.2f}mL")
elif isinstance(current_volume, (int, float)):
vessel["data"]["liquid_volume"] += final_volume
debug_print(f"📊 添加溶剂后体积: {vessel['data']['liquid_volume']:.2f}mL (+{final_volume:.2f}mL)")
else:
vessel["data"]["liquid_volume"] = final_volume
debug_print(f"📊 重置体积为: {final_volume:.2f}mL")
else:
vessel["data"]["liquid_volume"] = final_volume
debug_print(f"📊 创建新体积记录: {final_volume:.2f}mL")
# 🔧 同时更新图中的容器数据
if vessel_id in G.nodes():
@@ -262,19 +732,27 @@ def generate_dissolve_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [final_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = current_node_volume + final_volume
debug_print(f"✅ 图节点体积数据已更新")
action_sequence.append(create_action_log(f"容器体积已更新 (+{final_volume:.2f}mL)", "📊"))
# 溶剂添加后等待
action_sequence.append(create_action_log("溶剂添加后短暂等待...", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 5}
})
# 等待溶解完成
# 步骤5.4: 等待溶解完成
if final_time > 0:
debug_print(f"🔍 5.4: 等待溶解完成 - {final_time}s")
wait_minutes = final_time / 60
action_sequence.append(create_action_log(f"开始溶解等待 ({wait_minutes:.1f}分钟)", ""))
if heatchill_id:
# 使用定时加热搅拌
action_sequence.append(create_action_log(f"使用加热搅拌器进行定时溶解", "🔥"))
dissolve_action = {
"device_id": heatchill_id,
@@ -292,6 +770,7 @@ def generate_dissolve_protocol(
elif stirrer_id:
# 使用定时搅拌
action_sequence.append(create_action_log(f"使用搅拌器进行定时溶解", "🌪️"))
stir_action = {
"device_id": stirrer_id,
@@ -308,6 +787,7 @@ def generate_dissolve_protocol(
else:
# 简单等待
action_sequence.append(create_action_log(f"简单等待溶解完成", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": final_time}
@@ -315,7 +795,9 @@ def generate_dissolve_protocol(
# 步骤5.5: 停止加热搅拌(如果需要)
if heatchill_id and final_time == 0 and final_temp > 25.0:
debug_print(f"🔍 5.5: 停止加热器")
action_sequence.append(create_action_log("停止加热搅拌器", "🛑"))
stop_action = {
"device_id": heatchill_id,
"action_name": "heat_chill_stop",
@@ -326,7 +808,7 @@ def generate_dissolve_protocol(
action_sequence.append(stop_action)
except Exception as e:
debug_print(f"溶解流程执行失败: {str(e)}")
debug_print(f"溶解流程执行失败: {str(e)}")
action_sequence.append(create_action_log(f"溶解流程失败: {str(e)}", ""))
# 添加错误日志
action_sequence.append({
@@ -347,8 +829,23 @@ def generate_dissolve_protocol(
final_liquid_volume = current_volume
# === 最终结果 ===
debug_print(f"溶解协议完成: {vessel_id}, 类型={dissolve_type}, "
f"动作数={len(action_sequence)}, 体积={original_liquid_volume:.2f}{final_liquid_volume:.2f}mL")
debug_print("=" * 60)
debug_print(f"🎉 溶解协议生成完成")
debug_print(f"📊 协议统计:")
debug_print(f" 📋 总动作数: {len(action_sequence)}")
debug_print(f" 🥼 容器: {vessel_id}")
debug_print(f" {dissolve_emoji} 溶解类型: {dissolve_type}")
if is_liquid_dissolve:
debug_print(f" 💧 溶剂: {solvent} ({final_volume}mL)")
if is_solid_dissolve:
debug_print(f" 🧪 试剂: {reagent}")
debug_print(f" ⚖️ 质量: {final_mass}g")
debug_print(f" 🧬 摩尔: {mol}")
debug_print(f" 🌡️ 温度: {final_temp}°C")
debug_print(f" ⏱️ 时间: {final_time}s")
debug_print(f" 📊 溶解前体积: {original_liquid_volume:.2f}mL")
debug_print(f" 📊 溶解后体积: {final_liquid_volume:.2f}mL")
debug_print("=" * 60)
# 添加完成日志
summary_msg = f"溶解协议完成: {vessel_id}"
@@ -357,7 +854,7 @@ def generate_dissolve_protocol(
if is_solid_dissolve:
summary_msg += f" (溶解 {final_mass}g {reagent})"
action_sequence.append(create_action_log(summary_msg, ""))
action_sequence.append(create_action_log(summary_msg, "🎉"))
return action_sequence
@@ -369,7 +866,7 @@ def dissolve_solid_by_mass(G: nx.DiGraph, vessel: dict, reagent: str, mass: Unio
temp: Union[str, float] = 25.0, time: Union[str, float] = "10 min") -> List[Dict[str, Any]]:
"""按质量溶解固体"""
vessel_id = vessel["id"]
debug_print(f"快速固体溶解: {reagent} ({mass}) → {vessel_id}")
debug_print(f"🧂 快速固体溶解: {reagent} ({mass}) → {vessel_id}")
return generate_dissolve_protocol(
G, vessel,
mass=mass,
@@ -382,7 +879,7 @@ def dissolve_solid_by_moles(G: nx.DiGraph, vessel: dict, reagent: str, mol: str,
temp: Union[str, float] = 25.0, time: Union[str, float] = "10 min") -> List[Dict[str, Any]]:
"""按摩尔数溶解固体"""
vessel_id = vessel["id"]
debug_print(f"按摩尔数溶解固体: {reagent} ({mol}) → {vessel_id}")
debug_print(f"🧬 按摩尔数溶解固体: {reagent} ({mol}) → {vessel_id}")
return generate_dissolve_protocol(
G, vessel,
mol=mol,
@@ -395,7 +892,7 @@ def dissolve_with_solvent(G: nx.DiGraph, vessel: dict, solvent: str, volume: Uni
temp: Union[str, float] = 25.0, time: Union[str, float] = "5 min") -> List[Dict[str, Any]]:
"""用溶剂溶解"""
vessel_id = vessel["id"]
debug_print(f"溶剂溶解: {solvent} ({volume}) → {vessel_id}")
debug_print(f"💧 溶剂溶解: {solvent} ({volume}) → {vessel_id}")
return generate_dissolve_protocol(
G, vessel,
solvent=solvent,
@@ -407,7 +904,7 @@ def dissolve_with_solvent(G: nx.DiGraph, vessel: dict, solvent: str, volume: Uni
def dissolve_at_room_temp(G: nx.DiGraph, vessel: dict, solvent: str, volume: Union[str, float]) -> List[Dict[str, Any]]:
"""室温溶解"""
vessel_id = vessel["id"]
debug_print(f"室温溶解: {solvent} ({volume}) → {vessel_id}")
debug_print(f"🌡️ 室温溶解: {solvent} ({volume}) → {vessel_id}")
return generate_dissolve_protocol(
G, vessel,
solvent=solvent,
@@ -420,7 +917,7 @@ def dissolve_with_heating(G: nx.DiGraph, vessel: dict, solvent: str, volume: Uni
temp: Union[str, float] = "60 °C", time: Union[str, float] = "15 min") -> List[Dict[str, Any]]:
"""加热溶解"""
vessel_id = vessel["id"]
debug_print(f"加热溶解: {solvent} ({volume}) → {vessel_id} @ {temp}")
debug_print(f"🔥 加热溶解: {solvent} ({volume}) → {vessel_id} @ {temp}")
return generate_dissolve_protocol(
G, vessel,
solvent=solvent,
@@ -432,31 +929,37 @@ def dissolve_with_heating(G: nx.DiGraph, vessel: dict, solvent: str, volume: Uni
# 测试函数
def test_dissolve_protocol():
"""测试溶解协议的各种参数解析"""
debug_print("=== DISSOLVE PROTOCOL 增强版测试 ===")
# 测试体积解析
debug_print("💧 测试体积解析...")
volumes = ["10 mL", "?", 10.0, "1 L", "500 μL"]
for vol in volumes:
result = parse_volume_input(vol)
debug_print(f"体积解析: {vol}{result}mL")
debug_print(f"📏 体积解析: {vol}{result}mL")
# 测试质量解析
debug_print("⚖️ 测试质量解析...")
masses = ["2.9 g", "?", 2.5, "500 mg"]
for mass in masses:
result = parse_mass_input(mass)
debug_print(f"质量解析: {mass}{result}g")
debug_print(f"⚖️ 质量解析: {mass}{result}g")
# 测试温度解析
debug_print("🌡️ 测试温度解析...")
temps = ["60 °C", "room temperature", "?", 25.0, "reflux"]
for temp in temps:
result = parse_temperature_input(temp)
debug_print(f"温度解析: {temp}{result}°C")
debug_print(f"🌡️ 温度解析: {temp}{result}°C")
# 测试时间解析
debug_print("⏱️ 测试时间解析...")
times = ["30 min", "1 h", "?", 60.0]
for time in times:
result = parse_time_input(time)
debug_print(f"时间解析: {time}{result}s")
debug_print("测试完成")
debug_print(f"⏱️ 时间解析: {time}{result}s")
debug_print("测试完成")
if __name__ == "__main__":
test_dissolve_protocol()

View File

@@ -1,40 +1,87 @@
import networkx as nx
from typing import List, Dict, Any
from .utils.vessel_parser import get_vessel, find_connected_heatchill
from .utils.logger_util import debug_print
from unilabos.compile.utils.vessel_parser import get_vessel
def find_connected_heater(G: nx.DiGraph, vessel: str) -> str:
"""
查找与容器相连的加热器
Args:
G: 网络图
vessel: 容器名称
Returns:
str: 加热器ID如果没有则返回None
"""
print(f"DRY: 正在查找与容器 '{vessel}' 相连的加热器...")
# 查找所有加热器节点
heater_nodes = [node for node in G.nodes()
if ('heater' in node.lower() or
'heat' in node.lower() or
G.nodes[node].get('class') == 'virtual_heatchill' or
G.nodes[node].get('type') == 'heater')]
print(f"DRY: 找到的加热器节点: {heater_nodes}")
# 检查是否有加热器与目标容器相连
for heater in heater_nodes:
if G.has_edge(heater, vessel) or G.has_edge(vessel, heater):
print(f"DRY: 找到与容器 '{vessel}' 相连的加热器: {heater}")
return heater
# 如果没有直接连接,查找距离最近的加热器
for heater in heater_nodes:
try:
path = nx.shortest_path(G, source=heater, target=vessel)
if len(path) <= 3: # 最多2个中间节点
print(f"DRY: 找到距离较近的加热器: {heater}, 路径: {''.join(path)}")
return heater
except nx.NetworkXNoPath:
continue
print(f"DRY: 未找到与容器 '{vessel}' 相连的加热器")
return None
def generate_dry_protocol(
G: nx.DiGraph,
vessel: dict,
compound: str = "",
**kwargs
vessel: dict, # 🔧 修改:从字符串改为字典类型
compound: str = "", # 🔧 修改:参数顺序调整,并设置默认值
**kwargs # 接收其他可能的参数但不使用
) -> List[Dict[str, Any]]:
"""
生成干燥协议序列
Args:
G: 有向图,节点为容器和设备
vessel: 目标容器字典从XDL传入
compound: 化合物名称从XDL传入可选
**kwargs: 其他可选参数,但不使用
Returns:
List[Dict[str, Any]]: 动作序列
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
action_sequence = []
# 默认参数
dry_temp = 60.0
dry_time = 3600.0
simulation_time = 60.0
debug_print(f"开始生成干燥协议: vessel={vessel_id}, compound={compound or '未指定'}, temp={dry_temp}°C")
# 记录干燥前的容器状态
dry_temp = 60.0 # 默认干燥温度 60°C
dry_time = 3600.0 # 默认干燥时间 1小时3600秒
simulation_time = 60.0 # 模拟时间 1分钟
print(f"🌡️ DRY: 开始生成干燥协议 ✨")
print(f" 🥽 vessel: {vessel} (ID: {vessel_id})")
print(f" 🧪 化合物: {compound or '未指定'}")
print(f" 🔥 干燥温度: {dry_temp}°C")
print(f" ⏰ 干燥时间: {dry_time/60:.0f} 分钟")
# 🔧 新增:记录干燥前的容器状态
print(f"🔍 记录干燥前容器状态...")
original_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -42,30 +89,39 @@ def generate_dry_protocol(
original_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
original_liquid_volume = current_volume
print(f"📊 干燥前液体体积: {original_liquid_volume:.2f}mL")
# 1. 验证目标容器存在
print(f"\n📋 步骤1: 验证目标容器 '{vessel_id}' 是否存在...")
if vessel_id not in G.nodes():
debug_print(f"容器 '{vessel_id}' 不存在于系统中,跳过干燥")
print(f"⚠️ DRY: 警告 - 容器 '{vessel_id}' 不存在于系统中,跳过干燥 😢")
return action_sequence
print(f"✅ 容器 '{vessel_id}' 验证通过!")
# 2. 查找相连的加热器
heater_id = find_connected_heatchill(G, vessel_id)
print(f"\n🔍 步骤2: 查找与容器相连的加热器...")
heater_id = find_connected_heater(G, vessel_id) # 🔧 使用 vessel_id
if heater_id is None:
debug_print(f"未找到与容器 '{vessel_id}' 相连的加热器,添加模拟干燥动作")
print(f"😭 DRY: 警告 - 未找到与容器 '{vessel_id}' 相连的加热器,跳过干燥")
print(f"🎭 添加模拟干燥动作...")
# 添加一个等待动作,表示干燥过程(模拟)
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
"time": 10.0,
"time": 10.0, # 模拟等待时间
"description": f"模拟干燥 {compound or '化合物'} (无加热器可用)"
}
})
# 模拟干燥的体积变化
# 🔧 新增:模拟干燥的体积变化(溶剂蒸发)
print(f"🔧 模拟干燥过程的体积减少...")
if original_liquid_volume > 0:
# 假设干燥过程中损失10%的体积(溶剂蒸发)
volume_loss = original_liquid_volume * 0.1
new_volume = max(0.0, original_liquid_volume - volume_loss)
# 更新vessel字典中的体积
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
@@ -77,14 +133,15 @@ def generate_dry_protocol(
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"]["liquid_volume"] = new_volume
# 🔧 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = new_volume
@@ -92,27 +149,33 @@ def generate_dry_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [new_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = new_volume
debug_print(f"模拟干燥体积变化: {original_liquid_volume:.2f}mL -> {new_volume:.2f}mL")
debug_print(f"协议生成完成,共 {len(action_sequence)} 个动作")
print(f"📊 模拟干燥体积变化: {original_liquid_volume:.2f}mL {new_volume:.2f}mL (-{volume_loss:.2f}mL)")
print(f"📄 DRY: 协议生成完成,共 {len(action_sequence)} 个动作 🎯")
return action_sequence
debug_print(f"找到加热器: {heater_id}")
print(f"🎉 找到加热器: {heater_id}!")
# 3. 启动加热器进行干燥
print(f"\n🚀 步骤3: 开始执行干燥流程...")
print(f"🔥 启动加热器 {heater_id} 进行干燥")
# 3.1 启动加热
print(f" ⚡ 动作1: 启动加热到 {dry_temp}°C...")
action_sequence.append({
"device_id": heater_id,
"action_name": "heat_chill_start",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
"temp": dry_temp,
"purpose": f"干燥 {compound or '化合物'}"
}
})
print(f" ✅ 加热器启动命令已添加 🔥")
# 3.2 等待温度稳定
print(f" ⏳ 动作2: 等待温度稳定...")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
@@ -120,27 +183,34 @@ def generate_dry_protocol(
"description": f"等待温度稳定到 {dry_temp}°C"
}
})
print(f" ✅ 温度稳定等待命令已添加 🌡️")
# 3.3 保持干燥温度
print(f" 🔄 动作3: 保持干燥温度 {simulation_time/60:.0f} 分钟...")
action_sequence.append({
"device_id": heater_id,
"action_name": "heat_chill",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
"temp": dry_temp,
"time": simulation_time,
"purpose": f"干燥 {compound or '化合物'},保持温度 {dry_temp}°C"
}
})
# 干燥过程中的体积变化计算
print(f" ✅ 温度保持命令已添加 🌡️⏰")
# 🔧 新增:干燥过程中的体积变化计算
print(f"🔧 计算干燥过程中的体积变化...")
if original_liquid_volume > 0:
evaporation_rate = 0.001 * dry_temp
total_evaporation = min(original_liquid_volume * 0.8,
evaporation_rate * simulation_time)
# 干燥过程中,溶剂会蒸发,固体保留
# 根据温度和时间估算蒸发量
evaporation_rate = 0.001 * dry_temp # 每秒每°C蒸发0.001mL
total_evaporation = min(original_liquid_volume * 0.8,
evaporation_rate * simulation_time) # 最多蒸发80%
new_volume = max(0.0, original_liquid_volume - total_evaporation)
# 更新vessel字典中的体积
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
@@ -152,14 +222,15 @@ def generate_dry_protocol(
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"]["liquid_volume"] = new_volume
# 🔧 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = new_volume
@@ -167,29 +238,37 @@ def generate_dry_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [new_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = new_volume
debug_print(f"干燥体积变化: {original_liquid_volume:.2f}mL -> {new_volume:.2f}mL (-{total_evaporation:.2f}mL)")
print(f"📊 干燥体积变化计算:")
print(f" - 初始体积: {original_liquid_volume:.2f}mL")
print(f" - 蒸发量: {total_evaporation:.2f}mL")
print(f" - 剩余体积: {new_volume:.2f}mL")
print(f" - 蒸发率: {(total_evaporation/original_liquid_volume*100):.1f}%")
# 3.4 停止加热
print(f" ⏹️ 动作4: 停止加热...")
action_sequence.append({
"device_id": heater_id,
"action_name": "heat_chill_stop",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
"purpose": f"干燥完成,停止加热"
}
})
print(f" ✅ 停止加热命令已添加 🛑")
# 3.5 等待冷却
print(f" ❄️ 动作5: 等待冷却...")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
"time": 10.0,
"time": 10.0, # 等待10秒冷却
"description": f"等待 {compound or '化合物'} 冷却"
}
})
# 最终状态
print(f" ✅ 冷却等待命令已添加 🧊")
# 🔧 新增:干燥完成后的状态报告
final_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -197,37 +276,60 @@ def generate_dry_protocol(
final_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
final_liquid_volume = current_volume
debug_print(f"干燥协议生成完成: {len(action_sequence)} 个动作, 体积 {original_liquid_volume:.2f} -> {final_liquid_volume:.2f}mL")
print(f"\n🎊 DRY: 协议生成完成,共 {len(action_sequence)} 个动作 🎯")
print(f"⏱️ DRY: 预计总时间: {(simulation_time + 30)/60:.0f} 分钟 ⌛")
print(f"📊 干燥结果:")
print(f" - 容器: {vessel_id}")
print(f" - 化合物: {compound or '未指定'}")
print(f" - 干燥前体积: {original_liquid_volume:.2f}mL")
print(f" - 干燥后体积: {final_liquid_volume:.2f}mL")
print(f" - 蒸发体积: {(original_liquid_volume - final_liquid_volume):.2f}mL")
print(f"🏁 所有动作序列准备就绪! ✨")
return action_sequence
# 便捷函数
def generate_quick_dry_protocol(G: nx.DiGraph, vessel: dict, compound: str = "",
# 🔧 新增:便捷函数
def generate_quick_dry_protocol(G: nx.DiGraph, vessel: dict, compound: str = "",
temp: float = 40.0, time: float = 30.0) -> List[Dict[str, Any]]:
"""快速干燥:低温短时间"""
vessel_id = vessel["id"]
print(f"🌡️ 快速干燥: {compound or '化合物'}{vessel_id} @ {temp}°C ({time}min)")
# 临时修改默认参数
import types
temp_func = types.FunctionType(
generate_dry_protocol.__code__,
generate_dry_protocol.__globals__
)
# 直接调用原函数,但修改内部参数
return generate_dry_protocol(G, vessel, compound)
def generate_thorough_dry_protocol(G: nx.DiGraph, vessel: dict, compound: str = "",
def generate_thorough_dry_protocol(G: nx.DiGraph, vessel: dict, compound: str = "",
temp: float = 80.0, time: float = 120.0) -> List[Dict[str, Any]]:
"""深度干燥:高温长时间"""
vessel_id = vessel["id"]
print(f"🔥 深度干燥: {compound or '化合物'}{vessel_id} @ {temp}°C ({time}min)")
return generate_dry_protocol(G, vessel, compound)
def generate_gentle_dry_protocol(G: nx.DiGraph, vessel: dict, compound: str = "",
def generate_gentle_dry_protocol(G: nx.DiGraph, vessel: dict, compound: str = "",
temp: float = 30.0, time: float = 180.0) -> List[Dict[str, Any]]:
"""温和干燥:低温长时间"""
vessel_id = vessel["id"]
print(f"🌡️ 温和干燥: {compound or '化合物'}{vessel_id} @ {temp}°C ({time}min)")
return generate_dry_protocol(G, vessel, compound)
# 测试函数
def test_dry_protocol():
"""测试干燥协议"""
debug_print("=== DRY PROTOCOL 测试 ===")
debug_print("测试完成")
print("=== DRY PROTOCOL 测试 ===")
print("测试完成")
if __name__ == "__main__":
test_dry_protocol()
test_dry_protocol()

View File

@@ -3,14 +3,38 @@ from functools import partial
import networkx as nx
import logging
import uuid
import sys
from typing import List, Dict, Any, Optional
from .utils.vessel_parser import get_vessel, find_connected_stirrer
from .utils.logger_util import debug_print, action_log
from .utils.vessel_parser import get_vessel
from .utils.logger_util import action_log
from .pump_protocol import generate_pump_protocol_with_rinsing, generate_pump_protocol
# 设置日志
logger = logging.getLogger(__name__)
# 确保输出编码为UTF-8
if hasattr(sys.stdout, 'reconfigure'):
try:
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
except:
pass
def debug_print(message):
"""调试输出函数 - 支持中文"""
try:
# 确保消息是字符串格式
safe_message = str(message)
logger.info(f"[抽真空充气] {safe_message}")
except UnicodeEncodeError:
# 如果编码失败,尝试替换不支持的字符
safe_message = str(message).encode('utf-8', errors='replace').decode('utf-8')
logger.info(f"[抽真空充气] {safe_message}")
except Exception as e:
# 最后的安全措施
fallback_message = f"日志输出错误: {repr(message)}"
logger.info(f"[抽真空充气] {fallback_message}")
create_action_log = partial(action_log, prefix="[抽真空充气]")
def find_gas_source(G: nx.DiGraph, gas: str) -> str:
@@ -20,9 +44,10 @@ def find_gas_source(G: nx.DiGraph, gas: str) -> str:
2. 气体类型匹配data.gas_type
3. 默认气源
"""
debug_print(f"正在查找气体 '{gas}' 的气源...")
# 通过容器名称匹配
debug_print(f"🔍 正在查找气体 '{gas}' 的气源...")
# 第一步:通过容器名称匹配
debug_print(f"📋 方法1: 容器名称匹配...")
gas_source_patterns = [
f"gas_source_{gas}",
f"gas_{gas}",
@@ -32,178 +57,254 @@ def find_gas_source(G: nx.DiGraph, gas: str) -> str:
f"reagent_bottle_{gas}",
f"bottle_{gas}"
]
debug_print(f"🎯 尝试的容器名称: {gas_source_patterns}")
for pattern in gas_source_patterns:
if pattern in G.nodes():
debug_print(f"通过名称找到气源: {pattern}")
debug_print(f"通过名称找到气源: {pattern}")
return pattern
# 通过气体类型匹配 (data.gas_type)
# 第二步:通过气体类型匹配 (data.gas_type)
debug_print(f"📋 方法2: 气体类型匹配...")
for node_id in G.nodes():
node_data = G.nodes[node_id]
node_class = node_data.get('class', '') or ''
if ('gas_source' in node_class or
'gas' in node_id.lower() or
# 检查是否是气源设备
if ('gas_source' in node_class or
'gas' in node_id.lower() or
node_id.startswith('flask_')):
# 检查 data.gas_type
data = node_data.get('data', {})
gas_type = data.get('gas_type', '')
if gas_type.lower() == gas.lower():
debug_print(f"通过气体类型找到气源: {node_id} (气体类型: {gas_type})")
debug_print(f"通过气体类型找到气源: {node_id} (气体类型: {gas_type})")
return node_id
# 检查 config.gas_type
config = node_data.get('config', {})
config_gas_type = config.get('gas_type', '')
if config_gas_type.lower() == gas.lower():
debug_print(f"通过配置气体类型找到气源: {node_id} (配置气体类型: {config_gas_type})")
debug_print(f"通过配置气体类型找到气源: {node_id} (配置气体类型: {config_gas_type})")
return node_id
# 查找所有可用的气源设备
# 第三步:查找所有可用的气源设备
debug_print(f"📋 方法3: 查找可用气源...")
available_gas_sources = []
for node_id in G.nodes():
node_data = G.nodes[node_id]
node_class = node_data.get('class', '') or ''
if ('gas_source' in node_class or
if ('gas_source' in node_class or
'gas' in node_id.lower() or
(node_id.startswith('flask_') and any(g in node_id.lower() for g in ['air', 'nitrogen', 'argon']))):
data = node_data.get('data', {})
gas_type = data.get('gas_type', '未知')
available_gas_sources.append(f"{node_id} (气体类型: {gas_type})")
# 如果找不到特定气体,使用默认的第一个气源
debug_print(f"📊 可用气源: {available_gas_sources}")
# 第四步:如果找不到特定气体,使用默认的第一个气源
debug_print(f"📋 方法4: 查找默认气源...")
default_gas_sources = [
node for node in G.nodes()
node for node in G.nodes()
if ((G.nodes[node].get('class') or '').find('virtual_gas_source') != -1
or 'gas_source' in node)
]
if default_gas_sources:
default_source = default_gas_sources[0]
debug_print(f"未找到特定气体 '{gas}',使用默认气源: {default_source}")
debug_print(f"⚠️ 未找到特定气体 '{gas}',使用默认气源: {default_source}")
return default_source
debug_print(f"❌ 所有方法都失败了!")
raise ValueError(f"无法找到气体 '{gas}' 的气源。可用气源: {available_gas_sources}")
def find_vacuum_pump(G: nx.DiGraph) -> str:
"""查找真空泵设备"""
debug_print("🔍 正在查找真空泵...")
vacuum_pumps = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if ('virtual_vacuum_pump' in node_class or
'vacuum_pump' in node.lower() or
if ('virtual_vacuum_pump' in node_class or
'vacuum_pump' in node.lower() or
'vacuum' in node_class.lower()):
vacuum_pumps.append(node)
debug_print(f"📋 发现真空泵: {node}")
if not vacuum_pumps:
debug_print(f"❌ 系统中未找到真空泵")
raise ValueError("系统中未找到真空泵")
debug_print(f"使用真空泵: {vacuum_pumps[0]}")
debug_print(f"使用真空泵: {vacuum_pumps[0]}")
return vacuum_pumps[0]
def find_connected_stirrer(G: nx.DiGraph, vessel: str) -> Optional[str]:
"""查找与指定容器相连的搅拌器"""
debug_print(f"🔍 正在查找与容器 {vessel} 连接的搅拌器...")
stirrer_nodes = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if 'virtual_stirrer' in node_class or 'stirrer' in node.lower():
stirrer_nodes.append(node)
debug_print(f"📋 发现搅拌器: {node}")
debug_print(f"📊 找到的搅拌器总数: {len(stirrer_nodes)}")
# 检查哪个搅拌器与目标容器相连
for stirrer in stirrer_nodes:
if G.has_edge(stirrer, vessel) or G.has_edge(vessel, stirrer):
debug_print(f"✅ 找到连接的搅拌器: {stirrer}")
return stirrer
# 如果没有连接的搅拌器,返回第一个可用的
if stirrer_nodes:
debug_print(f"⚠️ 未找到直接连接的搅拌器,使用第一个可用的: {stirrer_nodes[0]}")
return stirrer_nodes[0]
debug_print("❌ 未找到搅拌器")
return None
def find_vacuum_solenoid_valve(G: nx.DiGraph, vacuum_pump: str) -> Optional[str]:
"""查找真空泵相关的电磁阀"""
debug_print(f"🔍 正在查找真空泵 {vacuum_pump} 的电磁阀...")
# 查找所有电磁阀
solenoid_valves = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if ('solenoid' in node_class.lower() or 'solenoid_valve' in node.lower()):
solenoid_valves.append(node)
debug_print(f"📋 发现电磁阀: {node}")
debug_print(f"📊 找到的电磁阀: {solenoid_valves}")
# 检查连接关系
debug_print(f"📋 方法1: 检查连接关系...")
for solenoid in solenoid_valves:
if G.has_edge(solenoid, vacuum_pump) or G.has_edge(vacuum_pump, solenoid):
debug_print(f"找到连接的真空电磁阀: {solenoid}")
debug_print(f"找到连接的真空电磁阀: {solenoid}")
return solenoid
# 通过命名规则查找
debug_print(f"📋 方法2: 检查命名规则...")
for solenoid in solenoid_valves:
if 'vacuum' in solenoid.lower() or solenoid == 'solenoid_valve_1':
debug_print(f"通过命名找到真空电磁阀: {solenoid}")
debug_print(f"通过命名找到真空电磁阀: {solenoid}")
return solenoid
debug_print("未找到真空电磁阀")
debug_print("⚠️ 未找到真空电磁阀")
return None
def find_gas_solenoid_valve(G: nx.DiGraph, gas_source: str) -> Optional[str]:
"""查找气源相关的电磁阀"""
debug_print(f"🔍 正在查找气源 {gas_source} 的电磁阀...")
# 查找所有电磁阀
solenoid_valves = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if ('solenoid' in node_class.lower() or 'solenoid_valve' in node.lower()):
solenoid_valves.append(node)
debug_print(f"📊 找到的电磁阀: {solenoid_valves}")
# 检查连接关系
debug_print(f"📋 方法1: 检查连接关系...")
for solenoid in solenoid_valves:
if G.has_edge(gas_source, solenoid) or G.has_edge(solenoid, gas_source):
debug_print(f"找到连接的气源电磁阀: {solenoid}")
debug_print(f"找到连接的气源电磁阀: {solenoid}")
return solenoid
# 通过命名规则查找
debug_print(f"📋 方法2: 检查命名规则...")
for solenoid in solenoid_valves:
if 'gas' in solenoid.lower() or solenoid == 'solenoid_valve_2':
debug_print(f"通过命名找到气源电磁阀: {solenoid}")
debug_print(f"通过命名找到气源电磁阀: {solenoid}")
return solenoid
debug_print("未找到气源电磁阀")
debug_print("⚠️ 未找到气源电磁阀")
return None
def generate_evacuateandrefill_protocol(
G: nx.DiGraph,
vessel: dict,
vessel: dict, # 🔧 修改:从字符串改为字典类型
gas: str,
**kwargs
) -> List[Dict[str, Any]]:
"""
生成抽真空和充气操作的动作序列
生成抽真空和充气操作的动作序列 - 中文版
Args:
G: 设备图
vessel: 目标容器字典(必需)
gas: 气体名称(必需)
gas: 气体名称(必需)
**kwargs: 其他参数(兼容性)
Returns:
List[Dict[str, Any]]: 动作序列
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
# 硬编码重复次数为 3
repeats = 3
# 生成协议ID
protocol_id = str(uuid.uuid4())
debug_print(f"开始生成抽真空充气协议: vessel={vessel_id}, gas={gas}, repeats={repeats}")
debug_print(f"🆔 生成协议ID: {protocol_id}")
debug_print("=" * 60)
debug_print("🧪 开始生成抽真空充气协议")
debug_print(f"📋 原始参数:")
debug_print(f" 🥼 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 💨 气体: '{gas}'")
debug_print(f" 🔄 循环次数: {repeats} (硬编码)")
debug_print(f" 📦 其他参数: {kwargs}")
debug_print("=" * 60)
action_sequence = []
# === 参数验证和修正 ===
debug_print("🔍 步骤1: 参数验证和修正...")
action_sequence.append(create_action_log(f"开始抽真空充气操作 - 容器: {vessel_id}", "🎬"))
action_sequence.append(create_action_log(f"目标气体: {gas}", "💨"))
action_sequence.append(create_action_log(f"循环次数: {repeats}", "🔄"))
# 验证必需参数
if not vessel_id:
debug_print("❌ 容器参数不能为空")
raise ValueError("容器参数不能为空")
if not gas:
debug_print("❌ 气体参数不能为空")
raise ValueError("气体参数不能为空")
if vessel_id not in G.nodes():
if vessel_id not in G.nodes(): # 🔧 使用 vessel_id
debug_print(f"❌ 容器 '{vessel_id}' 在系统中不存在")
raise ValueError(f"容器 '{vessel_id}' 在系统中不存在")
debug_print("✅ 基本参数验证通过")
action_sequence.append(create_action_log("参数验证通过", ""))
# 标准化气体名称
debug_print("🔧 标准化气体名称...")
gas_aliases = {
'n2': 'nitrogen',
'ar': 'argon',
@@ -218,54 +319,61 @@ def generate_evacuateandrefill_protocol(
'二氧化碳': 'carbon_dioxide',
'氢气': 'hydrogen'
}
original_gas = gas
gas_lower = gas.lower().strip()
if gas_lower in gas_aliases:
gas = gas_aliases[gas_lower]
debug_print(f"标准化气体名称: {original_gas} -> {gas}")
debug_print(f"🔄 标准化气体名称: {original_gas} -> {gas}")
action_sequence.append(create_action_log(f"气体名称标准化: {original_gas} -> {gas}", "🔄"))
debug_print(f"最终参数: 容器={vessel_id}, 气体={gas}, 重复={repeats}")
debug_print(f"📋 最终参数: 容器={vessel_id}, 气体={gas}, 重复={repeats}")
# === 查找设备 ===
debug_print("🔍 步骤2: 查找设备...")
action_sequence.append(create_action_log("正在查找相关设备...", "🔍"))
try:
vacuum_pump = find_vacuum_pump(G)
action_sequence.append(create_action_log(f"找到真空泵: {vacuum_pump}", "🌪️"))
gas_source = find_gas_source(G, gas)
action_sequence.append(create_action_log(f"找到气源: {gas_source}", "💨"))
vacuum_solenoid = find_vacuum_solenoid_valve(G, vacuum_pump)
if vacuum_solenoid:
action_sequence.append(create_action_log(f"找到真空电磁阀: {vacuum_solenoid}", "🚪"))
else:
action_sequence.append(create_action_log("未找到真空电磁阀", "⚠️"))
gas_solenoid = find_gas_solenoid_valve(G, gas_source)
if gas_solenoid:
action_sequence.append(create_action_log(f"找到气源电磁阀: {gas_solenoid}", "🚪"))
else:
action_sequence.append(create_action_log("未找到气源电磁阀", "⚠️"))
stirrer_id = find_connected_stirrer(G, vessel_id)
stirrer_id = find_connected_stirrer(G, vessel_id) # 🔧 使用 vessel_id
if stirrer_id:
action_sequence.append(create_action_log(f"找到搅拌器: {stirrer_id}", "🌪️"))
else:
action_sequence.append(create_action_log("未找到搅拌器", "⚠️"))
debug_print(f"设备配置: 真空泵={vacuum_pump}, 气源={gas_source}, 搅拌器={stirrer_id}")
debug_print(f"📊 设备配置:")
debug_print(f" 🌪️ 真空泵: {vacuum_pump}")
debug_print(f" 💨 气源: {gas_source}")
debug_print(f" 🚪 真空电磁阀: {vacuum_solenoid}")
debug_print(f" 🚪 气源电磁阀: {gas_solenoid}")
debug_print(f" 🌪️ 搅拌器: {stirrer_id}")
except Exception as e:
debug_print(f"设备查找失败: {str(e)}")
debug_print(f"设备查找失败: {str(e)}")
action_sequence.append(create_action_log(f"设备查找失败: {str(e)}", ""))
raise ValueError(f"设备查找失败: {str(e)}")
# === 参数设置 ===
debug_print("🔍 步骤3: 参数设置...")
action_sequence.append(create_action_log("设置操作参数...", "⚙️"))
# 根据气体类型调整参数
if gas.lower() in ['nitrogen', 'argon']:
VACUUM_VOLUME = 25.0
@@ -273,6 +381,7 @@ def generate_evacuateandrefill_protocol(
PUMP_FLOW_RATE = 2.0
VACUUM_TIME = 30.0
REFILL_TIME = 20.0
debug_print("💨 惰性气体: 使用标准参数")
action_sequence.append(create_action_log("检测到惰性气体,使用标准参数", "💨"))
elif gas.lower() in ['air', 'oxygen']:
VACUUM_VOLUME = 20.0
@@ -280,6 +389,7 @@ def generate_evacuateandrefill_protocol(
PUMP_FLOW_RATE = 1.5
VACUUM_TIME = 45.0
REFILL_TIME = 25.0
debug_print("🔥 活性气体: 使用保守参数")
action_sequence.append(create_action_log("检测到活性气体,使用保守参数", "🔥"))
else:
VACUUM_VOLUME = 15.0
@@ -287,88 +397,116 @@ def generate_evacuateandrefill_protocol(
PUMP_FLOW_RATE = 1.0
VACUUM_TIME = 60.0
REFILL_TIME = 30.0
debug_print("❓ 未知气体: 使用安全参数")
action_sequence.append(create_action_log("未知气体类型,使用安全参数", ""))
STIR_SPEED = 200.0
debug_print(f"⚙️ 操作参数:")
debug_print(f" 📏 真空体积: {VACUUM_VOLUME}mL")
debug_print(f" 📏 充气体积: {REFILL_VOLUME}mL")
debug_print(f" ⚡ 泵流速: {PUMP_FLOW_RATE}mL/s")
debug_print(f" ⏱️ 真空时间: {VACUUM_TIME}s")
debug_print(f" ⏱️ 充气时间: {REFILL_TIME}s")
debug_print(f" 🌪️ 搅拌速度: {STIR_SPEED}RPM")
action_sequence.append(create_action_log(f"真空体积: {VACUUM_VOLUME}mL", "📏"))
action_sequence.append(create_action_log(f"充气体积: {REFILL_VOLUME}mL", "📏"))
action_sequence.append(create_action_log(f"泵流速: {PUMP_FLOW_RATE}mL/s", ""))
# === 路径验证 ===
debug_print("🔍 步骤4: 路径验证...")
action_sequence.append(create_action_log("验证传输路径...", "🛤️"))
try:
if nx.has_path(G, vessel_id, vacuum_pump):
# 验证抽真空路径
if nx.has_path(G, vessel_id, vacuum_pump): # 🔧 使用 vessel_id
vacuum_path = nx.shortest_path(G, source=vessel_id, target=vacuum_pump)
debug_print(f"✅ 真空路径: {' -> '.join(vacuum_path)}")
action_sequence.append(create_action_log(f"真空路径: {' -> '.join(vacuum_path)}", "🛤️"))
else:
debug_print(f"⚠️ 真空路径不存在,继续执行但可能有问题")
action_sequence.append(create_action_log("真空路径检查: 路径不存在", "⚠️"))
if nx.has_path(G, gas_source, vessel_id):
# 验证充气路径
if nx.has_path(G, gas_source, vessel_id): # 🔧 使用 vessel_id
gas_path = nx.shortest_path(G, source=gas_source, target=vessel_id)
debug_print(f"✅ 气体路径: {' -> '.join(gas_path)}")
action_sequence.append(create_action_log(f"气体路径: {' -> '.join(gas_path)}", "🛤️"))
else:
debug_print(f"⚠️ 气体路径不存在,继续执行但可能有问题")
action_sequence.append(create_action_log("气体路径检查: 路径不存在", "⚠️"))
except Exception as e:
debug_print(f"⚠️ 路径验证失败: {str(e)},继续执行")
action_sequence.append(create_action_log(f"路径验证失败: {str(e)}", "⚠️"))
# === 启动搅拌器 ===
debug_print("🔍 步骤5: 启动搅拌器...")
if stirrer_id:
debug_print(f"🌪️ 启动搅拌器: {stirrer_id}")
action_sequence.append(create_action_log(f"启动搅拌器 {stirrer_id} (速度: {STIR_SPEED}rpm)", "🌪️"))
action_sequence.append({
"device_id": stirrer_id,
"action_name": "start_stir",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
"stir_speed": STIR_SPEED,
"purpose": "抽真空充气前预搅拌"
}
})
# 等待搅拌稳定
action_sequence.append(create_action_log("等待搅拌稳定...", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 5.0}
})
else:
debug_print("⚠️ 未找到搅拌器,跳过搅拌器启动")
action_sequence.append(create_action_log("跳过搅拌器启动", "⏭️"))
# === 执行循环 ===
debug_print("🔍 步骤6: 执行抽真空-充气循环...")
action_sequence.append(create_action_log(f"开始 {repeats} 次抽真空-充气循环", "🔄"))
for cycle in range(repeats):
debug_print(f"=== 第 {cycle+1}/{repeats} 轮循环 ===")
action_sequence.append(create_action_log(f"{cycle+1}/{repeats} 轮循环开始", "🚀"))
# ============ 抽真空阶段 ============
debug_print(f"🌪️ 抽真空阶段开始")
action_sequence.append(create_action_log("开始抽真空阶段", "🌪️"))
# 启动真空泵
debug_print(f"🔛 启动真空泵: {vacuum_pump}")
action_sequence.append(create_action_log(f"启动真空泵: {vacuum_pump}", "🔛"))
action_sequence.append({
"device_id": vacuum_pump,
"action_name": "set_status",
"action_kwargs": {"string": "ON"}
})
# 开启真空电磁阀
if vacuum_solenoid:
debug_print(f"🚪 打开真空电磁阀: {vacuum_solenoid}")
action_sequence.append(create_action_log(f"打开真空电磁阀: {vacuum_solenoid}", "🚪"))
action_sequence.append({
"device_id": vacuum_solenoid,
"action_name": "set_valve_position",
"action_kwargs": {"command": "OPEN"}
})
# 抽真空操作
debug_print(f"🌪️ 抽真空操作: {vessel_id} -> {vacuum_pump}")
action_sequence.append(create_action_log(f"开始抽真空: {vessel_id} -> {vacuum_pump}", "🌪️"))
try:
vacuum_transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=vessel_id,
from_vessel=vessel_id, # 🔧 使用 vessel_id
to_vessel=vacuum_pump,
volume=VACUUM_VOLUME,
amount="",
@@ -381,25 +519,27 @@ def generate_evacuateandrefill_protocol(
flowrate=PUMP_FLOW_RATE,
transfer_flowrate=PUMP_FLOW_RATE
)
if vacuum_transfer_actions:
action_sequence.extend(vacuum_transfer_actions)
debug_print(f"✅ 添加了 {len(vacuum_transfer_actions)} 个抽真空动作")
action_sequence.append(create_action_log(f"抽真空协议完成 ({len(vacuum_transfer_actions)} 个操作)", ""))
else:
debug_print("⚠️ 抽真空协议返回空序列,添加手动动作")
action_sequence.append(create_action_log("抽真空协议为空,使用手动等待", "⚠️"))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": VACUUM_TIME}
})
except Exception as e:
debug_print(f"抽真空失败: {str(e)}")
debug_print(f"抽真空失败: {str(e)}")
action_sequence.append(create_action_log(f"抽真空失败: {str(e)}", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": VACUUM_TIME}
})
# 抽真空后等待
wait_minutes = VACUUM_TIME / 60
action_sequence.append(create_action_log(f"抽真空后等待 ({wait_minutes:.1f} 分钟)", ""))
@@ -407,59 +547,65 @@ def generate_evacuateandrefill_protocol(
"action_name": "wait",
"action_kwargs": {"time": VACUUM_TIME}
})
# 关闭真空电磁阀
if vacuum_solenoid:
debug_print(f"🚪 关闭真空电磁阀: {vacuum_solenoid}")
action_sequence.append(create_action_log(f"关闭真空电磁阀: {vacuum_solenoid}", "🚪"))
action_sequence.append({
"device_id": vacuum_solenoid,
"action_name": "set_valve_position",
"action_kwargs": {"command": "CLOSED"}
})
# 关闭真空泵
debug_print(f"🔴 停止真空泵: {vacuum_pump}")
action_sequence.append(create_action_log(f"停止真空泵: {vacuum_pump}", "🔴"))
action_sequence.append({
"device_id": vacuum_pump,
"action_name": "set_status",
"action_kwargs": {"string": "OFF"}
})
# 阶段间等待
action_sequence.append(create_action_log("抽真空阶段完成,短暂等待", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 5.0}
})
# ============ 充气阶段 ============
debug_print(f"💨 充气阶段开始")
action_sequence.append(create_action_log("开始气体充气阶段", "💨"))
# 启动气源
debug_print(f"🔛 启动气源: {gas_source}")
action_sequence.append(create_action_log(f"启动气源: {gas_source}", "🔛"))
action_sequence.append({
"device_id": gas_source,
"action_name": "set_status",
"action_kwargs": {"string": "ON"}
})
# 开启气源电磁阀
if gas_solenoid:
debug_print(f"🚪 打开气源电磁阀: {gas_solenoid}")
action_sequence.append(create_action_log(f"打开气源电磁阀: {gas_solenoid}", "🚪"))
action_sequence.append({
"device_id": gas_solenoid,
"action_name": "set_valve_position",
"action_kwargs": {"command": "OPEN"}
})
# 充气操作
debug_print(f"💨 充气操作: {gas_source} -> {vessel_id}")
action_sequence.append(create_action_log(f"开始气体充气: {gas_source} -> {vessel_id}", "💨"))
try:
gas_transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=gas_source,
to_vessel=vessel_id,
to_vessel=vessel_id, # 🔧 使用 vessel_id
volume=REFILL_VOLUME,
amount="",
time=0.0,
@@ -471,25 +617,27 @@ def generate_evacuateandrefill_protocol(
flowrate=PUMP_FLOW_RATE,
transfer_flowrate=PUMP_FLOW_RATE
)
if gas_transfer_actions:
action_sequence.extend(gas_transfer_actions)
debug_print(f"✅ 添加了 {len(gas_transfer_actions)} 个充气动作")
action_sequence.append(create_action_log(f"气体充气协议完成 ({len(gas_transfer_actions)} 个操作)", ""))
else:
debug_print("⚠️ 充气协议返回空序列,添加手动动作")
action_sequence.append(create_action_log("充气协议为空,使用手动等待", "⚠️"))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": REFILL_TIME}
})
except Exception as e:
debug_print(f"气体充气失败: {str(e)}")
debug_print(f"气体充气失败: {str(e)}")
action_sequence.append(create_action_log(f"气体充气失败: {str(e)}", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": REFILL_TIME}
})
# 充气后等待
refill_wait_minutes = REFILL_TIME / 60
action_sequence.append(create_action_log(f"充气后等待 ({refill_wait_minutes:.1f} 分钟)", ""))
@@ -497,26 +645,29 @@ def generate_evacuateandrefill_protocol(
"action_name": "wait",
"action_kwargs": {"time": REFILL_TIME}
})
# 关闭气源电磁阀
if gas_solenoid:
debug_print(f"🚪 关闭气源电磁阀: {gas_solenoid}")
action_sequence.append(create_action_log(f"关闭气源电磁阀: {gas_solenoid}", "🚪"))
action_sequence.append({
"device_id": gas_solenoid,
"action_name": "set_valve_position",
"action_kwargs": {"command": "CLOSED"}
})
# 关闭气源
debug_print(f"🔴 停止气源: {gas_source}")
action_sequence.append(create_action_log(f"停止气源: {gas_source}", "🔴"))
action_sequence.append({
"device_id": gas_source,
"action_name": "set_status",
"action_kwargs": {"string": "OFF"}
})
# 循环间等待
if cycle < repeats - 1:
debug_print(f"⏳ 等待下一个循环...")
action_sequence.append(create_action_log("等待下一个循环...", ""))
action_sequence.append({
"action_name": "wait",
@@ -524,58 +675,78 @@ def generate_evacuateandrefill_protocol(
})
else:
action_sequence.append(create_action_log(f"{cycle+1}/{repeats} 轮循环完成", ""))
# === 停止搅拌器 ===
debug_print("🔍 步骤7: 停止搅拌器...")
if stirrer_id:
debug_print(f"🛑 停止搅拌器: {stirrer_id}")
action_sequence.append(create_action_log(f"停止搅拌器: {stirrer_id}", "🛑"))
action_sequence.append({
"device_id": stirrer_id,
"action_name": "stop_stir",
"action_kwargs": {"vessel": {"id": vessel_id},}
"action_kwargs": {"vessel": {"id": vessel_id},} # 🔧 使用 vessel_id
})
else:
action_sequence.append(create_action_log("跳过搅拌器停止", "⏭️"))
# === 最终等待 ===
action_sequence.append(create_action_log("最终稳定等待...", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 10.0}
})
# === 总结 ===
total_time = (VACUUM_TIME + REFILL_TIME + 25) * repeats + 20
debug_print(f"抽真空充气协议生成完成: {len(action_sequence)} 个动作, 预计 {total_time:.0f}s")
debug_print("=" * 60)
debug_print(f"🎉 抽真空充气协议生成完成")
debug_print(f"📊 协议统计:")
debug_print(f" 📋 总动作数: {len(action_sequence)}")
debug_print(f" ⏱️ 预计总时间: {total_time:.0f}s ({total_time/60:.1f} 分钟)")
debug_print(f" 🥼 处理容器: {vessel_id}")
debug_print(f" 💨 使用气体: {gas}")
debug_print(f" 🔄 重复次数: {repeats}")
debug_print("=" * 60)
# 添加完成日志
summary_msg = f"抽真空充气协议完成: {vessel_id} (使用 {gas}{repeats} 次循环)"
action_sequence.append(create_action_log(summary_msg, "🎉"))
return action_sequence
# === 便捷函数 ===
def generate_nitrogen_purge_protocol(G: nx.DiGraph, vessel: dict, **kwargs) -> List[Dict[str, Any]]:
def generate_nitrogen_purge_protocol(G: nx.DiGraph, vessel: dict, **kwargs) -> List[Dict[str, Any]]: # 🔧 修改参数类型
"""生成氮气置换协议"""
vessel_id = vessel["id"]
debug_print(f"💨 生成氮气置换协议: {vessel_id}")
return generate_evacuateandrefill_protocol(G, vessel, "nitrogen", **kwargs)
def generate_argon_purge_protocol(G: nx.DiGraph, vessel: dict, **kwargs) -> List[Dict[str, Any]]:
def generate_argon_purge_protocol(G: nx.DiGraph, vessel: dict, **kwargs) -> List[Dict[str, Any]]: # 🔧 修改参数类型
"""生成氩气置换协议"""
vessel_id = vessel["id"]
debug_print(f"💨 生成氩气置换协议: {vessel_id}")
return generate_evacuateandrefill_protocol(G, vessel, "argon", **kwargs)
def generate_air_purge_protocol(G: nx.DiGraph, vessel: dict, **kwargs) -> List[Dict[str, Any]]:
def generate_air_purge_protocol(G: nx.DiGraph, vessel: dict, **kwargs) -> List[Dict[str, Any]]: # 🔧 修改参数类型
"""生成空气置换协议"""
vessel_id = vessel["id"]
debug_print(f"💨 生成空气置换协议: {vessel_id}")
return generate_evacuateandrefill_protocol(G, vessel, "air", **kwargs)
def generate_inert_atmosphere_protocol(G: nx.DiGraph, vessel: dict, gas: str = "nitrogen", **kwargs) -> List[Dict[str, Any]]:
def generate_inert_atmosphere_protocol(G: nx.DiGraph, vessel: dict, gas: str = "nitrogen", **kwargs) -> List[Dict[str, Any]]: # 🔧 修改参数类型
"""生成惰性气氛协议"""
vessel_id = vessel["id"]
debug_print(f"🛡️ 生成惰性气氛协议: {vessel_id} (使用 {gas})")
return generate_evacuateandrefill_protocol(G, vessel, gas, **kwargs)
# 测试函数
def test_evacuateandrefill_protocol():
"""测试抽真空充气协议"""
debug_print("=== 抽真空充气协议测试 ===")
debug_print("测试完成")
debug_print("=== 抽真空充气协议增强中文版测试 ===")
debug_print("测试完成")
if __name__ == "__main__":
test_evacuateandrefill_protocol()
test_evacuateandrefill_protocol()

View File

@@ -0,0 +1,143 @@
# import numpy as np
# import networkx as nx
# def generate_evacuateandrefill_protocol(
# G: nx.DiGraph,
# vessel: str,
# gas: str,
# repeats: int = 1
# ) -> list[dict]:
# """
# 生成泵操作的动作序列。
# :param G: 有向图, 节点为容器和注射泵, 边为流体管道, A→B边的属性为管道接A端的阀门位置
# :param from_vessel: 容器A
# :param to_vessel: 容器B
# :param volume: 转移的体积
# :param flowrate: 最终注入容器B时的流速
# :param transfer_flowrate: 泵骨架中转移流速(若不指定,默认与注入流速相同)
# :return: 泵操作的动作序列
# """
# # 生成电磁阀、真空泵、气源操作的动作序列
# vacuum_action_sequence = []
# nodes = G.nodes(data=True)
# # 找到和 vessel 相连的电磁阀和真空泵、气源
# vacuum_backbone = {"vessel": vessel}
# for neighbor in G.neighbors(vessel):
# if nodes[neighbor]["class"].startswith("solenoid_valve"):
# for neighbor2 in G.neighbors(neighbor):
# if neighbor2 == vessel:
# continue
# if nodes[neighbor2]["class"].startswith("vacuum_pump"):
# vacuum_backbone.update({"vacuum_valve": neighbor, "pump": neighbor2})
# break
# elif nodes[neighbor2]["class"].startswith("gas_source"):
# vacuum_backbone.update({"gas_valve": neighbor, "gas": neighbor2})
# break
# # 判断是否设备齐全
# if len(vacuum_backbone) < 5:
# print(f"\n\n\n{vacuum_backbone}\n\n\n")
# raise ValueError("Not all devices are connected to the vessel.")
# # 生成操作的动作序列
# for i in range(repeats):
# # 打开真空泵阀门、关闭气源阀门
# vacuum_action_sequence.append([
# {
# "device_id": vacuum_backbone["vacuum_valve"],
# "action_name": "set_valve_position",
# "action_kwargs": {
# "command": "OPEN"
# }
# },
# {
# "device_id": vacuum_backbone["gas_valve"],
# "action_name": "set_valve_position",
# "action_kwargs": {
# "command": "CLOSED"
# }
# }
# ])
# # 打开真空泵、关闭气源
# vacuum_action_sequence.append([
# {
# "device_id": vacuum_backbone["pump"],
# "action_name": "set_status",
# "action_kwargs": {
# "string": "ON"
# }
# },
# {
# "device_id": vacuum_backbone["gas"],
# "action_name": "set_status",
# "action_kwargs": {
# "string": "OFF"
# }
# }
# ])
# vacuum_action_sequence.append({"action_name": "wait", "action_kwargs": {"time": 60}})
# # 关闭真空泵阀门、打开气源阀门
# vacuum_action_sequence.append([
# {
# "device_id": vacuum_backbone["vacuum_valve"],
# "action_name": "set_valve_position",
# "action_kwargs": {
# "command": "CLOSED"
# }
# },
# {
# "device_id": vacuum_backbone["gas_valve"],
# "action_name": "set_valve_position",
# "action_kwargs": {
# "command": "OPEN"
# }
# }
# ])
# # 关闭真空泵、打开气源
# vacuum_action_sequence.append([
# {
# "device_id": vacuum_backbone["pump"],
# "action_name": "set_status",
# "action_kwargs": {
# "string": "OFF"
# }
# },
# {
# "device_id": vacuum_backbone["gas"],
# "action_name": "set_status",
# "action_kwargs": {
# "string": "ON"
# }
# }
# ])
# vacuum_action_sequence.append({"action_name": "wait", "action_kwargs": {"time": 60}})
# # 关闭气源
# vacuum_action_sequence.append(
# {
# "device_id": vacuum_backbone["gas"],
# "action_name": "set_status",
# "action_kwargs": {
# "string": "OFF"
# }
# }
# )
# # 关闭阀门
# vacuum_action_sequence.append(
# {
# "device_id": vacuum_backbone["gas_valve"],
# "action_name": "set_valve_position",
# "action_kwargs": {
# "command": "CLOSED"
# }
# }
# )
# return vacuum_action_sequence

View File

@@ -4,99 +4,128 @@ import logging
import re
from .utils.vessel_parser import get_vessel
from .utils.unit_parser import parse_time_input
from .utils.logger_util import debug_print
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[EVAPORATE] {message}")
def find_rotavap_device(G: nx.DiGraph, vessel: str = None) -> Optional[str]:
"""
在组态图中查找旋转蒸发仪设备
Args:
G: 设备图
vessel: 指定的设备名称(可选)
Returns:
str: 找到的旋转蒸发仪设备ID如果没找到返回None
"""
debug_print("🔍 开始查找旋转蒸发仪设备... 🌪️")
# 如果指定了vessel先检查是否存在且是旋转蒸发仪
if vessel:
debug_print(f"🎯 检查指定设备: {vessel} 🔧")
if vessel in G.nodes():
node_data = G.nodes[vessel]
node_class = node_data.get('class', '')
node_type = node_data.get('type', '')
debug_print(f"📋 设备信息 {vessel}: class={node_class}, type={node_type}")
# 检查是否为旋转蒸发仪
if any(keyword in str(node_class).lower() for keyword in ['rotavap', 'rotary', 'evaporat']):
debug_print(f"找到指定的旋转蒸发仪: {vessel}")
debug_print(f"🎉 找到指定的旋转蒸发仪: {vessel}")
return vessel
elif node_type == 'device':
debug_print(f"指定设备存在,尝试直接使用: {vessel}")
debug_print(f"指定设备存在,尝试直接使用: {vessel} 🔧")
return vessel
else:
debug_print(f"❌ 指定的设备 {vessel} 不存在 😞")
# 在所有设备中查找旋转蒸发仪
debug_print("🔎 在所有设备中搜索旋转蒸发仪... 🕵️‍♀️")
rotavap_candidates = []
for node_id, node_data in G.nodes(data=True):
node_class = node_data.get('class', '')
node_type = node_data.get('type', '')
# 跳过非设备节点
if node_type != 'device':
continue
# 检查设备类型
if any(keyword in str(node_class).lower() for keyword in ['rotavap', 'rotary', 'evaporat']):
rotavap_candidates.append(node_id)
debug_print(f"🌟 找到旋转蒸发仪候选: {node_id} (class: {node_class}) 🌪️")
elif any(keyword in str(node_id).lower() for keyword in ['rotavap', 'rotary', 'evaporat']):
rotavap_candidates.append(node_id)
debug_print(f"🌟 找到旋转蒸发仪候选 (按名称): {node_id} 🌪️")
if rotavap_candidates:
selected = rotavap_candidates[0]
debug_print(f"选择旋转蒸发仪: {selected}")
selected = rotavap_candidates[0] # 选择第一个找到的
debug_print(f"🎯 选择旋转蒸发仪: {selected} 🏆")
return selected
debug_print("未找到旋转蒸发仪设备")
debug_print("😭 未找到旋转蒸发仪设备 💔")
return None
def find_connected_vessel(G: nx.DiGraph, rotavap_device: str) -> Optional[str]:
"""
查找与旋转蒸发仪连接的容器
Args:
G: 设备图
rotavap_device: 旋转蒸发仪设备ID
Returns:
str: 连接的容器ID如果没找到返回None
"""
debug_print(f"🔗 查找与 {rotavap_device} 连接的容器... 🥽")
# 查看旋转蒸发仪的子设备
rotavap_data = G.nodes[rotavap_device]
children = rotavap_data.get('children', [])
debug_print(f"👶 检查子设备: {children}")
for child_id in children:
if child_id in G.nodes():
child_data = G.nodes[child_id]
child_type = child_data.get('type', '')
if child_type == 'container':
debug_print(f"找到连接的容器: {child_id}")
debug_print(f"🎉 找到连接的容器: {child_id} 🥽✨")
return child_id
# 查看邻接的容器
debug_print("🤝 检查邻接设备...")
for neighbor in G.neighbors(rotavap_device):
neighbor_data = G.nodes[neighbor]
neighbor_type = neighbor_data.get('type', '')
if neighbor_type == 'container':
debug_print(f"找到邻接的容器: {neighbor}")
debug_print(f"🎉 找到邻接的容器: {neighbor} 🥽✨")
return neighbor
debug_print("未找到连接的容器")
debug_print("😞 未找到连接的容器 💔")
return None
def generate_evaporate_protocol(
G: nx.DiGraph,
vessel: dict,
vessel: dict, # 🔧 修改:从字符串改为字典类型
pressure: float = 0.1,
temp: float = 60.0,
time: Union[str, float] = "180",
time: Union[str, float] = "180", # 🔧 修改:支持字符串时间
stir_speed: float = 100.0,
solvent: str = "",
**kwargs
) -> List[Dict[str, Any]]:
"""
生成蒸发操作的协议序列 - 支持单位和体积运算
Args:
G: 设备图
vessel: 容器字典从XDL传入
@@ -106,16 +135,27 @@ def generate_evaporate_protocol(
stir_speed: 旋转速度 (RPM)默认100
solvent: 溶剂名称(用于参数优化)
**kwargs: 其他参数(兼容性)
Returns:
List[Dict[str, Any]]: 动作序列
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
debug_print(f"开始生成蒸发协议: vessel={vessel_id}, pressure={pressure}, temp={temp}, time={time}")
# 记录蒸发前的容器状态
debug_print("🌟" * 20)
debug_print("🌪️ 开始生成蒸发协议(支持单位和体积运算)✨")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 💨 pressure: {pressure} bar")
debug_print(f" 🌡️ temp: {temp}°C")
debug_print(f" ⏰ time: {time} (类型: {type(time)})")
debug_print(f" 🌪️ stir_speed: {stir_speed} RPM")
debug_print(f" 🧪 solvent: '{solvent}'")
debug_print("🌟" * 20)
# 🔧 新增:记录蒸发前的容器状态
debug_print("🔍 记录蒸发前容器状态...")
original_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -123,97 +163,168 @@ def generate_evaporate_protocol(
original_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
original_liquid_volume = current_volume
# 查找旋转蒸发仪设备
debug_print(f"📊 蒸发前液体体积: {original_liquid_volume:.2f}mL")
# === 步骤1: 查找旋转蒸发仪设备 ===
debug_print("📍 步骤1: 查找旋转蒸发仪设备... 🔍")
# 验证vessel参数
if not vessel_id:
debug_print("❌ vessel 参数不能为空! 😱")
raise ValueError("vessel 参数不能为空")
# 查找旋转蒸发仪设备
rotavap_device = find_rotavap_device(G, vessel_id)
if not rotavap_device:
debug_print("💥 未找到旋转蒸发仪设备! 😭")
raise ValueError(f"未找到旋转蒸发仪设备。请检查组态图中是否包含 class 包含 'rotavap''rotary''evaporat' 的设备")
# 确定目标容器
debug_print(f"🎉 成功找到旋转蒸发仪: {rotavap_device}")
# === 步骤2: 确定目标容器 ===
debug_print("📍 步骤2: 确定目标容器... 🥽")
target_vessel = vessel_id
# 如果vessel就是旋转蒸发仪设备查找连接的容器
if vessel_id == rotavap_device:
debug_print("🔄 vessel就是旋转蒸发仪查找连接的容器...")
connected_vessel = find_connected_vessel(G, rotavap_device)
if connected_vessel:
target_vessel = connected_vessel
debug_print(f"✅ 使用连接的容器: {target_vessel} 🥽✨")
else:
debug_print(f"⚠️ 未找到连接的容器,使用设备本身: {rotavap_device} 🔧")
target_vessel = rotavap_device
elif vessel_id in G.nodes() and G.nodes[vessel_id].get('type') == 'container':
debug_print(f"✅ 使用指定的容器: {vessel_id} 🥽✨")
target_vessel = vessel_id
else:
debug_print(f"⚠️ 容器 '{vessel_id}' 不存在或类型不正确,使用旋转蒸发仪设备: {rotavap_device} 🔧")
target_vessel = rotavap_device
# 单位解析处理
# === 🔧 新增步骤3单位解析处理 ===
debug_print("📍 步骤3: 单位解析处理... ⚡")
# 解析时间
final_time = parse_time_input(time)
debug_print(f"时间解析: {time} -> {final_time}s ({final_time/60:.1f}分钟)")
# 参数验证和修正
debug_print(f"🎯 时间解析完成: {time} {final_time}s ({final_time/60:.1f}分钟) ⏰✨")
# === 步骤4: 参数验证和修正 ===
debug_print("📍 步骤4: 参数验证和修正... 🔧")
# 修正参数范围
if pressure <= 0 or pressure > 1.0:
debug_print(f"⚠️ 真空度 {pressure} bar 超出范围,修正为 0.1 bar 💨")
pressure = 0.1
else:
debug_print(f"✅ 真空度 {pressure} bar 在正常范围内 💨")
if temp < 10.0 or temp > 200.0:
debug_print(f"⚠️ 温度 {temp}°C 超出范围,修正为 60°C 🌡️")
temp = 60.0
else:
debug_print(f"✅ 温度 {temp}°C 在正常范围内 🌡️")
if final_time <= 0:
debug_print(f"⚠️ 时间 {final_time}s 无效,修正为 180s (3分钟) ⏰")
final_time = 180.0
else:
debug_print(f"✅ 时间 {final_time}s ({final_time/60:.1f}分钟) 有效 ⏰")
if stir_speed < 10.0 or stir_speed > 300.0:
debug_print(f"⚠️ 旋转速度 {stir_speed} RPM 超出范围,修正为 100 RPM 🌪️")
stir_speed = 100.0
else:
debug_print(f"✅ 旋转速度 {stir_speed} RPM 在正常范围内 🌪️")
# 根据溶剂优化参数
if solvent:
debug_print(f"🧪 根据溶剂 '{solvent}' 优化参数... 🔬")
solvent_lower = solvent.lower()
if any(s in solvent_lower for s in ['water', 'aqueous', 'h2o']):
temp = max(temp, 80.0)
pressure = max(pressure, 0.2)
debug_print("💧 水系溶剂:提高温度和真空度 🌡️💨")
elif any(s in solvent_lower for s in ['ethanol', 'methanol', 'acetone']):
temp = min(temp, 50.0)
pressure = min(pressure, 0.05)
debug_print("🍺 易挥发溶剂:降低温度和真空度 🌡️💨")
elif any(s in solvent_lower for s in ['dmso', 'dmi', 'toluene']):
temp = max(temp, 100.0)
pressure = min(pressure, 0.01)
debug_print(f"最终参数: pressure={pressure}bar, temp={temp}°C, time={final_time}s, stir_speed={stir_speed}RPM")
# 蒸发体积计算
debug_print("🔥 高沸点溶剂:提高温度,降低真空度 🌡️💨")
else:
debug_print("🧪 通用溶剂,使用标准参数 ✨")
else:
debug_print("🤷‍♀️ 未指定溶剂,使用默认参数 ✨")
debug_print(f"🎯 最终参数: pressure={pressure} bar 💨, temp={temp}°C 🌡️, time={final_time}s ⏰, stir_speed={stir_speed} RPM 🌪️")
# === 🔧 新增步骤5蒸发体积计算 ===
debug_print("📍 步骤5: 蒸发体积计算... 📊")
# 根据温度、真空度、时间和溶剂类型估算蒸发量
evaporation_volume = 0.0
if original_liquid_volume > 0:
base_evap_rate = 0.5
# 基础蒸发速率mL/min
base_evap_rate = 0.5 # 基础速率
# 温度系数(高温蒸发更快)
temp_factor = 1.0 + (temp - 25.0) / 100.0
# 真空系数(真空度越高蒸发越快)
vacuum_factor = 1.0 + (1.0 - pressure) * 2.0
# 溶剂系数
solvent_factor = 1.0
if solvent:
solvent_lower = solvent.lower()
if any(s in solvent_lower for s in ['water', 'h2o']):
solvent_factor = 0.8
solvent_factor = 0.8 # 水蒸发较慢
elif any(s in solvent_lower for s in ['ethanol', 'methanol', 'acetone']):
solvent_factor = 1.5
solvent_factor = 1.5 # 易挥发溶剂蒸发快
elif any(s in solvent_lower for s in ['dmso', 'dmi']):
solvent_factor = 0.3
solvent_factor = 0.3 # 高沸点溶剂蒸发慢
# 计算总蒸发量
total_evap_rate = base_evap_rate * temp_factor * vacuum_factor * solvent_factor
evaporation_volume = min(
original_liquid_volume * 0.95,
total_evap_rate * (final_time / 60.0)
original_liquid_volume * 0.95, # 最多蒸发95%
total_evap_rate * (final_time / 60.0) # 时间相关的蒸发量
)
debug_print(f"预计蒸发量: {evaporation_volume:.2f}mL ({evaporation_volume/original_liquid_volume*100:.1f}%)")
# 生成动作序列
debug_print(f"📊 蒸发量计算:")
debug_print(f" - 基础蒸发速率: {base_evap_rate} mL/min")
debug_print(f" - 温度系数: {temp_factor:.2f} (基于 {temp}°C)")
debug_print(f" - 真空系数: {vacuum_factor:.2f} (基于 {pressure} bar)")
debug_print(f" - 溶剂系数: {solvent_factor:.2f} ({solvent or '通用'})")
debug_print(f" - 总蒸发速率: {total_evap_rate:.2f} mL/min")
debug_print(f" - 预计蒸发量: {evaporation_volume:.2f}mL ({evaporation_volume/original_liquid_volume*100:.1f}%)")
# === 步骤6: 生成动作序列 ===
debug_print("📍 步骤6: 生成动作序列... 🎬")
action_sequence = []
# 1. 等待稳定
debug_print(" 🔄 动作1: 添加初始等待稳定... ⏳")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 10}
})
debug_print(" ✅ 初始等待动作已添加 ⏳✨")
# 2. 执行蒸发
debug_print(f" 🌪️ 动作2: 执行蒸发操作...")
debug_print(f" 🔧 设备: {rotavap_device}")
debug_print(f" 🥽 容器: {target_vessel}")
debug_print(f" 💨 真空度: {pressure} bar")
debug_print(f" 🌡️ 温度: {temp}°C")
debug_print(f" ⏰ 时间: {final_time}s ({final_time/60:.1f}分钟)")
debug_print(f" 🌪️ 旋转速度: {stir_speed} RPM")
evaporate_action = {
"device_id": rotavap_device,
"action_name": "evaporate",
@@ -221,17 +332,20 @@ def generate_evaporate_protocol(
"vessel": {"id": target_vessel},
"pressure": float(pressure),
"temp": float(temp),
"time": float(final_time),
"time": float(final_time), # 🔧 强制转换为float类型
"stir_speed": float(stir_speed),
"solvent": str(solvent)
}
}
action_sequence.append(evaporate_action)
# 蒸发过程中的体积变化
debug_print(" ✅ 蒸发动作已添加 🌪️✨")
# 🔧 新增:蒸发过程中的体积变化
debug_print(" 🔧 更新容器体积 - 蒸发过程...")
if evaporation_volume > 0:
new_volume = max(0.0, original_liquid_volume - evaporation_volume)
# 更新vessel字典中的体积
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
@@ -243,14 +357,15 @@ def generate_evaporate_protocol(
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"]["liquid_volume"] = new_volume
# 🔧 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = new_volume
@@ -258,16 +373,18 @@ def generate_evaporate_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [new_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = new_volume
debug_print(f"蒸发体积变化: {original_liquid_volume:.2f}mL -> {new_volume:.2f}mL (-{evaporation_volume:.2f}mL)")
debug_print(f" 📊 蒸发体积变化: {original_liquid_volume:.2f}mL {new_volume:.2f}mL (-{evaporation_volume:.2f}mL)")
# 3. 蒸发后等待
debug_print(" 🔄 动作3: 添加蒸发后等待... ⏳")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 10}
})
# 最终状态
debug_print(" ✅ 蒸发后等待动作已添加 ⏳✨")
# 🔧 新增:蒸发完成后的状态报告
final_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -275,7 +392,19 @@ def generate_evaporate_protocol(
final_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
final_liquid_volume = current_volume
debug_print(f"蒸发协议生成完成: {len(action_sequence)} 个动作, 设备={rotavap_device}, 容器={target_vessel}")
# === 总结 ===
debug_print("🎊" * 20)
debug_print(f"🎉 蒸发协议生成完成! ✨")
debug_print(f"📊 总动作数: {len(action_sequence)} 个 📝")
debug_print(f"🌪️ 旋转蒸发仪: {rotavap_device} 🔧")
debug_print(f"🥽 目标容器: {target_vessel} 🧪")
debug_print(f"⚙️ 蒸发参数: {pressure} bar 💨, {temp}°C 🌡️, {final_time}s ⏰, {stir_speed} RPM 🌪️")
debug_print(f"⏱️ 预计总时间: {(final_time + 20)/60:.1f} 分钟 ⌛")
debug_print(f"📊 体积变化:")
debug_print(f" - 蒸发前: {original_liquid_volume:.2f}mL")
debug_print(f" - 蒸发后: {final_liquid_volume:.2f}mL")
debug_print(f" - 蒸发量: {evaporation_volume:.2f}mL ({evaporation_volume/max(original_liquid_volume, 0.01)*100:.1f}%)")
debug_print("🎊" * 20)
return action_sequence

View File

@@ -2,64 +2,87 @@ from typing import List, Dict, Any, Optional
import networkx as nx
import logging
from .utils.vessel_parser import get_vessel
from .utils.logger_util import debug_print
from .pump_protocol import generate_pump_protocol_with_rinsing
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[FILTER] {message}")
def find_filter_device(G: nx.DiGraph) -> str:
"""查找过滤器设备"""
debug_print("🔍 查找过滤器设备... 🌊")
# 查找过滤器设备
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if 'filter' in node_class.lower() or 'filter' in node.lower():
debug_print(f"找到过滤器设备: {node}")
debug_print(f"🎉 找到过滤器设备: {node}")
return node
# 如果没找到,寻找可能的过滤器名称
debug_print("🔎 在预定义名称中搜索过滤器... 📋")
possible_names = ["filter", "filter_1", "virtual_filter", "filtration_unit"]
for name in possible_names:
if name in G.nodes():
debug_print(f"找到过滤器设备: {name}")
debug_print(f"🎉 找到过滤器设备: {name}")
return name
debug_print("😭 未找到过滤器设备 💔")
raise ValueError("未找到过滤器设备")
def validate_vessel(G: nx.DiGraph, vessel: str, vessel_type: str = "容器") -> None:
"""验证容器是否存在"""
debug_print(f"🔍 验证{vessel_type}: '{vessel}' 🧪")
if not vessel:
debug_print(f"{vessel_type}不能为空! 😱")
raise ValueError(f"{vessel_type}不能为空")
if vessel not in G.nodes():
debug_print(f"{vessel_type} '{vessel}' 不存在于系统中! 😞")
raise ValueError(f"{vessel_type} '{vessel}' 不存在于系统中")
debug_print(f"{vessel_type} '{vessel}' 验证通过 🎯")
def generate_filter_protocol(
G: nx.DiGraph,
vessel: dict,
vessel: dict, # 🔧 修改:从字符串改为字典类型
filtrate_vessel: dict = {"id": "waste"},
**kwargs
) -> List[Dict[str, Any]]:
"""
生成过滤操作的协议序列 - 支持体积运算
Args:
G: 设备图
vessel: 过滤容器字典(必需)- 包含需要过滤的混合物
filtrate_vessel: 滤液容器名称(可选)- 如果提供则收集滤液
**kwargs: 其他参数(兼容性)
Returns:
List[Dict[str, Any]]: 过滤操作的动作序列
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
filtrate_vessel_id, filtrate_vessel_data = get_vessel(filtrate_vessel)
debug_print(f"开始生成过滤协议: vessel={vessel_id}, filtrate_vessel={filtrate_vessel_id}")
debug_print("🌊" * 20)
debug_print("🚀 开始生成过滤协议(支持体积运算)✨")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 🧪 filtrate_vessel: {filtrate_vessel}")
debug_print(f" ⚙️ 其他参数: {kwargs}")
debug_print("🌊" * 20)
action_sequence = []
# 记录过滤前的容器状态
# 🔧 新增:记录过滤前的容器状态
debug_print("🔍 记录过滤前容器状态...")
original_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -67,45 +90,79 @@ def generate_filter_protocol(
original_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
original_liquid_volume = current_volume
debug_print(f"📊 过滤前液体体积: {original_liquid_volume:.2f}mL")
# === 参数验证 ===
validate_vessel(G, vessel_id, "过滤容器")
debug_print("📍 步骤1: 参数验证... 🔧")
# 验证必需参数
debug_print(" 🔍 验证必需参数...")
validate_vessel(G, vessel_id, "过滤容器") # 🔧 使用 vessel_id
debug_print(" ✅ 必需参数验证完成 🎯")
# 验证可选参数
debug_print(" 🔍 验证可选参数...")
if filtrate_vessel:
validate_vessel(G, filtrate_vessel_id, "滤液容器")
debug_print(" 🌊 模式: 过滤并收集滤液 💧")
else:
debug_print(" 🧱 模式: 过滤并收集固体 🔬")
debug_print(" ✅ 可选参数验证完成 🎯")
# === 查找设备 ===
debug_print("📍 步骤2: 查找设备... 🔍")
try:
debug_print(" 🔎 搜索过滤器设备...")
filter_device = find_filter_device(G)
debug_print(f"使用过滤器设备: {filter_device}")
debug_print(f" 🎉 使用过滤器设备: {filter_device} 🌊✨")
except Exception as e:
debug_print(f" ❌ 设备查找失败: {str(e)} 😭")
raise ValueError(f"设备查找失败: {str(e)}")
# 过滤体积分配估算
solid_ratio = 0.1
liquid_ratio = 0.9
volume_loss_ratio = 0.05
# 🔧 新增:过滤效率和体积分配估算
debug_print("📍 步骤2.5: 过滤体积分配估算... 📊")
# 估算过滤分离比例(基于经验数据)
solid_ratio = 0.1 # 假设10%是固体(保留在过滤器上)
liquid_ratio = 0.9 # 假设90%是液体(通过过滤器)
volume_loss_ratio = 0.05 # 假设5%体积损失(残留在过滤器等)
# 从kwargs中获取过滤参数进行优化
if "solid_content" in kwargs:
try:
solid_ratio = float(kwargs["solid_content"])
liquid_ratio = 1.0 - solid_ratio
debug_print(f"📋 使用指定的固体含量: {solid_ratio*100:.1f}%")
except:
pass
debug_print("⚠️ 固体含量参数无效,使用默认值")
if original_liquid_volume > 0:
expected_filtrate_volume = original_liquid_volume * liquid_ratio * (1.0 - volume_loss_ratio)
expected_solid_volume = original_liquid_volume * solid_ratio
volume_loss = original_liquid_volume * volume_loss_ratio
debug_print(f"📊 过滤体积分配估算:")
debug_print(f" - 原始体积: {original_liquid_volume:.2f}mL")
debug_print(f" - 预计滤液体积: {expected_filtrate_volume:.2f}mL ({liquid_ratio*100:.1f}%)")
debug_print(f" - 预计固体体积: {expected_solid_volume:.2f}mL ({solid_ratio*100:.1f}%)")
debug_print(f" - 预计损失体积: {volume_loss:.2f}mL ({volume_loss_ratio*100:.1f}%)")
# === 转移到过滤器(如果需要)===
if vessel_id != filter_device:
debug_print("📍 步骤3: 转移到过滤器... 🚚")
if vessel_id != filter_device: # 🔧 使用 vessel_id
debug_print(f" 🚛 需要转移: {vessel_id}{filter_device} 📦")
try:
debug_print(" 🔄 开始执行转移操作...")
# 使用pump protocol转移液体到过滤器
transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel={"id": vessel_id},
from_vessel={"id": vessel_id}, # 🔧 使用 vessel_id
to_vessel={"id": filter_device},
volume=0.0,
volume=0.0, # 转移所有液体
amount="",
time=0.0,
viscous=False,
@@ -116,59 +173,88 @@ def generate_filter_protocol(
flowrate=2.0,
transfer_flowrate=2.0
)
if transfer_actions:
action_sequence.extend(transfer_actions)
debug_print(f"添加了 {len(transfer_actions)} 个转移动作")
# 更新容器体积
debug_print(f"添加了 {len(transfer_actions)} 个转移动作 🚚✨")
# 🔧 新增:转移后更新容器体积
debug_print(" 🔧 更新转移后的容器体积...")
# 原容器体积变为0所有液体已转移
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
vessel["data"]["liquid_volume"] = [0.0] if len(current_volume) > 0 else [0.0]
else:
vessel["data"]["liquid_volume"] = 0.0
# 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
G.nodes[vessel_id]['data']['liquid_volume'] = 0.0
debug_print(f" 📊 转移完成,{vessel_id} 体积更新为 0.0mL")
else:
debug_print(" ⚠️ 转移协议返回空序列 🤔")
except Exception as e:
debug_print(f"转移失败: {str(e)},继续执行")
debug_print(f"转移失败: {str(e)} 😞")
debug_print(" 🔄 继续执行,可能是直接连接的过滤器 🤞")
else:
debug_print(" ✅ 过滤容器就是过滤器,无需转移 🎯")
# === 执行过滤操作 ===
debug_print("📍 步骤4: 执行过滤操作... 🌊")
# 构建过滤动作参数
debug_print(" ⚙️ 构建过滤参数...")
filter_kwargs = {
"vessel": {"id": filter_device},
"filtrate_vessel": {"id": filtrate_vessel_id},
"vessel": {"id": filter_device}, # 过滤器设备
"filtrate_vessel": {"id": filtrate_vessel_id}, # 滤液容器(可能为空)
"stir": kwargs.get("stir", False),
"stir_speed": kwargs.get("stir_speed", 0.0),
"temp": kwargs.get("temp", 25.0),
"continue_heatchill": kwargs.get("continue_heatchill", False),
"volume": kwargs.get("volume", 0.0)
"volume": kwargs.get("volume", 0.0) # 0表示过滤所有
}
debug_print(f" 📋 过滤参数: {filter_kwargs}")
debug_print(" 🌊 开始过滤操作...")
# 过滤动作
filter_action = {
"device_id": filter_device,
"action_name": "filter",
"action_kwargs": filter_kwargs
}
action_sequence.append(filter_action)
debug_print(" ✅ 过滤动作已添加 🌊✨")
# 过滤后等待
debug_print(" ⏳ 添加过滤后等待...")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 10.0}
})
debug_print(" ✅ 过滤后等待动作已添加 ⏰✨")
# === 收集滤液(如果需要)===
debug_print("📍 步骤5: 收集滤液... 💧")
if filtrate_vessel_id and filtrate_vessel_id not in G.neighbors(filter_device):
debug_print(f" 🧪 收集滤液: {filter_device}{filtrate_vessel_id} 💧")
try:
debug_print(" 🔄 开始执行收集操作...")
# 使用pump protocol收集滤液
collect_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=filter_device,
to_vessel=filtrate_vessel,
volume=0.0,
volume=0.0, # 收集所有滤液
amount="",
time=0.0,
viscous=False,
@@ -179,15 +265,19 @@ def generate_filter_protocol(
flowrate=2.0,
transfer_flowrate=2.0
)
if collect_actions:
action_sequence.extend(collect_actions)
# 更新滤液容器体积
debug_print(f" ✅ 添加了 {len(collect_actions)} 个收集动作 🧪✨")
# 🔧 新增:收集滤液后的体积更新
debug_print(" 🔧 更新滤液容器体积...")
# 更新filtrate_vessel在图中的体积如果它是节点
if filtrate_vessel_id in G.nodes():
if 'data' not in G.nodes[filtrate_vessel_id]:
G.nodes[filtrate_vessel_id]['data'] = {}
current_filtrate_volume = G.nodes[filtrate_vessel_id]['data'].get('liquid_volume', 0.0)
if isinstance(current_filtrate_volume, list):
if len(current_filtrate_volume) > 0:
@@ -196,37 +286,58 @@ def generate_filter_protocol(
G.nodes[filtrate_vessel_id]['data']['liquid_volume'] = [expected_filtrate_volume]
else:
G.nodes[filtrate_vessel_id]['data']['liquid_volume'] = current_filtrate_volume + expected_filtrate_volume
debug_print(f" 📊 滤液容器 {filtrate_vessel_id} 体积增加 {expected_filtrate_volume:.2f}mL")
else:
debug_print(" ⚠️ 收集协议返回空序列 🤔")
except Exception as e:
debug_print(f"收集滤液失败: {str(e)},继续执行")
# 过滤完成后容器状态更新
debug_print(f"收集滤液失败: {str(e)} 😞")
debug_print(" 🔄 继续执行,可能滤液直接流入指定容器 🤞")
else:
debug_print(" 🧱 未指定滤液容器,固体保留在过滤器中 🔬")
# 🔧 新增:过滤完成后的容器状态更新
debug_print("📍 步骤5.5: 过滤完成后状态更新... 📊")
if vessel_id == filter_device:
# 如果过滤容器就是过滤器,需要更新其体积状态
if original_liquid_volume > 0:
if filtrate_vessel:
# 收集滤液模式:过滤器中主要保留固体
remaining_volume = expected_solid_volume
debug_print(f" 🧱 过滤器中保留固体: {remaining_volume:.2f}mL")
else:
# 保留固体模式:过滤器中保留所有物质
remaining_volume = original_liquid_volume * (1.0 - volume_loss_ratio)
debug_print(f" 🔬 过滤器中保留所有物质: {remaining_volume:.2f}mL")
# 更新vessel字典中的体积
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
vessel["data"]["liquid_volume"] = [remaining_volume] if len(current_volume) > 0 else [remaining_volume]
else:
vessel["data"]["liquid_volume"] = remaining_volume
# 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
G.nodes[vessel_id]['data']['liquid_volume'] = remaining_volume
debug_print(f" 📊 过滤器 {vessel_id} 体积更新为: {remaining_volume:.2f}mL")
# === 最终等待 ===
debug_print("📍 步骤6: 最终等待... ⏰")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 5.0}
})
# 最终状态
debug_print(" ✅ 最终等待动作已添加 ⏰✨")
# 🔧 新增:过滤完成后的状态报告
final_vessel_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -234,7 +345,22 @@ def generate_filter_protocol(
final_vessel_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
final_vessel_volume = current_volume
debug_print(f"过滤协议生成完成: {len(action_sequence)} 个动作, 容器={vessel_id}, 过滤器={filter_device}")
# === 总结 ===
debug_print("🎊" * 20)
debug_print(f"🎉 过滤协议生成完成! ✨")
debug_print(f"📊 总动作数: {len(action_sequence)} 个 📝")
debug_print(f"🥽 过滤容器: {vessel_id} 🧪")
debug_print(f"🌊 过滤器设备: {filter_device} 🔧")
debug_print(f"💧 滤液容器: {filtrate_vessel_id or '无(保留固体)'} 🧱")
debug_print(f"⏱️ 预计总时间: {(len(action_sequence) * 5):.0f} 秒 ⌛")
if original_liquid_volume > 0:
debug_print(f"📊 体积变化统计:")
debug_print(f" - 过滤前体积: {original_liquid_volume:.2f}mL")
debug_print(f" - 过滤后容器体积: {final_vessel_volume:.2f}mL")
if filtrate_vessel:
debug_print(f" - 预计滤液体积: {expected_filtrate_volume:.2f}mL")
debug_print(f" - 预计损失体积: {volume_loss:.2f}mL")
debug_print("🎊" * 20)
return action_sequence

View File

@@ -1,24 +1,118 @@
from typing import List, Dict, Any, Union
import networkx as nx
from .utils.vessel_parser import get_vessel, find_connected_heatchill
from .utils.unit_parser import parse_time_input, parse_temperature_input
from .utils.logger_util import debug_print
import logging
import re
from .utils.vessel_parser import get_vessel
from .utils.unit_parser import parse_time_input
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[HEATCHILL] {message}")
def parse_temp_input(temp_input: Union[str, float], default_temp: float = 25.0) -> float:
"""
解析温度输入(统一函数)
Args:
temp_input: 温度输入
default_temp: 默认温度
Returns:
float: 温度°C
"""
if not temp_input:
return default_temp
# 🔢 数值输入
if isinstance(temp_input, (int, float)):
result = float(temp_input)
debug_print(f"🌡️ 数值温度: {temp_input}{result}°C")
return result
# 📝 字符串输入
temp_str = str(temp_input).lower().strip()
debug_print(f"🔍 解析温度: '{temp_str}'")
# 🎯 特殊温度
special_temps = {
"room temperature": 25.0, "reflux": 78.0, "ice bath": 0.0,
"boiling": 100.0, "hot": 60.0, "warm": 40.0, "cold": 10.0
}
if temp_str in special_temps:
result = special_temps[temp_str]
debug_print(f"🎯 特殊温度: '{temp_str}'{result}°C")
return result
# 📐 正则解析(如 "256 °C"
temp_pattern = r'(\d+(?:\.\d+)?)\s*°?[cf]?'
match = re.search(temp_pattern, temp_str)
if match:
result = float(match.group(1))
debug_print(f"✅ 温度解析: '{temp_str}'{result}°C")
return result
debug_print(f"⚠️ 无法解析温度: '{temp_str}',使用默认值: {default_temp}°C")
return default_temp
def find_connected_heatchill(G: nx.DiGraph, vessel: str) -> str:
"""查找与指定容器相连的加热/冷却设备"""
debug_print(f"🔍 查找加热设备,目标容器: {vessel}")
# 🔧 查找所有加热设备
heatchill_nodes = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if 'heatchill' in node_class.lower() or 'virtual_heatchill' in node_class:
heatchill_nodes.append(node)
debug_print(f"🎉 找到加热设备: {node}")
# 🔗 检查连接
if vessel and heatchill_nodes:
for heatchill in heatchill_nodes:
if G.has_edge(heatchill, vessel) or G.has_edge(vessel, heatchill):
debug_print(f"✅ 加热设备 '{heatchill}' 与容器 '{vessel}' 相连")
return heatchill
# 🎯 使用第一个可用设备
if heatchill_nodes:
selected = heatchill_nodes[0]
debug_print(f"🔧 使用第一个加热设备: {selected}")
return selected
# 🆘 默认设备
debug_print("⚠️ 未找到加热设备,使用默认设备")
return "heatchill_1"
def validate_and_fix_params(temp: float, time: float, stir_speed: float) -> tuple:
"""验证和修正参数"""
# 🌡️ 温度范围验证
if temp < -50.0 or temp > 300.0:
debug_print(f"⚠️ 温度 {temp}°C 超出范围,修正为 25°C")
temp = 25.0
else:
debug_print(f"✅ 温度 {temp}°C 在正常范围内")
# ⏰ 时间验证
if time < 0:
debug_print(f"⚠️ 时间 {time}s 无效,修正为 300s")
time = 300.0
else:
debug_print(f"✅ 时间 {time}s ({time/60:.1f}分钟) 有效")
# 🌪️ 搅拌速度验证
if stir_speed < 0 or stir_speed > 1500.0:
debug_print(f"⚠️ 搅拌速度 {stir_speed} RPM 超出范围,修正为 300 RPM")
stir_speed = 300.0
else:
debug_print(f"✅ 搅拌速度 {stir_speed} RPM 在正常范围内")
return temp, time, stir_speed
def generate_heat_chill_protocol(
@@ -37,7 +131,7 @@ def generate_heat_chill_protocol(
) -> List[Dict[str, Any]]:
"""
生成加热/冷却操作的协议序列 - 支持vessel字典
Args:
G: 设备图
vessel: 容器字典从XDL传入
@@ -51,58 +145,82 @@ def generate_heat_chill_protocol(
stir_speed: 搅拌速度 (RPM)
purpose: 操作目的说明
**kwargs: 其他参数(兼容性)
Returns:
List[Dict[str, Any]]: 加热/冷却操作的动作序列
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
debug_print(f"开始生成加热冷却协议: vessel={vessel_id}, temp={temp}°C, "
f"time={time}, stir={stir} ({stir_speed} RPM), purpose='{purpose}'")
# 参数验证
if not vessel_id:
debug_print("🌡️" * 20)
debug_print("🚀 开始生成加热冷却协议支持vessel字典")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 🌡️ temp: {temp}°C")
debug_print(f" ⏰ time: {time}")
debug_print(f" 🎯 temp_spec: {temp_spec}")
debug_print(f" ⏱️ time_spec: {time_spec}")
debug_print(f" 🌪️ stir: {stir} ({stir_speed} RPM)")
debug_print(f" 🎭 purpose: '{purpose}'")
debug_print("🌡️" * 20)
# 📋 参数验证
debug_print("📍 步骤1: 参数验证... 🔧")
if not vessel_id: # 🔧 使用 vessel_id
debug_print("❌ vessel 参数不能为空! 😱")
raise ValueError("vessel 参数不能为空")
if vessel_id not in G.nodes():
if vessel_id not in G.nodes(): # 🔧 使用 vessel_id
debug_print(f"❌ 容器 '{vessel_id}' 不存在于系统中! 😞")
raise ValueError(f"容器 '{vessel_id}' 不存在于系统中")
# 参数解析
# 温度解析:优先使用 temp_spec
final_temp = parse_temperature_input(temp_spec, temp) if temp_spec else temp
debug_print("✅ 基础参数验证通过 🎯")
# 🔄 参数解析
debug_print("📍 步骤2: 参数解析... ⚡")
#温度解析:优先使用 temp_spec
final_temp = parse_temp_input(temp_spec, temp) if temp_spec else temp
# 时间解析:优先使用 time_spec
final_time = parse_time_input(time_spec) if time_spec else parse_time_input(time)
# 参数修正
final_temp, final_time, stir_speed = validate_and_fix_params(final_temp, final_time, stir_speed)
debug_print(f"最终参数: temp={final_temp}°C, time={final_time}s, stir_speed={stir_speed} RPM")
# 查找设备
debug_print(f"🎯 最终参数: temp={final_temp}°C, time={final_time}s, stir_speed={stir_speed} RPM")
# 🔍 查找设备
debug_print("📍 步骤3: 查找加热设备... 🔍")
try:
heatchill_id = find_connected_heatchill(G, vessel_id)
debug_print(f"使用加热设备: {heatchill_id}")
heatchill_id = find_connected_heatchill(G, vessel_id) # 🔧 使用 vessel_id
debug_print(f"🎉 使用加热设备: {heatchill_id}")
except Exception as e:
debug_print(f"❌ 设备查找失败: {str(e)} 😭")
raise ValueError(f"无法找到加热设备: {str(e)}")
# 生成动作
# 模拟运行时间优化
# 🚀 生成动作
debug_print("📍 步骤4: 生成加热动作... 🔥")
# 🕐 模拟运行时间优化
debug_print(" ⏱️ 检查模拟运行时间限制...")
original_time = final_time
simulation_time_limit = 100.0 # 模拟运行时间限制100秒
if final_time > simulation_time_limit:
final_time = simulation_time_limit
debug_print(f"模拟运行优化: {original_time}s → {final_time}s (限制为{simulation_time_limit}s)")
debug_print(f" 🎮 模拟运行优化: {original_time}s → {final_time}s (限制为{simulation_time_limit}s)")
debug_print(f" 📊 时间缩短: {original_time/60:.1f}分钟 → {final_time/60:.1f}分钟 🚀")
else:
debug_print(f" ✅ 时间在限制内: {final_time}s ({final_time/60:.1f}分钟) 保持不变 🎯")
action_sequence = []
heatchill_action = {
"device_id": heatchill_id,
"action_name": "heat_chill",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel},
"temp": float(final_temp),
"time": float(final_time),
"stir": bool(stir),
@@ -111,10 +229,21 @@ def generate_heat_chill_protocol(
}
}
action_sequence.append(heatchill_action)
debug_print(f"加热冷却协议生成完成: {len(action_sequence)} 个动作, "
f"vessel={vessel_id}, temp={final_temp}°C, time={final_time}s")
debug_print("✅ 加热动作已添加 🔥✨")
# 显示时间调整信息
if original_time != final_time:
debug_print(f" 🎭 模拟优化说明: 原计划 {original_time/60:.1f}分钟,实际模拟 {final_time/60:.1f}分钟 ⚡")
# 🎊 总结
debug_print("🎊" * 20)
debug_print(f"🎉 加热冷却协议生成完成! ✨")
debug_print(f"📊 总动作数: {len(action_sequence)}")
debug_print(f"🥽 加热容器: {vessel_id}")
debug_print(f"🌡️ 目标温度: {final_temp}°C")
debug_print(f"⏰ 加热时间: {final_time}s ({final_time/60:.1f}分钟)")
debug_print("🎊" * 20)
return action_sequence
def generate_heat_chill_to_temp_protocol(
@@ -126,7 +255,7 @@ def generate_heat_chill_to_temp_protocol(
) -> List[Dict[str, Any]]:
"""生成加热到指定温度的协议(简化版)"""
vessel_id, _ = get_vessel(vessel)
debug_print(f"生成加热到温度协议: {vessel_id}{temp}°C")
debug_print(f"🌡️ 生成加热到温度协议: {vessel_id}{temp}°C")
return generate_heat_chill_protocol(G, vessel, temp, time, **kwargs)
def generate_heat_chill_start_protocol(
@@ -137,19 +266,21 @@ def generate_heat_chill_start_protocol(
**kwargs
) -> List[Dict[str, Any]]:
"""生成开始加热操作的协议序列"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, _ = get_vessel(vessel)
debug_print(f"生成启动加热协议: vessel={vessel_id}, temp={temp}°C")
debug_print("🔥 开始生成启动加热协议")
debug_print(f"🥽 vessel: {vessel} (ID: {vessel_id}), 🌡️ temp: {temp}°C")
# 基础验证
if not vessel_id or vessel_id not in G.nodes():
if not vessel_id or vessel_id not in G.nodes(): # 🔧 使用 vessel_id
debug_print("❌ 容器验证失败!")
raise ValueError("vessel 参数无效")
# 查找设备
heatchill_id = find_connected_heatchill(G, vessel_id)
heatchill_id = find_connected_heatchill(G, vessel_id) # 🔧 使用 vessel_id
# 生成动作
action_sequence = [{
"device_id": heatchill_id,
@@ -160,8 +291,8 @@ def generate_heat_chill_start_protocol(
"vessel": {"id": vessel_id},
}
}]
debug_print(f"启动加热协议生成完成")
debug_print(f"启动加热协议生成完成 🎯")
return action_sequence
def generate_heat_chill_stop_protocol(
@@ -170,19 +301,21 @@ def generate_heat_chill_stop_protocol(
**kwargs
) -> List[Dict[str, Any]]:
"""生成停止加热操作的协议序列"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, _ = get_vessel(vessel)
debug_print(f"生成停止加热协议: vessel={vessel_id}")
debug_print("🛑 开始生成停止加热协议")
debug_print(f"🥽 vessel: {vessel} (ID: {vessel_id})")
# 基础验证
if not vessel_id or vessel_id not in G.nodes():
if not vessel_id or vessel_id not in G.nodes(): # 🔧 使用 vessel_id
debug_print("❌ 容器验证失败!")
raise ValueError("vessel 参数无效")
# 查找设备
heatchill_id = find_connected_heatchill(G, vessel_id)
heatchill_id = find_connected_heatchill(G, vessel_id) # 🔧 使用 vessel_id
# 生成动作
action_sequence = [{
"device_id": heatchill_id,
@@ -190,6 +323,6 @@ def generate_heat_chill_stop_protocol(
"action_kwargs": {
}
}]
debug_print(f"停止加热协议生成完成")
debug_print(f"停止加热协议生成完成 🎯")
return action_sequence

View File

@@ -1,50 +1,105 @@
import networkx as nx
from typing import List, Dict, Any, Optional
from .utils.vessel_parser import get_vessel
from .utils.logger_util import debug_print
from .utils.unit_parser import parse_temperature_input, parse_time_input
def parse_temperature(temp_str: str) -> float:
"""
解析温度字符串,支持多种格式
Args:
temp_str: 温度字符串(如 "45 °C", "45°C", "45"
Returns:
float: 温度值(摄氏度)
"""
try:
# 移除常见的温度单位和符号
temp_clean = temp_str.replace("°C", "").replace("°", "").replace("C", "").strip()
return float(temp_clean)
except ValueError:
print(f"HYDROGENATE: 无法解析温度 '{temp_str}',使用默认温度 25°C")
return 25.0
def parse_time(time_str: str) -> float:
"""
解析时间字符串,支持多种格式
Args:
time_str: 时间字符串(如 "2 h", "120 min", "7200 s"
Returns:
float: 时间值(秒)
"""
try:
time_clean = time_str.lower().strip()
# 处理小时
if "h" in time_clean:
hours = float(time_clean.replace("h", "").strip())
return hours * 3600.0
# 处理分钟
if "min" in time_clean:
minutes = float(time_clean.replace("min", "").strip())
return minutes * 60.0
# 处理秒
if "s" in time_clean:
seconds = float(time_clean.replace("s", "").strip())
return seconds
# 默认按小时处理
return float(time_clean) * 3600.0
except ValueError:
print(f"HYDROGENATE: 无法解析时间 '{time_str}',使用默认时间 2小时")
return 7200.0 # 2小时
def find_associated_solenoid_valve(G: nx.DiGraph, device_id: str) -> Optional[str]:
"""查找与指定设备相关联的电磁阀"""
solenoid_valves = [
node for node in G.nodes()
node for node in G.nodes()
if ('solenoid' in (G.nodes[node].get('class') or '').lower()
or 'solenoid_valve' in node)
]
# 通过网络连接查找直接相连的电磁阀
for solenoid in solenoid_valves:
if G.has_edge(device_id, solenoid) or G.has_edge(solenoid, device_id):
return solenoid
# 通过命名规则查找关联的电磁阀
device_type = ""
if 'gas' in device_id.lower():
device_type = "gas"
elif 'h2' in device_id.lower() or 'hydrogen' in device_id.lower():
device_type = "gas"
if device_type:
for solenoid in solenoid_valves:
if device_type in solenoid.lower():
return solenoid
return None
def find_connected_device(G: nx.DiGraph, vessel: str, device_type: str) -> str:
"""
查找与容器相连的指定类型设备
Args:
G: 网络图
vessel: 容器名称
device_type: 设备类型 ('heater', 'stirrer', 'gas_source')
Returns:
str: 设备ID如果没有则返回None
"""
print(f"HYDROGENATE: 正在查找与容器 '{vessel}' 相连的 {device_type}...")
# 根据设备类型定义搜索关键词
if device_type == 'heater':
keywords = ['heater', 'heat', 'heatchill']
@@ -57,38 +112,40 @@ def find_connected_device(G: nx.DiGraph, vessel: str, device_type: str) -> str:
device_class = 'virtual_gas_source'
else:
return None
# 查找设备节点
device_nodes = []
for node in G.nodes():
node_data = G.nodes[node]
node_name = node.lower()
node_class = node_data.get('class', '').lower()
# 通过名称匹配
if any(keyword in node_name for keyword in keywords):
device_nodes.append(node)
# 通过类型匹配
elif device_class in node_class:
device_nodes.append(node)
debug_print(f"找到的{device_type}节点: {device_nodes}")
print(f"HYDROGENATE: 找到的{device_type}节点: {device_nodes}")
# 检查是否有设备与目标容器相连
for device in device_nodes:
if G.has_edge(device, vessel) or G.has_edge(vessel, device):
debug_print(f"找到与容器 '{vessel}' 相连的{device_type}: {device}")
print(f"HYDROGENATE: 找到与容器 '{vessel}' 相连的{device_type}: {device}")
return device
# 如果没有直接连接,查找距离最近的设备
for device in device_nodes:
try:
path = nx.shortest_path(G, source=device, target=vessel)
if len(path) <= 3: # 最多2个中间节点
debug_print(f"找到距离较近的{device_type}: {device}")
print(f"HYDROGENATE: 找到距离较近的{device_type}: {device}")
return device
except nx.NetworkXNoPath:
continue
debug_print(f"未找到与容器 '{vessel}' 相连的{device_type}")
print(f"HYDROGENATE: 未找到与容器 '{vessel}' 相连的{device_type}")
return None
@@ -101,31 +158,36 @@ def generate_hydrogenate_protocol(
) -> List[Dict[str, Any]]:
"""
生成氢化反应协议序列 - 支持vessel字典
Args:
G: 有向图,节点为容器和设备
vessel: 反应容器字典从XDL传入
temp: 反应温度(如 "45 °C"
time: 反应时间(如 "2 h"
**kwargs: 其他可选参数,但不使用
Returns:
List[Dict[str, Any]]: 动作序列
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
action_sequence = []
# 解析参数
temperature = parse_temperature_input(temp)
reaction_time = parse_time_input(time)
debug_print(f"开始生成氢化反应协议: vessel={vessel_id}, "
f"temp={temperature}°C, time={reaction_time/3600:.1f}h")
# 记录氢化前的容器状态
temperature = parse_temperature(temp)
reaction_time = parse_time(time)
print("🧪" * 20)
print(f"HYDROGENATE: 开始生成氢化反应协议支持vessel字典")
print(f"📝 输入参数:")
print(f" 🥽 vessel: {vessel} (ID: {vessel_id})")
print(f" 🌡️ 反应温度: {temperature}°C")
print(f" ⏰ 反应时间: {reaction_time/3600:.1f} 小时")
print("🧪" * 20)
# 🔧 新增:记录氢化前的容器状态(可选,氢化反应通常不改变体积)
original_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -133,36 +195,47 @@ def generate_hydrogenate_protocol(
original_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
original_liquid_volume = current_volume
print(f"📊 氢化前液体体积: {original_liquid_volume:.2f}mL")
# 1. 验证目标容器存在
if vessel_id not in G.nodes():
debug_print(f"⚠️ 容器 '{vessel_id}' 不存在于系统中,跳过氢化反应")
print("📍 步骤1: 验证目标容器...")
if vessel_id not in G.nodes(): # 🔧 使用 vessel_id
print(f"⚠️ HYDROGENATE: 警告 - 容器 '{vessel_id}' 不存在于系统中,跳过氢化反应")
return action_sequence
print(f"✅ 容器 '{vessel_id}' 验证通过")
# 2. 查找相连的设备
heater_id = find_connected_device(G, vessel_id, 'heater')
stirrer_id = find_connected_device(G, vessel_id, 'stirrer')
gas_source_id = find_connected_device(G, vessel_id, 'gas_source')
debug_print(f"设备配置: heater={heater_id or '未找到'}, "
f"stirrer={stirrer_id or '未找到'}, gas={gas_source_id or '未找到'}")
print("📍 步骤2: 查找相连设备...")
heater_id = find_connected_device(G, vessel_id, 'heater') # 🔧 使用 vessel_id
stirrer_id = find_connected_device(G, vessel_id, 'stirrer') # 🔧 使用 vessel_id
gas_source_id = find_connected_device(G, vessel_id, 'gas_source') # 🔧 使用 vessel_id
print(f"🔧 设备配置:")
print(f" 🔥 加热器: {heater_id or '未找到'}")
print(f" 🌪️ 搅拌器: {stirrer_id or '未找到'}")
print(f" 💨 气源: {gas_source_id or '未找到'}")
# 3. 启动搅拌器
print("📍 步骤3: 启动搅拌器...")
if stirrer_id:
print(f"🌪️ 启动搅拌器 {stirrer_id}")
action_sequence.append({
"device_id": stirrer_id,
"action_name": "start_stir",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": vessel_id, # 🔧 使用 vessel_id
"stir_speed": 300.0,
"purpose": "氢化反应: 开始搅拌"
}
})
print("✅ 搅拌器启动动作已添加")
else:
debug_print(f"⚠️ 未找到搅拌器,继续执行")
print(f"⚠️ HYDROGENATE: 警告 - 未找到搅拌器,继续执行")
# 4. 启动气源(氢气)
print("📍 步骤4: 启动氢气源...")
if gas_source_id:
print(f"💨 启动气源 {gas_source_id} (氢气)")
action_sequence.append({
"device_id": gas_source_id,
"action_name": "set_status",
@@ -170,10 +243,11 @@ def generate_hydrogenate_protocol(
"string": "ON"
}
})
# 查找相关的电磁阀
gas_solenoid = find_associated_solenoid_valve(G, gas_source_id)
if gas_solenoid:
print(f"🚪 开启气源电磁阀 {gas_solenoid}")
action_sequence.append({
"device_id": gas_solenoid,
"action_name": "set_valve_position",
@@ -181,10 +255,12 @@ def generate_hydrogenate_protocol(
"command": "OPEN"
}
})
print("✅ 氢气源启动动作已添加")
else:
debug_print(f"⚠️ 未找到气源,继续执行")
print(f"⚠️ HYDROGENATE: 警告 - 未找到气源,继续执行")
# 5. 等待气体稳定
print("📍 步骤5: 等待气体环境稳定...")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
@@ -192,19 +268,22 @@ def generate_hydrogenate_protocol(
"description": "等待氢气环境稳定"
}
})
print("✅ 气体稳定等待动作已添加")
# 6. 启动加热器
print("📍 步骤6: 启动加热反应...")
if heater_id:
print(f"🔥 启动加热器 {heater_id}{temperature}°C")
action_sequence.append({
"device_id": heater_id,
"action_name": "heat_chill_start",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": vessel_id, # 🔧 使用 vessel_id
"temp": temperature,
"purpose": f"氢化反应: 加热到 {temperature}°C"
}
})
# 等待温度稳定
action_sequence.append({
"action_name": "wait",
@@ -213,38 +292,52 @@ def generate_hydrogenate_protocol(
"description": f"等待温度稳定到 {temperature}°C"
}
})
# 模拟运行时间优化
# 🕐 模拟运行时间优化
print(" ⏰ 检查模拟运行时间限制...")
original_reaction_time = reaction_time
simulation_time_limit = 60.0
simulation_time_limit = 60.0 # 模拟运行时间限制60秒
if reaction_time > simulation_time_limit:
reaction_time = simulation_time_limit
debug_print(f"模拟运行优化: {original_reaction_time}s → {reaction_time}s")
print(f" 🎮 模拟运行优化: {original_reaction_time}s → {reaction_time}s (限制为{simulation_time_limit}s)")
print(f" 📊 时间缩短: {original_reaction_time/3600:.2f}小时 → {reaction_time/60:.1f}分钟")
else:
print(f" ✅ 时间在限制内: {reaction_time}s ({reaction_time/60:.1f}分钟) 保持不变")
# 保持反应温度
action_sequence.append({
"device_id": heater_id,
"action_name": "heat_chill",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": vessel_id, # 🔧 使用 vessel_id
"temp": temperature,
"time": reaction_time,
"purpose": f"氢化反应: 保持 {temperature}°C反应 {reaction_time/60:.1f}分钟" + (f" (模拟时间)" if original_reaction_time != reaction_time else "")
}
})
# 显示时间调整信息
if original_reaction_time != reaction_time:
print(f" 🎭 模拟优化说明: 原计划 {original_reaction_time/3600:.2f}小时,实际模拟 {reaction_time/60:.1f}分钟")
print("✅ 加热反应动作已添加")
else:
debug_print(f"⚠️ 未找到加热器,使用室温反应")
# 室温反应也需要时间优化
print(f"⚠️ HYDROGENATE: 警告 - 未找到加热器,使用室温反应")
# 🕐 室温反应也需要时间优化
print(" ⏰ 检查室温反应模拟时间限制...")
original_reaction_time = reaction_time
simulation_time_limit = 60.0
simulation_time_limit = 60.0 # 模拟运行时间限制60秒
if reaction_time > simulation_time_limit:
reaction_time = simulation_time_limit
debug_print(f"室温反应时间优化: {original_reaction_time}s → {reaction_time}s")
print(f" 🎮 室温反应时间优化: {original_reaction_time}s → {reaction_time}s")
print(f" 📊 时间缩短: {original_reaction_time/3600:.2f}小时 → {reaction_time/60:.1f}分钟")
else:
print(f" ✅ 室温反应时间在限制内: {reaction_time}s 保持不变")
# 室温反应,只等待时间
action_sequence.append({
"action_name": "wait",
@@ -253,19 +346,28 @@ def generate_hydrogenate_protocol(
"description": f"室温氢化反应 {reaction_time/60:.1f}分钟" + (f" (模拟时间)" if original_reaction_time != reaction_time else "")
}
})
# 显示时间调整信息
if original_reaction_time != reaction_time:
print(f" 🎭 室温反应优化说明: 原计划 {original_reaction_time/3600:.2f}小时,实际模拟 {reaction_time/60:.1f}分钟")
print("✅ 室温反应等待动作已添加")
# 7. 停止加热
print("📍 步骤7: 停止加热...")
if heater_id:
action_sequence.append({
"device_id": heater_id,
"action_name": "heat_chill_stop",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": vessel_id, # 🔧 使用 vessel_id
"purpose": "氢化反应完成,停止加热"
}
})
print("✅ 停止加热动作已添加")
# 8. 等待冷却
print("📍 步骤8: 等待冷却...")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
@@ -273,12 +375,15 @@ def generate_hydrogenate_protocol(
"description": "等待反应混合物冷却"
}
})
print("✅ 冷却等待动作已添加")
# 9. 停止气源
print("📍 步骤9: 停止氢气源...")
if gas_source_id:
# 先关闭电磁阀
gas_solenoid = find_associated_solenoid_valve(G, gas_source_id)
if gas_solenoid:
print(f"🚪 关闭气源电磁阀 {gas_solenoid}")
action_sequence.append({
"device_id": gas_solenoid,
"action_name": "set_valve_position",
@@ -286,7 +391,7 @@ def generate_hydrogenate_protocol(
"command": "CLOSED"
}
})
# 再关闭气源
action_sequence.append({
"device_id": gas_source_id,
@@ -295,24 +400,59 @@ def generate_hydrogenate_protocol(
"string": "OFF"
}
})
print("✅ 氢气源停止动作已添加")
# 10. 停止搅拌
print("📍 步骤10: 停止搅拌...")
if stirrer_id:
action_sequence.append({
"device_id": stirrer_id,
"action_name": "stop_stir",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": vessel_id, # 🔧 使用 vessel_id
"purpose": "氢化反应完成,停止搅拌"
}
})
# 氢化完成后的状态(氢化反应通常不改变体积)
final_liquid_volume = original_liquid_volume
print("✅ 停止搅拌动作已添加")
# 🔧 新增:氢化完成后的状态(氢化反应通常不改变体积)
final_liquid_volume = original_liquid_volume # 氢化反应体积基本不变
# 总结
debug_print(f"氢化反应协议生成完成: {len(action_sequence)} 个动作, "
f"vessel={vessel_id}, temp={temperature}°C, time={reaction_time/60:.1f}min, "
f"volume={original_liquid_volume:.2f}{final_liquid_volume:.2f}mL")
print("🎊" * 20)
print(f"🎉 氢化反应协议生成完成! ✨")
print(f"📊 总动作数: {len(action_sequence)}")
print(f"🥽 反应容器: {vessel_id}")
print(f"🌡️ 反应温度: {temperature}°C")
print(f"⏰ 反应时间: {reaction_time/60:.1f}分钟")
print(f"⏱️ 预计总时间: {(reaction_time + 450)/3600:.1f} 小时")
print(f"📊 体积状态:")
print(f" - 反应前体积: {original_liquid_volume:.2f}mL")
print(f" - 反应后体积: {final_liquid_volume:.2f}mL (氢化反应体积基本不变)")
print("🎊" * 20)
return action_sequence
# 测试函数
def test_hydrogenate_protocol():
"""测试氢化反应协议"""
print("🧪 === HYDROGENATE PROTOCOL 测试 === ✨")
# 测试温度解析
test_temps = ["45 °C", "45°C", "45", "25 C", "invalid"]
for temp in test_temps:
parsed = parse_temperature(temp)
print(f"温度 '{temp}' -> {parsed}°C")
# 测试时间解析
test_times = ["2 h", "120 min", "7200 s", "2", "invalid"]
for time in test_times:
parsed = parse_time(time)
print(f"时间 '{time}' -> {parsed/3600:.1f} 小时")
print("✅ 测试完成 🎉")
if __name__ == "__main__":
test_hydrogenate_protocol()

View File

@@ -2,18 +2,99 @@ import traceback
import numpy as np
import networkx as nx
import asyncio
import time as time_module # 重命名time模块
import time as time_module # 🔧 重命名time模块
from typing import List, Dict, Any
import logging
import sys
from .utils.logger_util import debug_print
from .utils.vessel_parser import get_vessel
from .utils.resource_helper import get_resource_liquid_volume
from unilabos.compile.utils.vessel_parser import get_vessel
logger = logging.getLogger(__name__)
def debug_print(message):
"""强制输出调试信息"""
output = f"[TRANSFER] {message}"
logger.info(output)
def get_vessel_liquid_volume(G: nx.DiGraph, vessel: str) -> float:
"""
从容器节点的数据中获取液体体积
"""
debug_print(f"🔍 开始读取容器 '{vessel}' 的液体体积...")
if vessel not in G.nodes():
logger.error(f"❌ 容器 '{vessel}' 不存在于系统图中")
debug_print(f" - 系统中的容器: {list(G.nodes())}")
return 0.0
vessel_data = G.nodes[vessel].get('data', {})
debug_print(f"📋 容器 '{vessel}' 的数据结构: {vessel_data}")
total_volume = 0.0
# 方法1检查 'liquid' 字段(列表格式)
debug_print("🔍 方法1: 检查 'liquid' 字段...")
if 'liquid' in vessel_data:
liquids = vessel_data['liquid']
debug_print(f" - liquid 字段类型: {type(liquids)}")
debug_print(f" - liquid 字段内容: {liquids}")
if isinstance(liquids, list):
debug_print(f" - liquid 是列表,包含 {len(liquids)} 个元素")
for i, liquid in enumerate(liquids):
debug_print(f" 液体 {i + 1}: {liquid}")
if isinstance(liquid, dict):
volume_keys = ['liquid_volume', 'volume', 'amount', 'quantity']
for key in volume_keys:
if key in liquid:
try:
vol = float(liquid[key])
total_volume += vol
debug_print(f" ✅ 从 '{key}' 读取体积: {vol}mL")
break
except (ValueError, TypeError) as e:
logger.warning(f" ⚠️ 无法转换 '{key}': {liquid[key]} -> {str(e)}")
continue
else:
debug_print(f" - liquid 不是列表: {type(liquids)}")
else:
debug_print(" - 没有 'liquid' 字段")
# 方法2检查直接的体积字段
debug_print("🔍 方法2: 检查直接体积字段...")
volume_keys = ['total_volume', 'volume', 'liquid_volume', 'amount', 'current_volume']
for key in volume_keys:
if key in vessel_data:
try:
vol = float(vessel_data[key])
total_volume = max(total_volume, vol) # 取最大值
debug_print(f" ✅ 从容器数据 '{key}' 读取体积: {vol}mL")
break
except (ValueError, TypeError) as e:
logger.warning(f" ⚠️ 无法转换 '{key}': {vessel_data[key]} -> {str(e)}")
continue
# 方法3检查 'state' 或 'status' 字段
debug_print("🔍 方法3: 检查 'state' 字段...")
if 'state' in vessel_data and isinstance(vessel_data['state'], dict):
state = vessel_data['state']
debug_print(f" - state 字段内容: {state}")
if 'volume' in state:
try:
vol = float(state['volume'])
total_volume = max(total_volume, vol)
debug_print(f" ✅ 从容器状态读取体积: {vol}mL")
except (ValueError, TypeError) as e:
logger.warning(f" ⚠️ 无法转换 state.volume: {state['volume']} -> {str(e)}")
else:
debug_print(" - 没有 'state' 字段或不是字典")
debug_print(f"📊 容器 '{vessel}' 最终检测体积: {total_volume}mL")
return total_volume
def is_integrated_pump(node_class: str, node_name: str = "") -> bool:
"""
判断是否为泵阀一体设备
@@ -41,77 +122,108 @@ def is_integrated_pump(node_class: str, node_name: str = "") -> bool:
def find_connected_pump(G, valve_node):
"""
查找与阀门相连的泵节点
区分电磁阀和多通阀,电磁阀不参与泵查找
查找与阀门相连的泵节点 - 修复版本
🔧 修复:区分电磁阀和多通阀,电磁阀不参与泵查找
"""
# 检查节点类型,电磁阀不应该查找泵
debug_print(f"🔍 查找与阀门 {valve_node} 相连的泵...")
# 🔧 关键修复:检查节点类型,电磁阀不应该查找泵
node_data = G.nodes.get(valve_node, {})
node_class = node_data.get("class", "") or ""
debug_print(f" - 阀门类型: {node_class}")
# 如果是电磁阀,不应该查找泵(电磁阀只是开关)
if ("solenoid" in node_class.lower() or "solenoid_valve" in valve_node.lower()):
debug_print(f" ⚠️ {valve_node} 是电磁阀,不应该查找泵节点")
raise ValueError(f"电磁阀 {valve_node} 不应该参与泵查找逻辑")
# 只有多通阀等复杂阀门才需要查找连接的泵
if ("multiway" in node_class.lower() or "valve" in node_class.lower()):
debug_print(f" - {valve_node} 是多通阀,查找连接的泵...")
# 方法1直接相邻的泵
for neighbor in G.neighbors(valve_node):
neighbor_class = G.nodes[neighbor].get("class", "") or ""
# 排除非 电磁阀 和 泵 的邻居
debug_print(f" - 检查邻居 {neighbor}, class: {neighbor_class}")
if "pump" in neighbor_class.lower():
debug_print(f" ✅ 找到直接相连的泵: {neighbor}")
return neighbor
# 方法2通过路径查找泵最多2跳
pump_nodes = [
node_id for node_id in G.nodes()
if "pump" in (G.nodes[node_id].get("class", "") or "").lower()
]
debug_print(f" - 未找到直接相连的泵,尝试路径查找...")
# 获取所有泵节点
pump_nodes = []
for node_id in G.nodes():
node_class = G.nodes[node_id].get("class", "") or ""
if "pump" in node_class.lower():
pump_nodes.append(node_id)
debug_print(f" - 系统中的泵节点: {pump_nodes}")
# 查找到泵的最短路径
for pump_node in pump_nodes:
try:
if nx.has_path(G, valve_node, pump_node):
path = nx.shortest_path(G, valve_node, pump_node)
if len(path) - 1 <= 2: # 最多允许2跳
path_length = len(path) - 1
debug_print(f" - 到泵 {pump_node} 的路径: {path}, 距离: {path_length}")
if path_length <= 2: # 最多允许2跳
debug_print(f" ✅ 通过路径找到泵: {pump_node}")
return pump_node
except nx.NetworkXNoPath:
continue
# 最终失败
debug_print(f" ❌ 完全找不到泵节点")
raise ValueError(f"未找到与阀 {valve_node} 相连的泵节点")
def build_pump_valve_maps(G, pump_backbone):
"""
构建泵-阀门映射
过滤掉电磁阀,只处理需要泵的多通阀
构建泵-阀门映射 - 修复版本
🔧 修复:过滤掉电磁阀,只处理需要泵的多通阀
"""
pumps_from_node = {}
valve_from_node = {}
# 过滤掉电磁阀
debug_print(f"🔧 构建泵-阀门映射,原始骨架: {pump_backbone}")
# 🔧 关键修复:过滤掉电磁阀
filtered_backbone = []
for node in pump_backbone:
node_data = G.nodes.get(node, {})
node_class = node_data.get("class", "") or ""
# 跳过电磁阀
if ("solenoid" in node_class.lower() or "solenoid_valve" in node.lower()):
debug_print(f" - 跳过电磁阀: {node}")
continue
filtered_backbone.append(node)
debug_print(f"🔧 过滤后的骨架: {filtered_backbone}")
for node in filtered_backbone:
node_data = G.nodes.get(node, {})
node_class = node_data.get("class", "") or ""
if is_integrated_pump(node_class, node):
pumps_from_node[node] = node
valve_from_node[node] = node
debug_print(f" - 集成泵-阀: {node}")
else:
try:
pump_node = find_connected_pump(G, node)
pumps_from_node[node] = pump_node
valve_from_node[node] = node
except ValueError:
debug_print(f" - 阀门 {node} -> 泵 {pump_node}")
except ValueError as e:
debug_print(f" - 跳过节点 {node}: {str(e)}")
continue
debug_print(f"泵-阀映射: pumps={pumps_from_node}, valves={valve_from_node}")
debug_print(f"🔧 最终映射: pumps={pumps_from_node}, valves={valve_from_node}")
return pumps_from_node, valve_from_node
@@ -124,8 +236,8 @@ def generate_pump_protocol(
transfer_flowrate: float = 0.5,
) -> List[Dict[str, Any]]:
"""
生成泵操作的动作序列
正确处理包含电磁阀的路径
生成泵操作的动作序列 - 修复版本
🔧 修复:正确处理包含电磁阀的路径
"""
pump_action_sequence = []
nodes = G.nodes(data=True)
@@ -144,6 +256,7 @@ def generate_pump_protocol(
logger.warning(f"transfer_flowrate <= 0使用默认值 {transfer_flowrate}mL/s")
# 验证容器存在
debug_print(f"🔍 验证源容器 '{from_vessel_id}' 和目标容器 '{to_vessel_id}' 是否存在...")
if from_vessel_id not in G.nodes():
logger.error(f"源容器 '{from_vessel_id}' 不存在")
return pump_action_sequence
@@ -159,24 +272,28 @@ def generate_pump_protocol(
logger.error(f"无法找到从 '{from_vessel_id}''{to_vessel_id}' 的路径")
return pump_action_sequence
# 正确构建泵骨架,排除容器和电磁阀
# 🔧 关键修复:正确构建泵骨架,排除容器和电磁阀
pump_backbone = []
for node in shortest_path:
# 跳过起始和结束容器
if node == from_vessel_id or node == to_vessel_id:
continue
# 跳过电磁阀(电磁阀不参与泵操作)
node_data = G.nodes.get(node, {})
node_class = node_data.get("class", "") or ""
if ("solenoid" in node_class.lower() or "solenoid_valve" in node.lower()):
debug_print(f"PUMP_TRANSFER: 跳过电磁阀 {node}")
continue
# 只包含多通阀和泵
if ("multiway" in node_class.lower() or "valve" in node_class.lower() or "pump" in node_class.lower()):
pump_backbone.append(node)
debug_print(f"PUMP_TRANSFER: 泵骨架: {pump_backbone}")
debug_print(f"PUMP_TRANSFER: 过滤后的泵骨架: {pump_backbone}")
if not pump_backbone:
debug_print("PUMP_TRANSFER: 没有泵骨架节点")
debug_print("PUMP_TRANSFER: 没有泵骨架节点,可能是直接容器连接或只有电磁阀")
return pump_action_sequence
if transfer_flowrate == 0:
@@ -192,7 +309,7 @@ def generate_pump_protocol(
debug_print("PUMP_TRANSFER: 没有可用的泵映射")
return pump_action_sequence
# 安全地获取最小转移体积
# 🔧 修复:安全地获取最小转移体积
try:
min_transfer_volumes = []
for node in pump_backbone:
@@ -222,19 +339,19 @@ def generate_pump_protocol(
volume_left = volume
debug_print(f"PUMP_TRANSFER: 需要 {repeats} 次转移,单次最大体积 {min_transfer_volume} mL")
# 只在开头打印总体概览
# 🆕 只在开头打印总体概览
if repeats > 1:
debug_print(f"分批转移: 总体积 {volume:.2f}mL, {repeats}, 单次最大 {min_transfer_volume} mL")
logger.info(f"分批转移: 总体积 {volume:.2f}mL, {repeats} 次转移")
debug_print(f"🔄 分批转移概览: 总体积 {volume:.2f}mL,需要 {repeats}转移")
logger.info(f"🔄 分批转移概览: 总体积 {volume:.2f}mL,需要 {repeats} 次转移")
# 创建一个自定义的wait动作用于在执行时打印日志
# 🔧 创建一个自定义的wait动作用于在执行时打印日志
def create_progress_log_action(message: str) -> Dict[str, Any]:
"""创建一个特殊的等待动作,在执行时打印进度日志"""
return {
"action_name": "wait",
"action_kwargs": {
"time": 0.1,
"progress_message": message
"time": 0.1, # 很短的等待时间
"progress_message": message # 自定义字段,用于进度日志
}
}
@@ -242,12 +359,12 @@ def generate_pump_protocol(
for i in range(repeats):
current_volume = min(volume_left, min_transfer_volume)
# 🆕 在每次循环开始时添加进度日志
if repeats > 1:
pump_action_sequence.append(create_progress_log_action(
f"{i + 1}/{repeats} 次转移: {current_volume:.2f}mL ({from_vessel_id} -> {to_vessel_id})"
))
start_message = f"🚀 准备开始第 {i + 1}/{repeats} 次转移: {current_volume:.2f}mL ({from_vessel_id}{to_vessel_id}) 🚰"
pump_action_sequence.append(create_progress_log_action(start_message))
# 安全地获取边数据
# 🔧 修复:安全地获取边数据
def get_safe_edge_data(node_a, node_b, key):
try:
edge_data = G.get_edge_data(node_a, node_b)
@@ -350,13 +467,13 @@ def generate_pump_protocol(
])
pump_action_sequence.append({"action_name": "wait", "action_kwargs": {"time": 3}})
# 在每次循环结束时添加完成日志
# 🆕 在每次循环结束时添加完成日志
if repeats > 1:
remaining_volume = volume_left - current_volume
if remaining_volume > 0:
end_message = f"{i + 1}/{repeats} 次完成, 剩余 {remaining_volume:.2f}mL"
end_message = f"{i + 1}/{repeats}转移完成! 剩余 {remaining_volume:.2f}mL 待转移 ⏳"
else:
end_message = f"{i + 1}/{repeats} 次完成, 全部 {volume:.2f}mL 转移完毕"
end_message = f"🎉 {i + 1}/{repeats}转移完成! 全部 {volume:.2f}mL 转移完毕"
pump_action_sequence.append(create_progress_log_action(end_message))
@@ -398,205 +515,300 @@ def generate_pump_protocol_with_rinsing(
to_vessel_id, _ = get_vessel(to_vessel)
with generate_pump_protocol_with_rinsing._lock:
debug_print(f"PUMP_TRANSFER: {from_vessel_id} -> {to_vessel_id}, volume={volume}, flowrate={flowrate}")
debug_print("=" * 60)
debug_print(f"PUMP_TRANSFER: 🚀 开始生成协议 (同步版本)")
debug_print(f" 📍 路径: {from_vessel_id} -> {to_vessel_id}")
debug_print(f" 🕐 时间戳: {time_module.time()}")
debug_print(f" 🔒 获得执行锁")
debug_print("=" * 60)
# 短暂延迟,避免快速重复调用
time_module.sleep(0.01)
debug_print("🔍 步骤1: 开始体积处理...")
# 1. 处理体积参数
final_volume = volume
debug_print(f"📋 初始设置: final_volume = {final_volume}")
# 如果volume为0从容器读取实际体积
# 🔧 修复:如果volume为0ROS2传入的空值,从容器读取实际体积
if volume == 0.0:
debug_print("🎯 检测到 volume=0.0,开始自动体积检测...")
actual_volume = get_resource_liquid_volume(G.nodes.get(from_vessel_id, {}))
# 直接从源容器读取实际体积
actual_volume = get_vessel_liquid_volume(G, from_vessel_id)
debug_print(f"📖 从容器 '{from_vessel_id}' 读取到体积: {actual_volume}mL")
if actual_volume > 0:
final_volume = actual_volume
debug_print(f"✅ 成功设置体积为: {final_volume}mL")
else:
final_volume = 10.0
logger.warning(f"无法从容器读取体积,使用默认值: {final_volume}mL")
final_volume = 10.0 # 如果读取失败,使用默认值
logger.warning(f"⚠️ 无法从容器读取体积,使用默认值: {final_volume}mL")
else:
debug_print(f"📌 体积非零,直接使用: {final_volume}mL")
# 处理 amount 参数
if amount and amount.strip():
debug_print(f"🔍 检测到 amount 参数: '{amount}',开始解析...")
parsed_volume = _parse_amount_to_volume(amount)
debug_print(f"📖 从 amount 解析得到体积: {parsed_volume}mL")
if parsed_volume > 0:
final_volume = parsed_volume
debug_print(f"✅ 使用从 amount 解析的体积: {final_volume}mL")
elif parsed_volume == 0.0 and amount.lower().strip() == "all":
actual_volume = get_resource_liquid_volume(G.nodes.get(from_vessel_id, {}))
debug_print("🎯 检测到 amount='all',从容器读取全部体积...")
actual_volume = get_vessel_liquid_volume(G, from_vessel_id)
if actual_volume > 0:
final_volume = actual_volume
debug_print(f"✅ amount='all',设置体积为: {final_volume}mL")
# 最终体积验证
debug_print(f"🔍 步骤2: 最终体积验证...")
if final_volume <= 0:
logger.error(f"体积无效: {final_volume}mL")
logger.error(f"体积无效: {final_volume}mL")
final_volume = 10.0
logger.warning(f"强制设置为默认值: {final_volume}mL")
logger.warning(f"⚠️ 强制设置为默认值: {final_volume}mL")
debug_print(f"最终体积: {final_volume}mL")
debug_print(f"✅ 最终确定体积: {final_volume}mL")
# 2. 处理流速参数
debug_print(f"🔍 步骤3: 处理流速参数...")
debug_print(f" - 原始 flowrate: {flowrate}")
debug_print(f" - 原始 transfer_flowrate: {transfer_flowrate}")
final_flowrate = flowrate if flowrate > 0 else 2.5
final_transfer_flowrate = transfer_flowrate if transfer_flowrate > 0 else 0.5
if flowrate <= 0:
logger.warning(f"flowrate <= 0修正为: {final_flowrate}mL/s")
logger.warning(f"⚠️ flowrate <= 0修正为: {final_flowrate}mL/s")
if transfer_flowrate <= 0:
logger.warning(f"transfer_flowrate <= 0修正为: {final_transfer_flowrate}mL/s")
logger.warning(f"⚠️ transfer_flowrate <= 0修正为: {final_transfer_flowrate}mL/s")
debug_print(f"✅ 修正后流速: flowrate={final_flowrate}mL/s, transfer_flowrate={final_transfer_flowrate}mL/s")
# 3. 根据时间计算流速
if time > 0 and final_volume > 0:
debug_print(f"🔍 步骤4: 根据时间计算流速...")
calculated_flowrate = final_volume / time
debug_print(f" - 计算得到流速: {calculated_flowrate}mL/s")
if flowrate <= 0 or flowrate == 2.5:
final_flowrate = min(calculated_flowrate, 10.0)
debug_print(f" - 调整 flowrate 为: {final_flowrate}mL/s")
if transfer_flowrate <= 0 or transfer_flowrate == 0.5:
final_transfer_flowrate = min(calculated_flowrate, 5.0)
debug_print(f" - 调整 transfer_flowrate 为: {final_transfer_flowrate}mL/s")
# 4. 根据速度规格调整
if rate_spec:
debug_print(f"🔍 步骤5: 根据速度规格调整...")
debug_print(f" - 速度规格: '{rate_spec}'")
if rate_spec == "dropwise":
final_flowrate = min(final_flowrate, 0.1)
final_transfer_flowrate = min(final_transfer_flowrate, 0.1)
debug_print(f" - dropwise模式流速调整为: {final_flowrate}mL/s")
elif rate_spec == "slowly":
final_flowrate = min(final_flowrate, 0.5)
final_transfer_flowrate = min(final_transfer_flowrate, 0.3)
debug_print(f" - slowly模式流速调整为: {final_flowrate}mL/s")
elif rate_spec == "quickly":
final_flowrate = max(final_flowrate, 5.0)
final_transfer_flowrate = max(final_transfer_flowrate, 2.0)
debug_print(f"速度规格 '{rate_spec}': flowrate={final_flowrate}, transfer={final_transfer_flowrate}")
debug_print(f" - quickly模式流速调整为: {final_flowrate}mL/s")
# 5. 处理冲洗参数
debug_print(f"🔍 步骤6: 处理冲洗参数...")
final_rinsing_solvent = rinsing_solvent
final_rinsing_volume = rinsing_volume if rinsing_volume > 0 else 5.0
final_rinsing_repeats = rinsing_repeats if rinsing_repeats > 0 else 2
if rinsing_volume <= 0:
logger.warning(f"rinsing_volume <= 0修正为: {final_rinsing_volume}mL")
logger.warning(f"⚠️ rinsing_volume <= 0修正为: {final_rinsing_volume}mL")
if rinsing_repeats <= 0:
logger.warning(f"rinsing_repeats <= 0修正为: {final_rinsing_repeats}")
logger.warning(f"⚠️ rinsing_repeats <= 0修正为: {final_rinsing_repeats}")
# 根据物理属性调整冲洗参数
if viscous or solid:
final_rinsing_repeats = max(final_rinsing_repeats, 3)
final_rinsing_volume = max(final_rinsing_volume, 10.0)
debug_print(f"🧪 粘稠/固体物质,调整冲洗参数:{final_rinsing_repeats}次,{final_rinsing_volume}mL")
# 参数总结
debug_print(f"最终参数: volume={final_volume}mL, flowrate={final_flowrate}mL/s, "
f"transfer_flowrate={final_transfer_flowrate}mL/s, "
f"rinsing={final_rinsing_solvent}/{final_rinsing_volume}mL/{final_rinsing_repeats}")
debug_print("📊 最终参数总结:")
debug_print(f" - 体积: {final_volume}mL")
debug_print(f" - 流速: {final_flowrate}mL/s")
debug_print(f" - 转移流速: {final_transfer_flowrate}mL/s")
debug_print(f" - 冲洗溶剂: '{final_rinsing_solvent}'")
debug_print(f" - 冲洗体积: {final_rinsing_volume}mL")
debug_print(f" - 冲洗次数: {final_rinsing_repeats}")
# ========== 执行基础转移 ==========
debug_print("🔧 步骤7: 开始执行基础转移...")
# 执行基础转移
try:
debug_print(f" - 调用 generate_pump_protocol...")
debug_print(
f" - 参数: G, '{from_vessel_id}', '{to_vessel_id}', {final_volume}, {final_flowrate}, {final_transfer_flowrate}")
pump_action_sequence = generate_pump_protocol(
G, from_vessel_id, to_vessel_id, final_volume,
final_flowrate, final_transfer_flowrate
)
debug_print(f"基础转移生成了 {len(pump_action_sequence)} 个动作")
debug_print(f" - generate_pump_protocol 返回结果:")
debug_print(f" - 动作序列长度: {len(pump_action_sequence)}")
debug_print(f" - 动作序列是否为空: {len(pump_action_sequence) == 0}")
if not pump_action_sequence:
debug_print("基础转移协议为空")
debug_print("基础转移协议生成为空,可能是路径问题")
debug_print(f" - 源容器存在: {from_vessel_id in G.nodes()}")
debug_print(f" - 目标容器存在: {to_vessel_id in G.nodes()}")
if from_vessel_id in G.nodes() and to_vessel_id in G.nodes():
try:
path = nx.shortest_path(G, source=from_vessel_id, target=to_vessel_id)
debug_print(f"路径存在: {path}")
except Exception:
pass
debug_print(f" - 路径存在: {path}")
except Exception as path_error:
debug_print(f" - 无法找到路径: {str(path_error)}")
return [
{
"device_id": "system",
"action_name": "log_message",
"action_kwargs": {
"message": f"路径问题,无法转移: {final_volume}mL 从 {from_vessel_id}{to_vessel_id}"
"message": f"⚠️ 路径问题,无法转移: {final_volume}mL 从 {from_vessel_id}{to_vessel_id}"
}
}
]
debug_print(f"✅ 基础转移生成了 {len(pump_action_sequence)} 个动作")
# 打印前几个动作用于调试
if len(pump_action_sequence) > 0:
debug_print("🔍 前几个动作预览:")
for i, action in enumerate(pump_action_sequence[:3]):
debug_print(f" 动作 {i + 1}: {action}")
if len(pump_action_sequence) > 3:
debug_print(f" ... 还有 {len(pump_action_sequence) - 3} 个动作")
except Exception as e:
debug_print(f"基础转移失败: {str(e)}\n{traceback.format_exc()}")
debug_print(f"基础转移失败: {str(e)}")
import traceback
debug_print(f"详细错误: {traceback.format_exc()}")
return [
{
"device_id": "system",
"action_name": "log_message",
"action_kwargs": {
"message": f"转移失败: {final_volume}mL 从 {from_vessel_id}{to_vessel_id}, 错误: {str(e)}"
"message": f"转移失败: {final_volume}mL 从 {from_vessel_id}{to_vessel_id}, 错误: {str(e)}"
}
}
]
# 执行冲洗操作
# ========== 执行冲洗操作 ==========
debug_print("🔧 步骤8: 检查冲洗操作...")
if final_rinsing_solvent and final_rinsing_solvent.strip() and final_rinsing_repeats > 0:
debug_print(f"🧽 开始冲洗操作,溶剂: '{final_rinsing_solvent}'")
try:
if final_rinsing_solvent.strip() != "air":
debug_print(" - 执行液体冲洗...")
rinsing_actions = _generate_rinsing_sequence(
G, from_vessel_id, to_vessel_id, final_rinsing_solvent,
final_rinsing_volume, final_rinsing_repeats,
final_flowrate, final_transfer_flowrate
)
pump_action_sequence.extend(rinsing_actions)
debug_print(f" - 添加了 {len(rinsing_actions)} 个冲洗动作")
else:
debug_print(" - 执行空气冲洗...")
air_rinsing_actions = _generate_air_rinsing_sequence(
G, from_vessel_id, to_vessel_id, final_rinsing_volume, final_rinsing_repeats,
final_flowrate, final_transfer_flowrate
)
pump_action_sequence.extend(air_rinsing_actions)
debug_print(f" - 添加了 {len(air_rinsing_actions)} 个空气冲洗动作")
except Exception as e:
debug_print(f"冲洗操作失败: {str(e)}")
debug_print(f"⚠️ 冲洗操作失败: {str(e)},跳过冲洗")
else:
debug_print(f"跳过冲洗 (solvent='{final_rinsing_solvent}', repeats={final_rinsing_repeats})")
debug_print(f"⏭️ 跳过冲洗操作")
debug_print(f" - 溶剂: '{final_rinsing_solvent}'")
debug_print(f" - 次数: {final_rinsing_repeats}")
debug_print(f" - 条件满足: {bool(final_rinsing_solvent and final_rinsing_solvent.strip() and final_rinsing_repeats > 0)}")
# 最终结果
debug_print(f"PUMP_TRANSFER 完成: {from_vessel_id} -> {to_vessel_id}, "
f"volume={final_volume}mL, 动作数={len(pump_action_sequence)}")
# ========== 最终结果 ==========
debug_print("=" * 60)
debug_print(f"🎉 PUMP_TRANSFER: 协议生成完成")
debug_print(f" 📊 总动作数: {len(pump_action_sequence)}")
debug_print(f" 📋 最终体积: {final_volume}mL")
debug_print(f" 🚀 执行路径: {from_vessel_id} -> {to_vessel_id}")
# 最终验证
if len(pump_action_sequence) == 0:
debug_print("🚨 协议生成结果为空!这是异常情况")
return [
{
"device_id": "system",
"action_name": "log_message",
"action_kwargs": {
"message": "协议生成失败: 无法生成任何动作序列"
"message": f"🚨 协议生成失败: 无法生成任何动作序列"
}
}
]
debug_print("=" * 60)
return pump_action_sequence
def _parse_amount_to_volume(amount: str) -> float:
"""解析 amount 字符串为体积"""
debug_print(f"🔍 解析 amount: '{amount}'")
if not amount:
debug_print(" - amount 为空,返回 0.0")
return 0.0
amount = amount.lower().strip()
debug_print(f" - 处理后的 amount: '{amount}'")
# 处理特殊关键词
if amount == "all":
debug_print(" - 检测到 'all',返回 0.0(需要后续处理)")
return 0.0 # 返回0.0,让调用者处理
# 提取数字
import re
numbers = re.findall(r'[\d.]+', amount)
debug_print(f" - 提取到的数字: {numbers}")
if numbers:
volume = float(numbers[0])
debug_print(f" - 基础体积: {volume}")
# 单位转换
if 'ml' in amount or 'milliliter' in amount:
debug_print(f" - 单位: mL最终体积: {volume}")
return volume
elif 'l' in amount and 'ml' not in amount:
return volume * 1000
final_volume = volume * 1000
debug_print(f" - 单位: L最终体积: {final_volume}mL")
return final_volume
elif 'μl' in amount or 'microliter' in amount:
return volume / 1000
final_volume = volume / 1000
debug_print(f" - 单位: μL最终体积: {final_volume}mL")
return final_volume
else:
return volume # 默认mL
debug_print(f" - 无单位,假设为 mL: {volume}")
return volume
debug_print(" - 无法解析,返回 0.0")
return 0.0

View File

@@ -4,64 +4,76 @@ import logging
from typing import List, Dict, Any, Tuple, Union
from .utils.vessel_parser import get_vessel, find_solvent_vessel
from .utils.unit_parser import parse_volume_input
from .utils.logger_util import debug_print
from .pump_protocol import generate_pump_protocol_with_rinsing
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[RECRYSTALLIZE] {message}")
def parse_ratio(ratio_str: str) -> Tuple[float, float]:
"""
解析比例字符串,支持多种格式
Args:
ratio_str: 比例字符串(如 "1:1", "3:7", "50:50"
Returns:
Tuple[float, float]: 比例元组 (ratio1, ratio2)
"""
debug_print(f"⚖️ 开始解析比例: '{ratio_str}' 📊")
try:
# 处理 "1:1", "3:7", "50:50" 等格式
if ":" in ratio_str:
parts = ratio_str.split(":")
if len(parts) == 2:
ratio1 = float(parts[0])
ratio2 = float(parts[1])
debug_print(f"✅ 冒号格式解析成功: {ratio1}:{ratio2} 🎯")
return ratio1, ratio2
# 处理 "1-1", "3-7" 等格式
if "-" in ratio_str:
parts = ratio_str.split("-")
if len(parts) == 2:
ratio1 = float(parts[0])
ratio2 = float(parts[1])
debug_print(f"✅ 横线格式解析成功: {ratio1}:{ratio2} 🎯")
return ratio1, ratio2
# 处理 "1,1", "3,7" 等格式
if "," in ratio_str:
parts = ratio_str.split(",")
if len(parts) == 2:
ratio1 = float(parts[0])
ratio2 = float(parts[1])
debug_print(f"✅ 逗号格式解析成功: {ratio1}:{ratio2} 🎯")
return ratio1, ratio2
debug_print(f"无法解析比例 '{ratio_str}',使用默认比例 1:1")
# 默认 1:1
debug_print(f"⚠️ 无法解析比例 '{ratio_str}',使用默认比例 1:1 🎭")
return 1.0, 1.0
except ValueError:
debug_print(f"比例解析错误 '{ratio_str}',使用默认比例 1:1")
debug_print(f"比例解析错误 '{ratio_str}',使用默认比例 1:1 🎭")
return 1.0, 1.0
def generate_recrystallize_protocol(
G: nx.DiGraph,
vessel: dict,
vessel: dict, # 🔧 修改:从字符串改为字典类型
ratio: str,
solvent1: str,
solvent2: str,
volume: Union[str, float],
volume: Union[str, float], # 支持字符串和数值
**kwargs
) -> List[Dict[str, Any]]:
"""
生成重结晶协议序列 - 支持vessel字典和体积运算
Args:
G: 有向图,节点为容器和设备
vessel: 目标容器字典从XDL传入
@@ -70,18 +82,28 @@ def generate_recrystallize_protocol(
solvent2: 第二种溶剂名称
volume: 总体积(支持 "100 mL", "50", "2.5 L" 等)
**kwargs: 其他可选参数
Returns:
List[Dict[str, Any]]: 动作序列
"""
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
action_sequence = []
debug_print(f"开始生成重结晶协议: vessel={vessel_id}, ratio={ratio}, solvent1={solvent1}, solvent2={solvent2}, volume={volume}")
# 记录重结晶前的容器状态
debug_print("💎" * 20)
debug_print("🚀 开始生成重结晶协议支持vessel字典和体积运算")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" ⚖️ 比例: {ratio}")
debug_print(f" 🧪 溶剂1: {solvent1}")
debug_print(f" 🧪 溶剂2: {solvent2}")
debug_print(f" 💧 总体积: {volume} (类型: {type(volume)})")
debug_print("💎" * 20)
# 🔧 新增:记录重结晶前的容器状态
debug_print("🔍 记录重结晶前容器状态...")
original_liquid_volume = 0.0
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
@@ -89,73 +111,102 @@ def generate_recrystallize_protocol(
original_liquid_volume = current_volume[0]
elif isinstance(current_volume, (int, float)):
original_liquid_volume = current_volume
debug_print(f"📊 重结晶前液体体积: {original_liquid_volume:.2f}mL")
# 1. 验证目标容器存在
if vessel_id not in G.nodes():
debug_print("📍 步骤1: 验证目标容器... 🔧")
if vessel_id not in G.nodes(): # 🔧 使用 vessel_id
debug_print(f"❌ 目标容器 '{vessel_id}' 不存在于系统中! 😱")
raise ValueError(f"目标容器 '{vessel_id}' 不存在于系统中")
debug_print(f"✅ 目标容器 '{vessel_id}' 验证通过 🎯")
# 2. 解析体积(支持单位)
debug_print("📍 步骤2: 解析体积(支持单位)... 💧")
final_volume = parse_volume_input(volume, "mL")
debug_print(f"体积解析: {volume} -> {final_volume}mL")
debug_print(f"🎯 体积解析完成: {volume} {final_volume}mL")
# 3. 解析比例
debug_print("📍 步骤3: 解析比例... ⚖️")
ratio1, ratio2 = parse_ratio(ratio)
total_ratio = ratio1 + ratio2
debug_print(f"🎯 比例解析完成: {ratio1}:{ratio2} (总比例: {total_ratio}) ✨")
# 4. 计算各溶剂体积
debug_print("📍 步骤4: 计算各溶剂体积... 🧮")
volume1 = final_volume * (ratio1 / total_ratio)
volume2 = final_volume * (ratio2 / total_ratio)
debug_print(f"溶剂体积: {solvent1}={volume1:.2f}mL, {solvent2}={volume2:.2f}mL")
debug_print(f"🧪 {solvent1} 体积: {volume1:.2f} mL ({ratio1}/{total_ratio} × {final_volume})")
debug_print(f"🧪 {solvent2} 体积: {volume2:.2f} mL ({ratio2}/{total_ratio} × {final_volume})")
debug_print(f"✅ 体积计算完成: 总计 {volume1 + volume2:.2f} mL 🎯")
# 5. 查找溶剂容器
debug_print("📍 步骤5: 查找溶剂容器... 🔍")
try:
debug_print(f" 🔍 查找溶剂1容器...")
solvent1_vessel = find_solvent_vessel(G, solvent1)
debug_print(f" 🎉 找到溶剂1容器: {solvent1_vessel}")
except ValueError as e:
debug_print(f" ❌ 溶剂1容器查找失败: {str(e)} 😭")
raise ValueError(f"无法找到溶剂1 '{solvent1}': {str(e)}")
try:
debug_print(f" 🔍 查找溶剂2容器...")
solvent2_vessel = find_solvent_vessel(G, solvent2)
debug_print(f" 🎉 找到溶剂2容器: {solvent2_vessel}")
except ValueError as e:
debug_print(f" ❌ 溶剂2容器查找失败: {str(e)} 😭")
raise ValueError(f"无法找到溶剂2 '{solvent2}': {str(e)}")
# 6. 验证路径存在
debug_print("📍 步骤6: 验证传输路径... 🛤️")
try:
path1 = nx.shortest_path(G, source=solvent1_vessel, target=vessel_id)
path1 = nx.shortest_path(G, source=solvent1_vessel, target=vessel_id) # 🔧 使用 vessel_id
debug_print(f" 🛤️ 溶剂1路径: {''.join(path1)}")
except nx.NetworkXNoPath:
debug_print(f" ❌ 溶剂1路径不可达: {solvent1_vessel}{vessel_id} 😞")
raise ValueError(f"从溶剂1容器 '{solvent1_vessel}' 到目标容器 '{vessel_id}' 没有可用路径")
try:
path2 = nx.shortest_path(G, source=solvent2_vessel, target=vessel_id)
path2 = nx.shortest_path(G, source=solvent2_vessel, target=vessel_id) # 🔧 使用 vessel_id
debug_print(f" 🛤️ 溶剂2路径: {''.join(path2)}")
except nx.NetworkXNoPath:
debug_print(f" ❌ 溶剂2路径不可达: {solvent2_vessel}{vessel_id} 😞")
raise ValueError(f"从溶剂2容器 '{solvent2_vessel}' 到目标容器 '{vessel_id}' 没有可用路径")
# 7. 添加第一种溶剂
debug_print("📍 步骤7: 添加第一种溶剂... 🧪")
debug_print(f" 🚰 开始添加溶剂1: {solvent1} ({volume1:.2f} mL)")
try:
pump_actions1 = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=solvent1_vessel,
to_vessel=vessel_id,
volume=volume1,
to_vessel=vessel_id, # 🔧 使用 vessel_id
volume=volume1, # 使用解析后的体积
amount="",
time=0.0,
viscous=False,
rinsing_solvent="",
rinsing_solvent="", # 重结晶不需要清洗
rinsing_volume=0.0,
rinsing_repeats=0,
solid=False,
flowrate=2.0,
flowrate=2.0, # 正常流速
transfer_flowrate=0.5
)
action_sequence.extend(pump_actions1)
debug_print(f" ✅ 溶剂1泵送动作已添加: {len(pump_actions1)} 个动作 🚰✨")
except Exception as e:
debug_print(f" ❌ 溶剂1泵协议生成失败: {str(e)} 😭")
raise ValueError(f"生成溶剂1泵协议时出错: {str(e)}")
# 更新容器体积 - 添加溶剂1后
# 🔧 新增:更新容器体积 - 添加溶剂1后
debug_print(" 🔧 更新容器体积 - 添加溶剂1后...")
new_volume_after_solvent1 = original_liquid_volume + volume1
# 更新vessel字典中的体积
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
@@ -165,14 +216,15 @@ def generate_recrystallize_protocol(
vessel["data"]["liquid_volume"] = [new_volume_after_solvent1]
else:
vessel["data"]["liquid_volume"] = new_volume_after_solvent1
# 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = new_volume_after_solvent1
@@ -180,42 +232,53 @@ def generate_recrystallize_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [new_volume_after_solvent1]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = new_volume_after_solvent1
debug_print(f" 📊 体积更新: {original_liquid_volume:.2f}mL + {volume1:.2f}mL = {new_volume_after_solvent1:.2f}mL")
# 8. 等待溶剂1稳定
debug_print(" ⏳ 添加溶剂1稳定等待...")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
"time": 5.0,
"time": 5.0, # 缩短等待时间
"description": f"等待溶剂1 {solvent1} 稳定"
}
})
debug_print(" ✅ 溶剂1稳定等待已添加 ⏰✨")
# 9. 添加第二种溶剂
debug_print("📍 步骤8: 添加第二种溶剂... 🧪")
debug_print(f" 🚰 开始添加溶剂2: {solvent2} ({volume2:.2f} mL)")
try:
pump_actions2 = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=solvent2_vessel,
to_vessel=vessel_id,
volume=volume2,
to_vessel=vessel_id, # 🔧 使用 vessel_id
volume=volume2, # 使用解析后的体积
amount="",
time=0.0,
viscous=False,
rinsing_solvent="",
rinsing_solvent="", # 重结晶不需要清洗
rinsing_volume=0.0,
rinsing_repeats=0,
solid=False,
flowrate=2.0,
flowrate=2.0, # 正常流速
transfer_flowrate=0.5
)
action_sequence.extend(pump_actions2)
debug_print(f" ✅ 溶剂2泵送动作已添加: {len(pump_actions2)} 个动作 🚰✨")
except Exception as e:
debug_print(f" ❌ 溶剂2泵协议生成失败: {str(e)} 😭")
raise ValueError(f"生成溶剂2泵协议时出错: {str(e)}")
# 更新容器体积 - 添加溶剂2后
# 🔧 新增:更新容器体积 - 添加溶剂2后
debug_print(" 🔧 更新容器体积 - 添加溶剂2后...")
final_liquid_volume = new_volume_after_solvent1 + volume2
# 更新vessel字典中的体积
if "data" in vessel and "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
@@ -225,14 +288,15 @@ def generate_recrystallize_protocol(
vessel["data"]["liquid_volume"] = [final_liquid_volume]
else:
vessel["data"]["liquid_volume"] = final_liquid_volume
# 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = final_liquid_volume
@@ -240,25 +304,36 @@ def generate_recrystallize_protocol(
G.nodes[vessel_id]['data']['liquid_volume'] = [final_liquid_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = final_liquid_volume
debug_print(f" 📊 最终体积: {new_volume_after_solvent1:.2f}mL + {volume2:.2f}mL = {final_liquid_volume:.2f}mL")
# 10. 等待溶剂2稳定
debug_print(" ⏳ 添加溶剂2稳定等待...")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
"time": 5.0,
"time": 5.0, # 缩短等待时间
"description": f"等待溶剂2 {solvent2} 稳定"
}
})
debug_print(" ✅ 溶剂2稳定等待已添加 ⏰✨")
# 11. 等待重结晶完成
original_crystallize_time = 600.0
simulation_time_limit = 60.0
debug_print("📍 步骤9: 等待重结晶完成... 💎")
# 模拟运行时间优化
debug_print(" ⏱️ 检查模拟运行时间限制...")
original_crystallize_time = 600.0 # 原始重结晶时间
simulation_time_limit = 60.0 # 模拟运行时间限制60秒
final_crystallize_time = min(original_crystallize_time, simulation_time_limit)
if original_crystallize_time > simulation_time_limit:
debug_print(f"模拟运行优化: {original_crystallize_time}s -> {final_crystallize_time}s")
debug_print(f" 🎮 模拟运行优化: {original_crystallize_time}s {final_crystallize_time}s")
debug_print(f" 📊 时间缩短: {original_crystallize_time/60:.1f}分钟 → {final_crystallize_time/60:.1f}分钟 🚀")
else:
debug_print(f" ✅ 时间在限制内: {final_crystallize_time}s 保持不变 🎯")
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
@@ -266,28 +341,50 @@ def generate_recrystallize_protocol(
"description": f"等待重结晶完成({solvent1}:{solvent2} = {ratio},总体积 {final_volume}mL" + (f" (模拟时间)" if original_crystallize_time != final_crystallize_time else "")
}
})
debug_print(f"重结晶协议生成完成: {len(action_sequence)} 个动作, 容器={vessel_id}, 体积变化: {original_liquid_volume:.2f} -> {final_liquid_volume:.2f}mL")
debug_print(f" ✅ 重结晶等待已添加: {final_crystallize_time}s 💎✨")
# 显示时间调整信息
if original_crystallize_time != final_crystallize_time:
debug_print(f" 🎭 模拟优化说明: 原计划 {original_crystallize_time/60:.1f}分钟,实际模拟 {final_crystallize_time/60:.1f}分钟 ⚡")
# 总结
debug_print("💎" * 20)
debug_print(f"🎉 重结晶协议生成完成! ✨")
debug_print(f"📊 总动作数: {len(action_sequence)}")
debug_print(f"🥽 目标容器: {vessel_id}")
debug_print(f"💧 总体积变化:")
debug_print(f" - 原始体积: {original_liquid_volume:.2f}mL")
debug_print(f" - 添加溶剂: {final_volume:.2f}mL")
debug_print(f" - 最终体积: {final_liquid_volume:.2f}mL")
debug_print(f"⚖️ 溶剂比例: {solvent1}:{solvent2} = {ratio1}:{ratio2}")
debug_print(f"🧪 溶剂1: {solvent1} ({volume1:.2f}mL)")
debug_print(f"🧪 溶剂2: {solvent2} ({volume2:.2f}mL)")
debug_print(f"⏱️ 预计总时间: {(final_crystallize_time + 10)/60:.1f} 分钟 ⌛")
debug_print("💎" * 20)
return action_sequence
# 测试函数
def test_recrystallize_protocol():
"""测试重结晶协议"""
debug_print("=== RECRYSTALLIZE PROTOCOL 测试 ===")
debug_print("🧪 === RECRYSTALLIZE PROTOCOL 测试 ===")
# 测试体积解析
debug_print("💧 测试体积解析...")
test_volumes = ["100 mL", "2.5 L", "500", "50.5", "?", "invalid"]
for vol in test_volumes:
parsed = parse_volume_input(vol)
debug_print(f"体积 '{vol}' -> {parsed}mL")
debug_print(f" 📊 体积 '{vol}' -> {parsed}mL")
# 测试比例解析
debug_print("⚖️ 测试比例解析...")
test_ratios = ["1:1", "3:7", "50:50", "1-1", "2,8", "invalid"]
for ratio in test_ratios:
r1, r2 = parse_ratio(ratio)
debug_print(f"比例 '{ratio}' -> {r1}:{r2}")
debug_print("测试完成")
debug_print(f" 📊 比例 '{ratio}' -> {r1}:{r2}")
debug_print("测试完成 🎉")
if __name__ == "__main__":
test_recrystallize_protocol()
test_recrystallize_protocol()

View File

@@ -1,87 +1,253 @@
import networkx as nx
import logging
import sys
from typing import List, Dict, Any, Optional
from .utils.logger_util import debug_print, action_log
from .utils.vessel_parser import find_solvent_vessel
from .pump_protocol import generate_pump_protocol_with_rinsing
# 设置日志
logger = logging.getLogger(__name__)
create_action_log = action_log
# 确保输出编码为UTF-8
if hasattr(sys.stdout, 'reconfigure'):
try:
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
except:
pass
def debug_print(message):
"""调试输出函数 - 支持中文"""
try:
# 确保消息是字符串格式
safe_message = str(message)
print(f"[重置处理] {safe_message}", flush=True)
logger.info(f"[重置处理] {safe_message}")
except UnicodeEncodeError:
# 如果编码失败,尝试替换不支持的字符
safe_message = str(message).encode('utf-8', errors='replace').decode('utf-8')
print(f"[重置处理] {safe_message}", flush=True)
logger.info(f"[重置处理] {safe_message}")
except Exception as e:
# 最后的安全措施
fallback_message = f"日志输出错误: {repr(message)}"
print(f"[重置处理] {fallback_message}", flush=True)
logger.info(f"[重置处理] {fallback_message}")
def create_action_log(message: str, emoji: str = "📝") -> Dict[str, Any]:
"""创建一个动作日志 - 支持中文和emoji"""
try:
full_message = f"{emoji} {message}"
debug_print(full_message)
logger.info(full_message)
return {
"action_name": "wait",
"action_kwargs": {
"time": 0.1,
"log_message": full_message,
"progress_message": full_message
}
}
except Exception as e:
# 如果emoji有问题使用纯文本
safe_message = f"[日志] {message}"
debug_print(safe_message)
logger.info(safe_message)
return {
"action_name": "wait",
"action_kwargs": {
"time": 0.1,
"log_message": safe_message,
"progress_message": safe_message
}
}
def find_solvent_vessel(G: nx.DiGraph, solvent: str) -> str:
"""
查找溶剂容器,支持多种匹配模式
Args:
G: 网络图
solvent: 溶剂名称(如 "methanol", "ethanol", "water"
Returns:
str: 溶剂容器ID
"""
debug_print(f"🔍 正在查找溶剂 '{solvent}' 的容器...")
# 构建可能的容器名称
possible_names = [
f"flask_{solvent}", # flask_methanol
f"bottle_{solvent}", # bottle_methanol
f"reagent_{solvent}", # reagent_methanol
f"reagent_bottle_{solvent}", # reagent_bottle_methanol
f"{solvent}_flask", # methanol_flask
f"{solvent}_bottle", # methanol_bottle
f"{solvent}", # methanol
f"vessel_{solvent}", # vessel_methanol
]
debug_print(f"🎯 候选容器名称: {possible_names[:3]}... (共{len(possible_names)}个)")
# 第一步:通过容器名称匹配
debug_print("📋 方法1: 精确名称匹配...")
for vessel_name in possible_names:
if vessel_name in G.nodes():
debug_print(f"✅ 通过名称匹配找到容器: {vessel_name}")
return vessel_name
debug_print("⚠️ 精确名称匹配失败,尝试模糊匹配...")
# 第二步:通过模糊匹配
debug_print("📋 方法2: 模糊名称匹配...")
for node_id in G.nodes():
if G.nodes[node_id].get('type') == 'container':
node_name = G.nodes[node_id].get('name', '').lower()
# 检查是否包含溶剂名称
if solvent.lower() in node_id.lower() or solvent.lower() in node_name:
debug_print(f"✅ 通过模糊匹配找到容器: {node_id}")
return node_id
debug_print("⚠️ 模糊匹配失败,尝试液体类型匹配...")
# 第三步:通过液体类型匹配
debug_print("📋 方法3: 液体类型匹配...")
for node_id in G.nodes():
if G.nodes[node_id].get('type') == 'container':
vessel_data = G.nodes[node_id].get('data', {})
liquids = vessel_data.get('liquid', [])
for liquid in liquids:
if isinstance(liquid, dict):
liquid_type = (liquid.get('liquid_type') or liquid.get('name', '')).lower()
reagent_name = vessel_data.get('reagent_name', '').lower()
if solvent.lower() in liquid_type or solvent.lower() in reagent_name:
debug_print(f"✅ 通过液体类型匹配找到容器: {node_id}")
return node_id
# 列出可用容器帮助调试
debug_print("📊 显示可用容器信息...")
available_containers = []
for node_id in G.nodes():
if G.nodes[node_id].get('type') == 'container':
vessel_data = G.nodes[node_id].get('data', {})
liquids = vessel_data.get('liquid', [])
liquid_types = [liquid.get('liquid_type', '') or liquid.get('name', '')
for liquid in liquids if isinstance(liquid, dict)]
available_containers.append({
'id': node_id,
'name': G.nodes[node_id].get('name', ''),
'liquids': liquid_types,
'reagent_name': vessel_data.get('reagent_name', '')
})
debug_print(f"📋 可用容器列表 (共{len(available_containers)}个):")
for i, container in enumerate(available_containers[:5]): # 只显示前5个
debug_print(f" {i+1}. 🥽 {container['id']}: {container['name']}")
debug_print(f" 💧 液体: {container['liquids']}")
debug_print(f" 🧪 试剂: {container['reagent_name']}")
if len(available_containers) > 5:
debug_print(f" ... 还有 {len(available_containers)-5} 个容器")
debug_print(f"❌ 找不到溶剂 '{solvent}' 对应的容器")
raise ValueError(f"找不到溶剂 '{solvent}' 对应的容器。尝试了: {possible_names[:3]}...")
def generate_reset_handling_protocol(
G: nx.DiGraph,
solvent: str,
vessel: Optional[str] = None,
**kwargs
vessel: Optional[str] = None, # 🆕 新增可选vessel参数
**kwargs # 接收其他可能的参数但不使用
) -> List[Dict[str, Any]]:
"""
生成重置处理协议序列 - 支持自定义容器
Args:
G: 有向图,节点为容器和设备
solvent: 溶剂名称从XDL传入
vessel: 目标容器名称(可选,默认为 "main_reactor"
**kwargs: 其他可选参数,但不使用
Returns:
List[Dict[str, Any]]: 动作序列
"""
action_sequence = []
# 🔧 修改支持自定义vessel参数
target_vessel = vessel if vessel is not None else "main_reactor" # 默认目标容器
volume = 50.0 # 默认体积 50 mL
target_vessel = vessel if vessel is not None else "main_reactor"
volume = 50.0
debug_print(f"开始生成重置处理协议: solvent={solvent}, vessel={target_vessel}, volume={volume}mL")
debug_print("=" * 60)
debug_print("🚀 开始生成重置处理协议")
debug_print(f"📋 输入参数:")
debug_print(f" 🧪 溶剂: {solvent}")
debug_print(f" 🥽 目标容器: {target_vessel} {'(默认)' if vessel is None else '(指定)'}")
debug_print(f" 💧 体积: {volume} mL")
debug_print(f" ⚙️ 其他参数: {kwargs}")
debug_print("=" * 60)
# 添加初始日志
action_sequence.append(action_log(f"开始重置处理操作 - 容器: {target_vessel}", "🎬"))
action_sequence.append(action_log(f"使用溶剂: {solvent}", "🧪"))
action_sequence.append(action_log(f"重置体积: {volume}mL", "💧"))
action_sequence.append(create_action_log(f"开始重置处理操作 - 容器: {target_vessel}", "🎬"))
action_sequence.append(create_action_log(f"使用溶剂: {solvent}", "🧪"))
action_sequence.append(create_action_log(f"重置体积: {volume}mL", "💧"))
if vessel is None:
action_sequence.append(action_log("使用默认目标容器: main_reactor", "⚙️"))
action_sequence.append(create_action_log("使用默认目标容器: main_reactor", "⚙️"))
else:
action_sequence.append(action_log(f"使用指定目标容器: {vessel}", "🎯"))
action_sequence.append(create_action_log(f"使用指定目标容器: {vessel}", "🎯"))
# 1. 验证目标容器存在
action_sequence.append(action_log("正在验证目标容器...", "🔍"))
debug_print("🔍 步骤1: 验证目标容器...")
action_sequence.append(create_action_log("正在验证目标容器...", "🔍"))
if target_vessel not in G.nodes():
action_sequence.append(action_log(f"目标容器 '{target_vessel}' 不存在", ""))
debug_print(f"目标容器 '{target_vessel}' 不存在于系统中!")
action_sequence.append(create_action_log(f"目标容器 '{target_vessel}' 不存在", ""))
raise ValueError(f"目标容器 '{target_vessel}' 不存在于系统中")
action_sequence.append(action_log(f"目标容器验证通过: {target_vessel}", ""))
debug_print(f"目标容器 '{target_vessel}' 验证通过")
action_sequence.append(create_action_log(f"目标容器验证通过: {target_vessel}", ""))
# 2. 查找溶剂容器
action_sequence.append(action_log("正在查找溶剂容器...", "🔍"))
debug_print("🔍 步骤2: 查找溶剂容器...")
action_sequence.append(create_action_log("正在查找溶剂容器...", "🔍"))
try:
solvent_vessel = find_solvent_vessel(G, solvent)
debug_print(f"找到溶剂容器: {solvent_vessel}")
action_sequence.append(action_log(f"找到溶剂容器: {solvent_vessel}", ""))
debug_print(f"找到溶剂容器: {solvent_vessel}")
action_sequence.append(create_action_log(f"找到溶剂容器: {solvent_vessel}", ""))
except ValueError as e:
action_sequence.append(action_log(f"溶剂容器查找失败: {str(e)}", ""))
debug_print(f"溶剂容器查找失败: {str(e)}")
action_sequence.append(create_action_log(f"溶剂容器查找失败: {str(e)}", ""))
raise ValueError(f"无法找到溶剂 '{solvent}': {str(e)}")
# 3. 验证路径存在
action_sequence.append(action_log("正在验证传输路径...", "🛤️"))
debug_print("🔍 步骤3: 验证传输路径...")
action_sequence.append(create_action_log("正在验证传输路径...", "🛤️"))
try:
path = nx.shortest_path(G, source=solvent_vessel, target=target_vessel)
action_sequence.append(action_log(f"传输路径: {''.join(path)}", "🛤️"))
debug_print(f"✅ 找到路径: {''.join(path)}")
action_sequence.append(create_action_log(f"传输路径: {''.join(path)}", "🛤️"))
except nx.NetworkXNoPath:
action_sequence.append(action_log(f"路径不可达: {solvent_vessel}{target_vessel}", ""))
debug_print(f"路径不可达: {solvent_vessel}{target_vessel}")
action_sequence.append(create_action_log(f"路径不可达: {solvent_vessel}{target_vessel}", ""))
raise ValueError(f"从溶剂容器 '{solvent_vessel}' 到目标容器 '{target_vessel}' 没有可用路径")
# 4. 使用pump_protocol转移溶剂
action_sequence.append(action_log("开始溶剂转移操作...", "🚰"))
action_sequence.append(action_log(f"转移: {solvent_vessel}{target_vessel} ({volume}mL)", "🚛"))
debug_print("🔍 步骤4: 转移溶剂...")
action_sequence.append(create_action_log("开始溶剂转移操作...", "🚰"))
debug_print(f"🚛 开始转移: {solvent_vessel}{target_vessel}")
debug_print(f"💧 转移体积: {volume} mL")
action_sequence.append(create_action_log(f"转移: {solvent_vessel}{target_vessel} ({volume}mL)", "🚛"))
try:
action_sequence.append(action_log("正在生成泵送协议...", "🔄"))
debug_print("🔄 生成泵送协议...")
action_sequence.append(create_action_log("正在生成泵送协议...", "🔄"))
pump_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=solvent_vessel,
@@ -90,34 +256,41 @@ def generate_reset_handling_protocol(
amount="",
time=0.0,
viscous=False,
rinsing_solvent="",
rinsing_solvent="", # 重置处理不需要清洗
rinsing_volume=0.0,
rinsing_repeats=0,
solid=False,
flowrate=2.5,
transfer_flowrate=0.5
flowrate=2.5, # 正常流速
transfer_flowrate=0.5 # 正常转移流速
)
action_sequence.extend(pump_actions)
debug_print(f"泵送协议已添加: {len(pump_actions)} 个动作")
action_sequence.append(action_log(f"泵送协议完成 ({len(pump_actions)} 个操作)", ""))
debug_print(f"泵送协议已添加: {len(pump_actions)} 个动作")
action_sequence.append(create_action_log(f"泵送协议完成 ({len(pump_actions)} 个操作)", ""))
except Exception as e:
action_sequence.append(action_log(f"泵送协议生成失败: {str(e)}", ""))
debug_print(f"泵送协议生成失败: {str(e)}")
action_sequence.append(create_action_log(f"泵送协议生成失败: {str(e)}", ""))
raise ValueError(f"生成泵协议时出错: {str(e)}")
# 5. 等待溶剂稳定
action_sequence.append(action_log("等待溶剂稳定...", ""))
original_wait_time = 10.0
simulation_time_limit = 5.0
debug_print("🔍 步骤5: 等待溶剂稳定...")
action_sequence.append(create_action_log("等待溶剂稳定...", ""))
# 模拟运行时间优化
debug_print("⏱️ 检查模拟运行时间限制...")
original_wait_time = 10.0 # 原始等待时间
simulation_time_limit = 5.0 # 模拟运行时间限制5秒
final_wait_time = min(original_wait_time, simulation_time_limit)
if original_wait_time > simulation_time_limit:
action_sequence.append(action_log(f"时间优化: {original_wait_time}s → {final_wait_time}s", ""))
debug_print(f"🎮 模拟运行优化: {original_wait_time}s → {final_wait_time}s")
action_sequence.append(create_action_log(f"时间优化: {original_wait_time}s → {final_wait_time}s", ""))
else:
action_sequence.append(action_log(f"等待时间: {final_wait_time}s", ""))
debug_print(f"✅ 时间在限制内: {final_wait_time}s 保持不变")
action_sequence.append(create_action_log(f"等待时间: {final_wait_time}s", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
@@ -125,50 +298,90 @@ def generate_reset_handling_protocol(
"description": f"等待溶剂 {solvent} 在容器 {target_vessel} 中稳定" + (f" (模拟时间)" if original_wait_time != final_wait_time else "")
}
})
debug_print(f"✅ 稳定等待已添加: {final_wait_time}s")
# 显示时间调整信息
if original_wait_time != final_wait_time:
action_sequence.append(action_log("应用模拟时间优化", "🎭"))
debug_print(f"🎭 模拟优化说明: 原计划 {original_wait_time}s实际模拟 {final_wait_time}s")
action_sequence.append(create_action_log("应用模拟时间优化", "🎭"))
# 总结
debug_print(f"重置处理协议生成完成: {len(action_sequence)} 个动作, {solvent_vessel} -> {target_vessel}, {volume}mL")
debug_print("=" * 60)
debug_print(f"🎉 重置处理协议生成完成!")
debug_print(f"📊 总结信息:")
debug_print(f" 📋 总动作数: {len(action_sequence)}")
debug_print(f" 🧪 溶剂: {solvent}")
debug_print(f" 🥽 源容器: {solvent_vessel}")
debug_print(f" 🥽 目标容器: {target_vessel} {'(默认)' if vessel is None else '(指定)'}")
debug_print(f" 💧 转移体积: {volume} mL")
debug_print(f" ⏱️ 预计总时间: {(final_wait_time + 5):.0f}")
debug_print(f" 🎯 操作结果: 已添加 {volume} mL {solvent}{target_vessel}")
debug_print("=" * 60)
# 添加完成日志
summary_msg = f"重置处理完成: {target_vessel} (使用 {volume}mL {solvent})"
if vessel is None:
summary_msg += " [默认容器]"
else:
summary_msg += " [指定容器]"
action_sequence.append(action_log(summary_msg, "🎉"))
action_sequence.append(create_action_log(summary_msg, "🎉"))
return action_sequence
# === 便捷函数 ===
def reset_main_reactor(G: nx.DiGraph, solvent: str = "methanol", **kwargs) -> List[Dict[str, Any]]:
"""重置主反应器 (默认行为)"""
debug_print(f"🔄 重置主反应器,使用溶剂: {solvent}")
return generate_reset_handling_protocol(G, solvent=solvent, vessel=None, **kwargs)
def reset_custom_vessel(G: nx.DiGraph, vessel: str, solvent: str = "methanol", **kwargs) -> List[Dict[str, Any]]:
"""重置指定容器"""
debug_print(f"🔄 重置指定容器: {vessel},使用溶剂: {solvent}")
return generate_reset_handling_protocol(G, solvent=solvent, vessel=vessel, **kwargs)
def reset_with_water(G: nx.DiGraph, vessel: Optional[str] = None, **kwargs) -> List[Dict[str, Any]]:
"""使用水重置容器"""
target = vessel or "main_reactor"
debug_print(f"💧 使用水重置容器: {target}")
return generate_reset_handling_protocol(G, solvent="water", vessel=vessel, **kwargs)
def reset_with_methanol(G: nx.DiGraph, vessel: Optional[str] = None, **kwargs) -> List[Dict[str, Any]]:
"""使用甲醇重置容器"""
target = vessel or "main_reactor"
debug_print(f"🧪 使用甲醇重置容器: {target}")
return generate_reset_handling_protocol(G, solvent="methanol", vessel=vessel, **kwargs)
def reset_with_ethanol(G: nx.DiGraph, vessel: Optional[str] = None, **kwargs) -> List[Dict[str, Any]]:
"""使用乙醇重置容器"""
target = vessel or "main_reactor"
debug_print(f"🧪 使用乙醇重置容器: {target}")
return generate_reset_handling_protocol(G, solvent="ethanol", vessel=vessel, **kwargs)
# 测试函数
def test_reset_handling_protocol():
"""测试重置处理协议"""
debug_print("=== 重置处理协议测试 ===")
debug_print("测试完成")
debug_print("=== 重置处理协议增强中文版测试 ===")
# 测试溶剂名称
debug_print("🧪 测试常用溶剂名称...")
test_solvents = ["methanol", "ethanol", "water", "acetone", "dmso"]
for solvent in test_solvents:
debug_print(f" 🔍 测试溶剂: {solvent}")
# 测试容器参数
debug_print("🥽 测试容器参数...")
test_cases = [
{"solvent": "methanol", "vessel": None, "desc": "默认容器"},
{"solvent": "ethanol", "vessel": "reactor_2", "desc": "指定容器"},
{"solvent": "water", "vessel": "flask_1", "desc": "自定义容器"}
]
for case in test_cases:
debug_print(f" 🧪 测试案例: {case['desc']} - {case['solvent']} -> {case['vessel'] or 'main_reactor'}")
debug_print("✅ 测试完成")
if __name__ == "__main__":
test_reset_handling_protocol()
test_reset_handling_protocol()

View File

@@ -2,54 +2,60 @@ from typing import List, Dict, Any, Union
import networkx as nx
import logging
import re
from .utils.vessel_parser import get_vessel, find_solvent_vessel
from .utils.resource_helper import get_resource_id, get_resource_data, get_resource_liquid_volume, update_vessel_volume
from .utils.logger_util import debug_print
from .utils.vessel_parser import get_vessel
from .pump_protocol import generate_pump_protocol_with_rinsing
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[RUN_COLUMN] {message}")
def parse_percentage(pct_str: str) -> float:
"""
解析百分比字符串为数值
Args:
pct_str: 百分比字符串(如 "40 %", "40%", "40"
Returns:
float: 百分比数值0-100
"""
if not pct_str or not pct_str.strip():
return 0.0
pct_str = pct_str.strip().lower()
debug_print(f"🔍 解析百分比: '{pct_str}'")
# 移除百分号和空格
pct_clean = re.sub(r'[%\s]', '', pct_str)
# 提取数字
match = re.search(r'([0-9]*\.?[0-9]+)', pct_clean)
if match:
value = float(match.group(1))
debug_print(f"✅ 百分比解析结果: {value}%")
return value
debug_print(f"无法解析百分比: '{pct_str}'返回0.0")
debug_print(f"⚠️ 无法解析百分比: '{pct_str}'返回0.0")
return 0.0
def parse_ratio(ratio_str: str) -> tuple:
"""
解析比例字符串为两个数值
Args:
ratio_str: 比例字符串(如 "5:95", "1:1", "40:60"
Returns:
tuple: (ratio1, ratio2) 两个比例值(百分比)
tuple: (ratio1, ratio2) 两个比例值
"""
if not ratio_str or not ratio_str.strip():
return (50.0, 50.0)
return (50.0, 50.0) # 默认1:1
ratio_str = ratio_str.strip()
debug_print(f"🔍 解析比例: '{ratio_str}'")
# 支持多种分隔符:: / -
if ':' in ratio_str:
parts = ratio_str.split(':')
@@ -60,82 +66,101 @@ def parse_ratio(ratio_str: str) -> tuple:
elif 'to' in ratio_str.lower():
parts = ratio_str.lower().split('to')
else:
debug_print(f"无法解析比例格式: '{ratio_str}'使用默认1:1")
debug_print(f"⚠️ 无法解析比例格式: '{ratio_str}'使用默认1:1")
return (50.0, 50.0)
if len(parts) >= 2:
try:
ratio1 = float(parts[0].strip())
ratio2 = float(parts[1].strip())
total = ratio1 + ratio2
# 转换为百分比
pct1 = (ratio1 / total) * 100
pct2 = (ratio2 / total) * 100
debug_print(f"✅ 比例解析结果: {ratio1}:{ratio2} -> {pct1:.1f}%:{pct2:.1f}%")
return (pct1, pct2)
except ValueError as e:
debug_print(f"比例数值转换失败: {str(e)}")
debug_print(f"比例解析失败使用默认1:1")
debug_print(f"⚠️ 比例数值转换失败: {str(e)}")
debug_print(f"⚠️ 比例解析失败使用默认1:1")
return (50.0, 50.0)
def parse_rf_value(rf_str: str) -> float:
"""
解析Rf值字符串
Args:
rf_str: Rf值字符串"0.3", "0.45", "?"
Returns:
float: Rf值0-1
"""
if not rf_str or not rf_str.strip():
return 0.3
return 0.3 # 默认Rf值
rf_str = rf_str.strip().lower()
debug_print(f"🔍 解析Rf值: '{rf_str}'")
# 处理未知Rf值
if rf_str in ['?', 'unknown', 'tbd', 'to be determined']:
return 0.3
default_rf = 0.3
debug_print(f"❓ 检测到未知Rf值使用默认值: {default_rf}")
return default_rf
# 提取数字
match = re.search(r'([0-9]*\.?[0-9]+)', rf_str)
if match:
value = float(match.group(1))
# 确保Rf值在0-1范围内
if value > 1.0:
value = value / 100.0
value = max(0.0, min(1.0, value))
value = value / 100.0 # 可能是百分比形式
value = max(0.0, min(1.0, value)) # 限制在0-1范围
debug_print(f"✅ Rf值解析结果: {value}")
return value
debug_print(f"⚠️ 无法解析Rf值: '{rf_str}'使用默认值0.3")
return 0.3
def find_column_device(G: nx.DiGraph) -> str:
"""查找柱层析设备"""
debug_print("🔍 查找柱层析设备...")
# 查找虚拟柱设备
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if 'virtual_column' in node_class.lower() or 'column' in node_class.lower():
debug_print(f"找到柱层析设备: {node}")
debug_print(f"🎉 找到柱层析设备: {node}")
return node
# 如果没有找到,尝试创建虚拟设备名称
possible_names = ['column_1', 'virtual_column_1', 'chromatography_column_1']
for name in possible_names:
if name in G.nodes():
debug_print(f"找到柱设备: {name}")
debug_print(f"🎉 找到柱设备: {name}")
return name
debug_print("未找到柱层析设备将使用pump protocol直接转移")
debug_print("⚠️ 未找到柱层析设备将使用pump protocol直接转移")
return ""
def find_column_vessel(G: nx.DiGraph, column: str) -> str:
"""查找柱容器"""
debug_print(f"🔍 查找柱容器: '{column}'")
# 直接检查column参数是否是容器
if column in G.nodes():
node_type = G.nodes[column].get('type', '')
if node_type == 'container':
debug_print(f"🎉 找到柱容器: {column}")
return column
# 尝试常见的命名规则
possible_names = [
f"column_{column}",
f"{column}_column",
f"{column}_column",
f"vessel_{column}",
f"{column}_vessel",
"column_vessel",
@@ -144,25 +169,211 @@ def find_column_vessel(G: nx.DiGraph, column: str) -> str:
"preparative_column",
"column"
]
for vessel_name in possible_names:
if vessel_name in G.nodes():
node_type = G.nodes[vessel_name].get('type', '')
if node_type == 'container':
debug_print(f"🎉 找到柱容器: {vessel_name}")
return vessel_name
debug_print(f"⚠️ 未找到柱容器,将直接在源容器中进行分离")
return ""
def find_solvent_vessel(G: nx.DiGraph, solvent: str) -> str:
"""查找溶剂容器 - 增强版"""
if not solvent or not solvent.strip():
return ""
solvent = solvent.strip().replace(' ', '_').lower()
debug_print(f"🔍 查找溶剂容器: '{solvent}'")
# 🔧 方法1直接搜索 data.reagent_name
for node in G.nodes():
node_data = G.nodes[node].get('data', {})
node_type = G.nodes[node].get('type', '')
# 只搜索容器类型的节点
if node_type == 'container':
reagent_name = node_data.get('reagent_name', '').lower()
reagent_config = G.nodes[node].get('config', {}).get('reagent', '').lower()
# 检查 data.reagent_name 和 config.reagent
if reagent_name == solvent or reagent_config == solvent:
debug_print(f"🎉 通过reagent_name找到溶剂容器: {node} (reagent: {reagent_name or reagent_config}) ✨")
return node
# 模糊匹配 reagent_name
if solvent in reagent_name or reagent_name in solvent:
debug_print(f"🎉 通过reagent_name模糊匹配到溶剂容器: {node} (reagent: {reagent_name}) ✨")
return node
if solvent in reagent_config or reagent_config in solvent:
debug_print(f"🎉 通过config.reagent模糊匹配到溶剂容器: {node} (reagent: {reagent_config}) ✨")
return node
# 🔧 方法2常见的溶剂容器命名规则
possible_names = [
f"flask_{solvent}",
f"bottle_{solvent}",
f"reagent_{solvent}",
f"{solvent}_bottle",
f"{solvent}_flask",
f"solvent_{solvent}",
f"reagent_bottle_{solvent}"
]
for vessel_name in possible_names:
if vessel_name in G.nodes():
node_type = G.nodes[vessel_name].get('type', '')
if node_type == 'container':
debug_print(f"🎉 通过命名规则找到溶剂容器: {vessel_name}")
return vessel_name
# 🔧 方法3节点名称模糊匹配
for node in G.nodes():
node_type = G.nodes[node].get('type', '')
if node_type == 'container':
if ('flask_' in node or 'bottle_' in node or 'reagent_' in node) and solvent in node.lower():
debug_print(f"🎉 通过节点名称模糊匹配到溶剂容器: {node}")
return node
# 🔧 方法4特殊溶剂名称映射
solvent_mapping = {
'dmf': ['dmf', 'dimethylformamide', 'n,n-dimethylformamide'],
'ethyl_acetate': ['ethyl_acetate', 'ethylacetate', 'etoac', 'ea'],
'hexane': ['hexane', 'hexanes', 'n-hexane'],
'methanol': ['methanol', 'meoh', 'ch3oh'],
'water': ['water', 'h2o', 'distilled_water'],
'acetone': ['acetone', 'ch3coch3', '2-propanone'],
'dichloromethane': ['dichloromethane', 'dcm', 'ch2cl2', 'methylene_chloride'],
'chloroform': ['chloroform', 'chcl3', 'trichloromethane']
}
# 查找映射的同义词
for canonical_name, synonyms in solvent_mapping.items():
if solvent in synonyms:
debug_print(f"🔍 检测到溶剂同义词: '{solvent}' -> '{canonical_name}'")
return find_solvent_vessel(G, canonical_name) # 递归搜索
debug_print(f"⚠️ 未找到溶剂 '{solvent}' 的容器")
return ""
def get_vessel_liquid_volume(vessel: dict) -> float:
"""
获取容器中的液体体积 - 支持vessel字典
Args:
vessel: 容器字典
Returns:
float: 液体体积mL
"""
if not vessel or "data" not in vessel:
debug_print(f"⚠️ 容器数据为空,返回 0.0mL")
return 0.0
vessel_data = vessel["data"]
vessel_id = vessel.get("id", "unknown")
debug_print(f"🔍 读取容器 '{vessel_id}' 体积数据: {vessel_data}")
# 检查liquid_volume字段
if "liquid_volume" in vessel_data:
liquid_volume = vessel_data["liquid_volume"]
# 处理列表格式
if isinstance(liquid_volume, list):
if len(liquid_volume) > 0:
volume = liquid_volume[0]
if isinstance(volume, (int, float)):
debug_print(f"✅ 容器 '{vessel_id}' 体积: {volume}mL (列表格式)")
return float(volume)
# 处理直接数值格式
elif isinstance(liquid_volume, (int, float)):
debug_print(f"✅ 容器 '{vessel_id}' 体积: {liquid_volume}mL (数值格式)")
return float(liquid_volume)
# 检查其他可能的体积字段
volume_keys = ['current_volume', 'total_volume', 'volume']
for key in volume_keys:
if key in vessel_data:
try:
volume = float(vessel_data[key])
if volume > 0:
debug_print(f"✅ 容器 '{vessel_id}' 体积: {volume}mL (字段: {key})")
return volume
except (ValueError, TypeError):
continue
debug_print(f"⚠️ 无法获取容器 '{vessel_id}' 的体积,返回默认值 50.0mL")
return 50.0
def update_vessel_volume(vessel: dict, G: nx.DiGraph, new_volume: float, description: str = "") -> None:
"""
更新容器体积同时更新vessel字典和图节点
Args:
vessel: 容器字典
G: 网络图
new_volume: 新体积
description: 更新描述
"""
vessel_id = vessel.get("id", "unknown")
if description:
debug_print(f"🔧 更新容器体积 - {description}")
# 更新vessel字典中的体积
if "data" in vessel:
if "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
if len(current_volume) > 0:
vessel["data"]["liquid_volume"][0] = new_volume
else:
vessel["data"]["liquid_volume"] = [new_volume]
else:
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"] = {"liquid_volume": new_volume}
# 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = new_volume
else:
G.nodes[vessel_id]['data']['liquid_volume'] = [new_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = new_volume
debug_print(f"📊 容器 '{vessel_id}' 体积已更新为: {new_volume:.2f}mL")
def calculate_solvent_volumes(total_volume: float, pct1: float, pct2: float) -> tuple:
"""根据百分比计算溶剂体积"""
volume1 = (total_volume * pct1) / 100.0
volume2 = (total_volume * pct2) / 100.0
debug_print(f"🧮 溶剂体积计算: 总体积{total_volume}mL")
debug_print(f" - 溶剂1: {pct1}% = {volume1}mL")
debug_print(f" - 溶剂2: {pct2}% = {volume2}mL")
return (volume1, volume2)
def generate_run_column_protocol(
G: nx.DiGraph,
from_vessel: dict,
to_vessel: dict,
from_vessel: dict, # 🔧 修改:从字符串改为字典类型
to_vessel: dict, # 🔧 修改:从字符串改为字典类型
column: str,
rf: str = "",
pct1: str = "",
@@ -174,7 +385,7 @@ def generate_run_column_protocol(
) -> List[Dict[str, Any]]:
"""
生成柱层析分离的协议序列 - 支持vessel字典和体积运算
Args:
G: 有向图,节点为设备和容器,边为流体管道
from_vessel: 源容器字典从XDL传入
@@ -187,112 +398,173 @@ def generate_run_column_protocol(
solvent2: 第二种溶剂名称(可选)
ratio: 溶剂比例(如 "5:95"可选优先级高于pct1/pct2
**kwargs: 其他可选参数
Returns:
List[Dict[str, Any]]: 柱层析分离操作的动作序列
"""
# 🔧 核心修改从字典中提取容器ID
from_vessel_id, _ = get_vessel(from_vessel)
to_vessel_id, _ = get_vessel(to_vessel)
debug_print(f"开始生成柱层析协议: {from_vessel_id} -> {to_vessel_id}, column={column}")
debug_print("🏛️" * 20)
debug_print("🚀 开始生成柱层析协议支持vessel字典和体积运算")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 from_vessel: {from_vessel} (ID: {from_vessel_id})")
debug_print(f" 🥽 to_vessel: {to_vessel} (ID: {to_vessel_id})")
debug_print(f" 🏛️ column: '{column}'")
debug_print(f" 📊 rf: '{rf}'")
debug_print(f" 🧪 溶剂配比: pct1='{pct1}', pct2='{pct2}', ratio='{ratio}'")
debug_print(f" 🧪 溶剂名称: solvent1='{solvent1}', solvent2='{solvent2}'")
debug_print("🏛️" * 20)
action_sequence = []
# 记录柱层析前的容器状态
original_from_volume = get_resource_liquid_volume(from_vessel)
original_to_volume = get_resource_liquid_volume(to_vessel)
# 🔧 新增:记录柱层析前的容器状态
debug_print("🔍 记录柱层析前容器状态...")
original_from_volume = get_vessel_liquid_volume(from_vessel)
original_to_volume = get_vessel_liquid_volume(to_vessel)
debug_print(f"📊 柱层析前状态:")
debug_print(f" - 源容器 {from_vessel_id}: {original_from_volume:.2f}mL")
debug_print(f" - 目标容器 {to_vessel_id}: {original_to_volume:.2f}mL")
# === 参数验证 ===
if not from_vessel_id:
debug_print("📍 步骤1: 参数验证...")
if not from_vessel_id: # 🔧 使用 from_vessel_id
raise ValueError("from_vessel 参数不能为空")
if not to_vessel_id:
if not to_vessel_id: # 🔧 使用 to_vessel_id
raise ValueError("to_vessel 参数不能为空")
if not column:
raise ValueError("column 参数不能为空")
if from_vessel_id not in G.nodes():
if from_vessel_id not in G.nodes(): # 🔧 使用 from_vessel_id
raise ValueError(f"源容器 '{from_vessel_id}' 不存在于系统中")
if to_vessel_id not in G.nodes():
if to_vessel_id not in G.nodes(): # 🔧 使用 to_vessel_id
raise ValueError(f"目标容器 '{to_vessel_id}' 不存在于系统中")
debug_print("✅ 基本参数验证通过")
# === 参数解析 ===
debug_print("📍 步骤2: 参数解析...")
# 解析Rf值
final_rf = parse_rf_value(rf)
debug_print(f"🎯 最终Rf值: {final_rf}")
# 解析溶剂比例ratio优先级高于pct1/pct2
if ratio and ratio.strip():
final_pct1, final_pct2 = parse_ratio(ratio)
debug_print(f"📊 使用ratio参数: {final_pct1:.1f}% : {final_pct2:.1f}%")
else:
final_pct1 = parse_percentage(pct1) if pct1 else 50.0
final_pct2 = parse_percentage(pct2) if pct2 else 50.0
# 如果百分比和不是100%,进行归一化
total_pct = final_pct1 + final_pct2
if total_pct == 0:
final_pct1, final_pct2 = 50.0, 50.0
elif total_pct != 100.0:
final_pct1 = (final_pct1 / total_pct) * 100
final_pct2 = (final_pct2 / total_pct) * 100
debug_print(f"📊 使用百分比参数: {final_pct1:.1f}% : {final_pct2:.1f}%")
# 设置默认溶剂(如果未指定)
final_solvent1 = solvent1.strip() if solvent1 else "ethyl_acetate"
final_solvent2 = solvent2.strip() if solvent2 else "hexane"
debug_print(f"参数: rf={final_rf}, 溶剂={final_solvent1}:{final_solvent2} = {final_pct1:.1f}%:{final_pct2:.1f}%")
debug_print(f"🧪 最终溶剂: {final_solvent1} : {final_solvent2}")
# === 查找设备和容器 ===
debug_print("📍 步骤3: 查找设备和容器...")
# 查找柱层析设备
column_device_id = find_column_device(G)
# 查找柱容器
column_vessel = find_column_vessel(G, column)
# 查找溶剂容器
solvent1_vessel = find_solvent_vessel(G, final_solvent1)
solvent2_vessel = find_solvent_vessel(G, final_solvent2)
debug_print(f"🔧 设备映射:")
debug_print(f" - 柱设备: '{column_device_id}'")
debug_print(f" - 柱容器: '{column_vessel}'")
debug_print(f" - 溶剂1容器: '{solvent1_vessel}'")
debug_print(f" - 溶剂2容器: '{solvent2_vessel}'")
# === 获取源容器体积 ===
debug_print("📍 步骤4: 获取源容器体积...")
source_volume = original_from_volume
if source_volume <= 0:
source_volume = 50.0
source_volume = 50.0 # 默认体积
debug_print(f"⚠️ 无法获取源容器体积,使用默认值: {source_volume}mL")
else:
debug_print(f"✅ 源容器体积: {source_volume}mL")
# === 计算溶剂体积 ===
debug_print("📍 步骤5: 计算溶剂体积...")
# 洗脱溶剂通常是样品体积的2-5倍
total_elution_volume = source_volume * 3.0
solvent1_volume, solvent2_volume = calculate_solvent_volumes(
total_elution_volume, final_pct1, final_pct2
)
# === 执行柱层析流程 ===
debug_print("📍 步骤6: 执行柱层析流程...")
# 🔧 新增:体积变化跟踪变量
current_from_volume = source_volume
current_to_volume = original_to_volume
current_column_volume = 0.0
try:
# 步骤1: 样品上柱
if column_vessel and column_vessel != from_vessel_id:
# 步骤6.1: 样品上柱(如果有独立的柱容器)
if column_vessel and column_vessel != from_vessel_id: # 🔧 使用 from_vessel_id
debug_print(f"📍 6.1: 样品上柱 - {source_volume}mL 从 {from_vessel_id}{column_vessel}")
try:
sample_transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=from_vessel_id,
from_vessel=from_vessel_id, # 🔧 使用 from_vessel_id
to_vessel=column_vessel,
volume=source_volume,
flowrate=1.0,
flowrate=1.0, # 慢速上柱
transfer_flowrate=0.5,
rinsing_solvent="",
rinsing_solvent="", # 暂不冲洗
rinsing_volume=0.0,
rinsing_repeats=0
)
action_sequence.extend(sample_transfer_actions)
current_from_volume = 0.0
current_column_volume = source_volume
debug_print(f"✅ 样品上柱完成,添加了 {len(sample_transfer_actions)} 个动作")
# 🔧 新增:更新体积 - 样品转移到柱上
current_from_volume = 0.0 # 源容器体积变为0
current_column_volume = source_volume # 柱容器体积增加
update_vessel_volume(from_vessel, G, current_from_volume, "样品上柱后,源容器清空")
# 如果柱容器在图中,也更新其体积
if column_vessel in G.nodes():
if 'data' not in G.nodes[column_vessel]:
G.nodes[column_vessel]['data'] = {}
G.nodes[column_vessel]['data']['liquid_volume'] = current_column_volume
debug_print(f"📊 柱容器 '{column_vessel}' 体积更新为: {current_column_volume:.2f}mL")
except Exception as e:
debug_print(f"样品上柱失败: {str(e)}")
# 步骤2: 添加洗脱溶剂1
debug_print(f"⚠️ 样品上柱失败: {str(e)}")
# 步骤6.2: 添加洗脱溶剂1(如果有溶剂容器)
if solvent1_vessel and solvent1_volume > 0:
debug_print(f"📍 6.2: 添加洗脱溶剂1 - {solvent1_volume:.1f}mL {final_solvent1}")
try:
target_vessel = column_vessel if column_vessel else from_vessel_id
target_vessel = column_vessel if column_vessel else from_vessel_id # 🔧 使用 from_vessel_id
solvent1_transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=solvent1_vessel,
@@ -302,22 +574,27 @@ def generate_run_column_protocol(
transfer_flowrate=1.0
)
action_sequence.extend(solvent1_transfer_actions)
debug_print(f"✅ 溶剂1添加完成添加了 {len(solvent1_transfer_actions)} 个动作")
# 🔧 新增:更新体积 - 添加溶剂1
if target_vessel == column_vessel:
current_column_volume += solvent1_volume
if column_vessel in G.nodes():
G.nodes[column_vessel]['data']['liquid_volume'] = current_column_volume
debug_print(f"📊 柱容器体积增加: +{solvent1_volume:.2f}mL = {current_column_volume:.2f}mL")
elif target_vessel == from_vessel_id:
current_from_volume += solvent1_volume
update_vessel_volume(from_vessel, G, current_from_volume, "添加溶剂1后")
except Exception as e:
debug_print(f"溶剂1添加失败: {str(e)}")
# 步骤3: 添加洗脱溶剂2
debug_print(f"⚠️ 溶剂1添加失败: {str(e)}")
# 步骤6.3: 添加洗脱溶剂2(如果有溶剂容器)
if solvent2_vessel and solvent2_volume > 0:
debug_print(f"📍 6.3: 添加洗脱溶剂2 - {solvent2_volume:.1f}mL {final_solvent2}")
try:
target_vessel = column_vessel if column_vessel else from_vessel_id
target_vessel = column_vessel if column_vessel else from_vessel_id # 🔧 使用 from_vessel_id
solvent2_transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=solvent2_vessel,
@@ -327,26 +604,31 @@ def generate_run_column_protocol(
transfer_flowrate=1.0
)
action_sequence.extend(solvent2_transfer_actions)
debug_print(f"✅ 溶剂2添加完成添加了 {len(solvent2_transfer_actions)} 个动作")
# 🔧 新增:更新体积 - 添加溶剂2
if target_vessel == column_vessel:
current_column_volume += solvent2_volume
if column_vessel in G.nodes():
G.nodes[column_vessel]['data']['liquid_volume'] = current_column_volume
debug_print(f"📊 柱容器体积增加: +{solvent2_volume:.2f}mL = {current_column_volume:.2f}mL")
elif target_vessel == from_vessel_id:
current_from_volume += solvent2_volume
update_vessel_volume(from_vessel, G, current_from_volume, "添加溶剂2后")
except Exception as e:
debug_print(f"溶剂2添加失败: {str(e)}")
# 步骤4: 使用柱层析设备执行分离
debug_print(f"⚠️ 溶剂2添加失败: {str(e)}")
# 步骤6.4: 使用柱层析设备执行分离(如果有设备)
if column_device_id:
debug_print(f"📍 6.4: 使用柱层析设备执行分离")
column_separation_action = {
"device_id": column_device_id,
"action_name": "run_column",
"action_kwargs": {
"from_vessel": from_vessel_id,
"to_vessel": to_vessel_id,
"from_vessel": from_vessel_id, # 🔧 使用 from_vessel_id
"to_vessel": to_vessel_id, # 🔧 使用 to_vessel_id
"column": column,
"rf": rf,
"pct1": pct1,
@@ -357,65 +639,85 @@ def generate_run_column_protocol(
}
}
action_sequence.append(column_separation_action)
separation_time = max(30, min(120, int(total_elution_volume / 2)))
debug_print(f"✅ 柱层析设备动作已添加")
# 等待分离完成
separation_time = max(30, min(120, int(total_elution_volume / 2))) # 30-120秒基于体积
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": separation_time}
})
# 步骤5: 产物收集
if column_vessel and column_vessel != to_vessel_id:
debug_print(f"✅ 等待分离完成: {separation_time}")
# 步骤6.5: 产物收集(从柱容器到目标容器)
if column_vessel and column_vessel != to_vessel_id: # 🔧 使用 to_vessel_id
debug_print(f"📍 6.5: 产物收集 - 从 {column_vessel}{to_vessel_id}")
try:
# 估算产物体积原始样品体积的70-90%,收率考虑)
product_volume = source_volume * 0.8
product_transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=column_vessel,
to_vessel=to_vessel_id,
to_vessel=to_vessel_id, # 🔧 使用 to_vessel_id
volume=product_volume,
flowrate=1.5,
transfer_flowrate=0.8
)
action_sequence.extend(product_transfer_actions)
debug_print(f"✅ 产物收集完成,添加了 {len(product_transfer_actions)} 个动作")
# 🔧 新增:更新体积 - 产物收集到目标容器
current_to_volume += product_volume
current_column_volume -= product_volume
current_column_volume -= product_volume # 柱容器体积减少
update_vessel_volume(to_vessel, G, current_to_volume, "产物收集后")
# 更新柱容器体积
if column_vessel in G.nodes():
G.nodes[column_vessel]['data']['liquid_volume'] = max(0.0, current_column_volume)
debug_print(f"📊 柱容器体积减少: -{product_volume:.2f}mL = {current_column_volume:.2f}mL")
except Exception as e:
debug_print(f"产物收集失败: {str(e)}")
# 步骤6: 简化模式 - 直接转移
debug_print(f"⚠️ 产物收集失败: {str(e)}")
# 步骤6.6: 如果没有独立的柱设备和容器,执行简化的直接转移
if not column_device_id and not column_vessel:
debug_print(f"📍 6.6: 简化模式 - 直接转移 {source_volume}mL 从 {from_vessel_id}{to_vessel_id}")
try:
direct_transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=from_vessel_id,
to_vessel=to_vessel_id,
from_vessel=from_vessel_id, # 🔧 使用 from_vessel_id
to_vessel=to_vessel_id, # 🔧 使用 to_vessel_id
volume=source_volume,
flowrate=2.0,
transfer_flowrate=1.0
)
action_sequence.extend(direct_transfer_actions)
current_from_volume = 0.0
current_to_volume += source_volume
debug_print(f"✅ 直接转移完成,添加了 {len(direct_transfer_actions)} 个动作")
# 🔧 新增:更新体积 - 直接转移
current_from_volume = 0.0 # 源容器清空
current_to_volume += source_volume # 目标容器增加
update_vessel_volume(from_vessel, G, current_from_volume, "直接转移后,源容器清空")
update_vessel_volume(to_vessel, G, current_to_volume, "直接转移后,目标容器增加")
except Exception as e:
debug_print(f"直接转移失败: {str(e)}")
debug_print(f"⚠️ 直接转移失败: {str(e)}")
except Exception as e:
debug_print(f"协议生成失败: {str(e)}")
debug_print(f"协议生成失败: {str(e)} 😭")
# 不添加不确定的动作直接让action_sequence保持为空列表
# action_sequence 已经在函数开始时初始化为 []
# 确保至少有一个有效的动作,如果完全失败就返回空列表
if not action_sequence:
debug_print("⚠️ 没有生成任何有效动作")
# 可以选择返回空列表或添加一个基本的等待动作
action_sequence.append({
"action_name": "wait",
"action_kwargs": {
@@ -423,50 +725,83 @@ def generate_run_column_protocol(
"description": "柱层析协议执行完成"
}
})
final_from_volume = get_resource_liquid_volume(from_vessel)
final_to_volume = get_resource_liquid_volume(to_vessel)
debug_print(f"柱层析协议生成完成: {len(action_sequence)} 个动作, {from_vessel_id} -> {to_vessel_id}, 收集={final_to_volume - original_to_volume:.2f}mL")
# 🔧 新增:柱层析完成后的最终状态报告
final_from_volume = get_vessel_liquid_volume(from_vessel)
final_to_volume = get_vessel_liquid_volume(to_vessel)
# 🎊 总结
debug_print("🏛️" * 20)
debug_print(f"🎉 柱层析协议生成完成! ✨")
debug_print(f"📊 总动作数: {len(action_sequence)}")
debug_print(f"🥽 路径: {from_vessel_id}{to_vessel_id}")
debug_print(f"🏛️ 柱子: {column}")
debug_print(f"🧪 溶剂: {final_solvent1}:{final_solvent2} = {final_pct1:.1f}%:{final_pct2:.1f}%")
debug_print(f"📊 体积变化统计:")
debug_print(f" 源容器 {from_vessel_id}:")
debug_print(f" - 柱层析前: {original_from_volume:.2f}mL")
debug_print(f" - 柱层析后: {final_from_volume:.2f}mL")
debug_print(f" 目标容器 {to_vessel_id}:")
debug_print(f" - 柱层析前: {original_to_volume:.2f}mL")
debug_print(f" - 柱层析后: {final_to_volume:.2f}mL")
debug_print(f" - 收集体积: {final_to_volume - original_to_volume:.2f}mL")
debug_print(f"⏱️ 预计总时间: {len(action_sequence) * 5:.0f} 秒 ⌛")
debug_print("🏛️" * 20)
return action_sequence
# 便捷函数
def generate_ethyl_acetate_hexane_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
# 🔧 新增:便捷函数
def generate_ethyl_acetate_hexane_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
column: str, ratio: str = "30:70") -> List[Dict[str, Any]]:
"""乙酸乙酯-己烷柱层析(常用组合)"""
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
from_vessel_id = from_vessel["id"]
to_vessel_id = to_vessel["id"]
debug_print(f"🧪⛽ 乙酸乙酯-己烷柱层析: {from_vessel_id}{to_vessel_id} @ {ratio}")
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
solvent1="ethyl_acetate", solvent2="hexane", ratio=ratio)
def generate_methanol_dcm_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
def generate_methanol_dcm_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
column: str, ratio: str = "5:95") -> List[Dict[str, Any]]:
"""甲醇-二氯甲烷柱层析"""
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
from_vessel_id = from_vessel["id"]
to_vessel_id = to_vessel["id"]
debug_print(f"🧪🧪 甲醇-DCM柱层析: {from_vessel_id}{to_vessel_id} @ {ratio}")
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
solvent1="methanol", solvent2="dichloromethane", ratio=ratio)
def generate_gradient_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
column: str, start_ratio: str = "10:90",
def generate_gradient_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
column: str, start_ratio: str = "10:90",
end_ratio: str = "50:50") -> List[Dict[str, Any]]:
"""梯度洗脱柱层析(中等比例)"""
from_vessel_id, _ = get_vessel(from_vessel)
to_vessel_id, _ = get_vessel(to_vessel)
debug_print(f"📈 梯度柱层析: {from_vessel_id}{to_vessel_id} ({start_ratio}{end_ratio})")
# 使用中间比例作为近似
return generate_run_column_protocol(G, from_vessel, to_vessel, column, ratio="30:70")
def generate_polar_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
def generate_polar_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
column: str) -> List[Dict[str, Any]]:
"""极性化合物柱层析(高极性溶剂比例)"""
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
from_vessel_id, _ = get_vessel(from_vessel)
to_vessel_id, _ = get_vessel(to_vessel)
debug_print(f"⚡ 极性化合物柱层析: {from_vessel_id}{to_vessel_id}")
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
solvent1="ethyl_acetate", solvent2="hexane", ratio="70:30")
def generate_nonpolar_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
def generate_nonpolar_column_protocol(G: nx.DiGraph, from_vessel: dict, to_vessel: dict,
column: str) -> List[Dict[str, Any]]:
"""非极性化合物柱层析(低极性溶剂比例)"""
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
from_vessel_id, _ = get_vessel(from_vessel)
to_vessel_id, _ = get_vessel(to_vessel)
debug_print(f"🛢️ 非极性化合物柱层析: {from_vessel_id}{to_vessel_id}")
return generate_run_column_protocol(G, from_vessel, to_vessel, column,
solvent1="ethyl_acetate", solvent2="hexane", ratio="5:95")
# 测试函数
def test_run_column_protocol():
"""测试柱层析协议"""
debug_print("=== RUN COLUMN PROTOCOL 测试 ===")
debug_print("测试完成")
debug_print("🧪 === RUN COLUMN PROTOCOL 测试 ===")
debug_print("测试完成 🎉")
if __name__ == "__main__":
test_run_column_protocol()

View File

@@ -1,11 +1,41 @@
from functools import partial
import networkx as nx
import re
import logging
import sys
from typing import List, Dict, Any, Union
from .utils.vessel_parser import get_vessel, find_solvent_vessel, find_connected_stirrer
from .utils.resource_helper import get_resource_liquid_volume, update_vessel_volume
from .utils.logger_util import debug_print, action_log
from .utils.unit_parser import parse_volume_input
from .utils.vessel_parser import get_vessel
from .utils.logger_util import action_log
from .pump_protocol import generate_pump_protocol_with_rinsing
logger = logging.getLogger(__name__)
# 确保输出编码为UTF-8
if hasattr(sys.stdout, 'reconfigure'):
try:
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
except:
pass
def debug_print(message):
"""调试输出函数 - 支持中文"""
try:
# 确保消息是字符串格式
safe_message = str(message)
logger.info(f"[SEPARATE] {safe_message}")
except UnicodeEncodeError:
# 如果编码失败,尝试替换不支持的字符
safe_message = str(message).encode('utf-8', errors='replace').decode('utf-8')
logger.info(f"[SEPARATE] {safe_message}")
except Exception as e:
# 最后的安全措施
fallback_message = f"日志输出错误: {repr(message)}"
logger.info(f"[SEPARATE] {fallback_message}")
create_action_log = partial(action_log, prefix="[SEPARATE]")
def generate_separate_protocol(
G: nx.DiGraph,
@@ -63,33 +93,45 @@ def generate_separate_protocol(
# 🔧 核心修改从字典中提取容器ID
vessel_id, vessel_data = get_vessel(vessel)
debug_print(f"开始生成分离协议: vessel={vessel_id}, purpose={purpose}, "
f"product_phase={product_phase}, solvent={solvent}, "
f"volume={volume}, repeats={repeats}")
debug_print("🌀" * 20)
debug_print("🚀 开始生成分离协议支持vessel字典和体积运算")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 vessel: {vessel} (ID: {vessel_id})")
debug_print(f" 🎯 分离目的: '{purpose}'")
debug_print(f" 📊 产物相: '{product_phase}'")
debug_print(f" 💧 溶剂: '{solvent}'")
debug_print(f" 📏 体积: {volume} (类型: {type(volume)})")
debug_print(f" 🔄 重复次数: {repeats}")
debug_print(f" 🎯 产物容器: '{product_vessel}'")
debug_print(f" 🗑️ 废液容器: '{waste_vessel}'")
debug_print(f" 📦 其他参数: {kwargs}")
debug_print("🌀" * 20)
action_sequence = []
# 记录分离前的容器状态
original_liquid_volume = get_resource_liquid_volume(vessel)
debug_print(f"分离前液体体积: {original_liquid_volume:.2f}mL")
# 🔧 新增:记录分离前的容器状态
debug_print("🔍 记录分离前容器状态...")
original_liquid_volume = get_vessel_liquid_volume(vessel)
debug_print(f"📊 分离前液体体积: {original_liquid_volume:.2f}mL")
# === 参数验证和标准化 ===
action_sequence.append(action_log(f"开始分离操作 - 容器: {vessel_id}", "🎬", prefix="[SEPARATE]"))
action_sequence.append(action_log(f"分离目的: {purpose}", "🧪", prefix="[SEPARATE]"))
action_sequence.append(action_log(f"产物相: {product_phase}", "📊", prefix="[SEPARATE]"))
debug_print("🔍 步骤1: 参数验证和标准化...")
action_sequence.append(create_action_log(f"开始分离操作 - 容器: {vessel_id}", "🎬"))
action_sequence.append(create_action_log(f"分离目的: {purpose}", "🧪"))
action_sequence.append(create_action_log(f"产物相: {product_phase}", "📊"))
# 统一容器参数 - 支持字典和字符串
final_vessel_id = vessel_id
def extract_vessel_id(vessel_param):
if isinstance(vessel_param, dict):
return vessel_param.get("id", "")
elif isinstance(vessel_param, str):
return vessel_param
else:
return ""
to_vessel_result = get_vessel(to_vessel) if to_vessel else None
if to_vessel_result is None or to_vessel_result[0] == "":
to_vessel_result = get_vessel(product_vessel) if product_vessel else None
final_to_vessel_id = to_vessel_result[0] if to_vessel_result else ""
waste_vessel_result = get_vessel(waste_phase_to_vessel) if waste_phase_to_vessel else None
if waste_vessel_result is None or waste_vessel_result[0] == "":
waste_vessel_result = get_vessel(waste_vessel) if waste_vessel else None
final_waste_vessel_id = waste_vessel_result[0] if waste_vessel_result else ""
final_vessel_id, _ = vessel_id
final_to_vessel_id, _ = get_vessel(to_vessel) or get_vessel(product_vessel)
final_waste_vessel_id, _ = get_vessel(waste_phase_to_vessel) or get_vessel(waste_vessel)
# 统一体积参数
final_volume = parse_volume_input(volume or solvent_volume)
@@ -99,12 +141,16 @@ def generate_separate_protocol(
repeats = 1
debug_print(f"⚠️ 重复次数参数 <= 0自动设置为 1")
debug_print(f"标准化参数: vessel={final_vessel_id}, to={final_to_vessel_id}, "
f"waste={final_waste_vessel_id}, volume={final_volume}mL, repeats={repeats}")
debug_print(f"🔧 标准化后的参数:")
debug_print(f" 🥼 分离容器: '{final_vessel_id}'")
debug_print(f" 🎯 产物容器: '{final_to_vessel_id}'")
debug_print(f" 🗑️ 废液容器: '{final_waste_vessel_id}'")
debug_print(f" 📏 溶剂体积: {final_volume}mL")
debug_print(f" 🔄 重复次数: {repeats}")
action_sequence.append(action_log(f"分离容器: {final_vessel_id}", "🧪", prefix="[SEPARATE]"))
action_sequence.append(action_log(f"溶剂体积: {final_volume}mL", "📏", prefix="[SEPARATE]"))
action_sequence.append(action_log(f"重复次数: {repeats}", "🔄", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"分离容器: {final_vessel_id}", "🧪"))
action_sequence.append(create_action_log(f"溶剂体积: {final_volume}mL", "📏"))
action_sequence.append(create_action_log(f"重复次数: {repeats}", "🔄"))
# 验证必需参数
if not purpose:
@@ -114,68 +160,72 @@ def generate_separate_protocol(
if purpose not in ["wash", "extract", "separate"]:
debug_print(f"⚠️ 未知的分离目的 '{purpose}',使用默认值 'separate'")
purpose = "separate"
action_sequence.append(action_log(f"未知目的,使用: {purpose}", "⚠️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"未知目的,使用: {purpose}", "⚠️"))
if product_phase not in ["top", "bottom"]:
debug_print(f"⚠️ 未知的产物相 '{product_phase}',使用默认值 'top'")
product_phase = "top"
action_sequence.append(action_log(f"未知相别,使用: {product_phase}", "⚠️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"未知相别,使用: {product_phase}", "⚠️"))
action_sequence.append(action_log("参数验证通过", "", prefix="[SEPARATE]"))
debug_print("参数验证通过")
action_sequence.append(create_action_log("参数验证通过", ""))
# === 查找设备 ===
action_sequence.append(action_log("正在查找相关设备...", "🔍", prefix="[SEPARATE]"))
debug_print("🔍 步骤2: 查找设备...")
action_sequence.append(create_action_log("正在查找相关设备...", "🔍"))
# 查找分离器设备
separator_device = find_separator_device(G, final_vessel_id)
separator_device = find_separator_device(G, final_vessel_id) # 🔧 使用 final_vessel_id
if separator_device:
action_sequence.append(action_log(f"找到分离器设备: {separator_device}", "🧪", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"找到分离器设备: {separator_device}", "🧪"))
else:
debug_print("⚠️ 未找到分离器设备,可能无法执行分离")
action_sequence.append(action_log("未找到分离器设备", "⚠️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log("未找到分离器设备", "⚠️"))
# 查找搅拌器
stirrer_device = find_connected_stirrer(G, final_vessel_id)
stirrer_device = find_connected_stirrer(G, final_vessel_id) # 🔧 使用 final_vessel_id
if stirrer_device:
action_sequence.append(action_log(f"找到搅拌器: {stirrer_device}", "🌪️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"找到搅拌器: {stirrer_device}", "🌪️"))
else:
action_sequence.append(action_log("未找到搅拌器", "⚠️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log("未找到搅拌器", "⚠️"))
# 查找溶剂容器(如果需要)
solvent_vessel = ""
if solvent and solvent.strip():
try:
solvent_vessel = find_solvent_vessel(G, solvent)
except ValueError:
solvent_vessel = ""
solvent_vessel = find_solvent_vessel(G, solvent)
if solvent_vessel:
action_sequence.append(action_log(f"找到溶剂容器: {solvent_vessel}", "💧", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"找到溶剂容器: {solvent_vessel}", "💧"))
else:
action_sequence.append(action_log(f"未找到溶剂容器: {solvent}", "⚠️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"未找到溶剂容器: {solvent}", "⚠️"))
debug_print(f"设备配置: separator={separator_device}, stirrer={stirrer_device}, solvent_vessel={solvent_vessel}")
debug_print(f"📊 设备配置:")
debug_print(f" 🧪 分离器设备: '{separator_device}'")
debug_print(f" 🌪️ 搅拌器设备: '{stirrer_device}'")
debug_print(f" 💧 溶剂容器: '{solvent_vessel}'")
# === 执行分离流程 ===
action_sequence.append(action_log("开始分离工作流程", "🎯", prefix="[SEPARATE]"))
debug_print("🔍 步骤3: 执行分离流程...")
action_sequence.append(create_action_log("开始分离工作流程", "🎯"))
# 体积变化跟踪变量
# 🔧 新增:体积变化跟踪变量
current_volume = original_liquid_volume
try:
for repeat_idx in range(repeats):
cycle_num = repeat_idx + 1
debug_print(f"分离循环 {cycle_num}/{repeats} 开始")
action_sequence.append(action_log(f"分离循环 {cycle_num}/{repeats} 开始", "🔄", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮: 开始分离循环 {cycle_num}/{repeats}")
action_sequence.append(create_action_log(f"分离循环 {cycle_num}/{repeats} 开始", "🔄"))
# 步骤3.1: 添加溶剂(如果需要)
if solvent_vessel and final_volume > 0:
action_sequence.append(action_log(f"向分离容器添加 {final_volume}mL {solvent}", "💧", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮 步骤1: 添加溶剂 {solvent} ({final_volume}mL)")
action_sequence.append(create_action_log(f"向分离容器添加 {final_volume}mL {solvent}", "💧"))
try:
# 使用pump protocol添加溶剂
pump_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=solvent_vessel,
to_vessel=final_vessel_id,
to_vessel=final_vessel_id, # 🔧 使用 final_vessel_id
volume=final_volume,
amount="",
time=0.0,
@@ -192,27 +242,30 @@ def generate_separate_protocol(
**kwargs
)
action_sequence.extend(pump_actions)
action_sequence.append(action_log(f"溶剂转移完成 ({len(pump_actions)} 个操作)", "", prefix="[SEPARATE]"))
debug_print(f"✅ 溶剂添加完成,添加了 {len(pump_actions)} 个动作")
action_sequence.append(create_action_log(f"溶剂转移完成 ({len(pump_actions)} 个操作)", ""))
# 更新体积 - 添加溶剂后
# 🔧 新增:更新体积 - 添加溶剂后
current_volume += final_volume
update_vessel_volume(vessel, G, current_volume, f"添加{final_volume}mL {solvent}")
except Exception as e:
debug_print(f"❌ 溶剂添加失败: {str(e)}")
action_sequence.append(action_log(f"溶剂添加失败: {str(e)}", "", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"溶剂添加失败: {str(e)}", ""))
else:
action_sequence.append(action_log("无需添加溶剂", "⏭️", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮 步骤1: 无需添加溶剂")
action_sequence.append(create_action_log("无需添加溶剂", "⏭️"))
# 步骤3.2: 启动搅拌(如果有搅拌器)
if stirrer_device and stir_time > 0:
action_sequence.append(action_log(f"开始搅拌: {stir_speed}rpm持续 {stir_time}s", "🌪️", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮 步骤2: 开始搅拌 ({stir_speed}rpm持续 {stir_time}s)")
action_sequence.append(create_action_log(f"开始搅拌: {stir_speed}rpm持续 {stir_time}s", "🌪️"))
action_sequence.append({
"device_id": stirrer_device,
"action_name": "start_stir",
"action_kwargs": {
"vessel": {"id": final_vessel_id},
"vessel": {"id": final_vessel_id}, # 🔧 使用 final_vessel_id
"stir_speed": stir_speed,
"purpose": f"分离混合 - {purpose}"
}
@@ -220,37 +273,43 @@ def generate_separate_protocol(
# 搅拌等待
stir_minutes = stir_time / 60
action_sequence.append(action_log(f"搅拌中,持续 {stir_minutes:.1f} 分钟", "⏱️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"搅拌中,持续 {stir_minutes:.1f} 分钟", "⏱️"))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": stir_time}
})
# 停止搅拌
action_sequence.append(action_log("停止搅拌器", "🛑", prefix="[SEPARATE]"))
action_sequence.append(create_action_log("停止搅拌器", "🛑"))
action_sequence.append({
"device_id": stirrer_device,
"action_name": "stop_stir",
"action_kwargs": {"vessel": final_vessel_id}
"action_kwargs": {"vessel": final_vessel_id} # 🔧 使用 final_vessel_id
})
else:
action_sequence.append(action_log("无需搅拌", "⏭️", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮 步骤2: 无需搅拌")
action_sequence.append(create_action_log("无需搅拌", "⏭️"))
# 步骤3.3: 静置分层
if settling_time > 0:
debug_print(f"🔄 第{cycle_num}轮 步骤3: 静置分层 ({settling_time}s)")
settling_minutes = settling_time / 60
action_sequence.append(action_log(f"静置分层 ({settling_minutes:.1f} 分钟)", "⚖️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"静置分层 ({settling_minutes:.1f} 分钟)", "⚖️"))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": settling_time}
})
else:
action_sequence.append(action_log("未指定静置时间", "⏭️", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮 步骤3: 未指定静置时间")
action_sequence.append(create_action_log("未指定静置时间", "⏭️"))
# 步骤3.4: 执行分离操作
if separator_device:
action_sequence.append(action_log(f"执行分离: 收集{product_phase}", "🧪", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮 步骤4: 执行分离操作")
action_sequence.append(create_action_log(f"执行分离: 收集{product_phase}", "🧪"))
# 🔧 替换为具体的分离操作逻辑基于old版本
# 首先进行分液判断(电导突跃)
action_sequence.append({
@@ -265,10 +324,11 @@ def generate_separate_protocol(
phase_volume = current_volume / 2
# 智能查找分离容器底部
separation_vessel_bottom = find_separation_vessel_bottom(G, final_vessel_id)
separation_vessel_bottom = find_separation_vessel_bottom(G, final_vessel_id) # ✅
if product_phase == "bottom":
action_sequence.append(action_log("收集底相产物", "📦", prefix="[SEPARATE]"))
debug_print(f"🔄 收集底相产物{final_to_vessel_id}")
action_sequence.append(create_action_log("收集底相产物", "📦"))
# 产物转移到目标瓶
if final_to_vessel_id:
@@ -304,7 +364,8 @@ def generate_separate_protocol(
action_sequence.extend(pump_actions)
elif product_phase == "top":
action_sequence.append(action_log("收集上相产物", "📦", prefix="[SEPARATE]"))
debug_print(f"🔄 收集上相产物{final_to_vessel_id}")
action_sequence.append(create_action_log("收集上相产物", "📦"))
# 弃去下面那一相进废液
if final_waste_vessel_id:
@@ -339,9 +400,10 @@ def generate_separate_protocol(
)
action_sequence.extend(pump_actions)
action_sequence.append(action_log("分离操作完成", "", prefix="[SEPARATE]"))
debug_print(f"分离操作完成")
action_sequence.append(create_action_log("分离操作完成", ""))
# 分离后体积估算
# 🔧 新增:分离后体积估算
separated_volume = phase_volume * 0.95 # 假设5%损失,只保留产物相体积
update_vessel_volume(vessel, G, separated_volume, f"分离操作后(第{cycle_num}轮)")
current_volume = separated_volume
@@ -349,21 +411,23 @@ def generate_separate_protocol(
# 收集结果
if final_to_vessel_id:
action_sequence.append(
action_log(f"产物 ({product_phase}相) 收集到: {final_to_vessel_id}", "📦", prefix="[SEPARATE]"))
create_action_log(f"产物 ({product_phase}相) 收集到: {final_to_vessel_id}", "📦"))
if final_waste_vessel_id:
action_sequence.append(action_log(f"废相收集到: {final_waste_vessel_id}", "🗑️", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"废相收集到: {final_waste_vessel_id}", "🗑️"))
else:
action_sequence.append(action_log("无分离器设备可用", "", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮 步骤4: 无分离器设备,跳过分离")
action_sequence.append(create_action_log("无分离器设备可用", ""))
# 添加等待时间模拟分离
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 10.0}
})
# 如果不是最后一次,从中转瓶转移回分液漏斗
# 🔧 新增:如果不是最后一次,从中转瓶转移回分液漏斗基于old版本逻辑
if repeat_idx < repeats - 1 and final_to_vessel_id and final_to_vessel_id != final_vessel_id:
action_sequence.append(action_log("产物转回分离容器准备下一轮", "🔄", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮: 产物转回分离容器准备下一轮")
action_sequence.append(create_action_log("产物转回分离容器,准备下一轮", "🔄"))
pump_actions = generate_pump_protocol_with_rinsing(
G=G,
@@ -380,85 +444,368 @@ def generate_separate_protocol(
# 循环间等待(除了最后一次)
if repeat_idx < repeats - 1:
action_sequence.append(action_log("等待下一次循环...", "", prefix="[SEPARATE]"))
debug_print(f"🔄 第{cycle_num}轮: 等待下一次循环...")
action_sequence.append(create_action_log("等待下一次循环...", ""))
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": 5}
})
else:
action_sequence.append(action_log(f"分离循环 {cycle_num}/{repeats} 完成", "🌟", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"分离循环 {cycle_num}/{repeats} 完成", "🌟"))
except Exception as e:
debug_print(f"❌ 分离工作流程执行失败: {str(e)}")
action_sequence.append(action_log(f"分离工作流程失败: {str(e)}", "", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(f"分离工作流程失败: {str(e)}", ""))
# 分离完成后的最终状态报告
final_liquid_volume = get_resource_liquid_volume(vessel)
# 🔧 新增:分离完成后的最终状态报告
final_liquid_volume = get_vessel_liquid_volume(vessel)
# === 最终结果 ===
total_time = (stir_time + settling_time + 15) * repeats # 估算总时间
debug_print(f"分离协议生成完成: {len(action_sequence)} 个动作, "
f"预计 {total_time:.0f}s, 体积 {original_liquid_volume:.2f}{final_liquid_volume:.2f}mL")
debug_print("🌀" * 20)
debug_print(f"🎉 分离协议生成完成")
debug_print(f"📊 协议统计:")
debug_print(f" 📋 总动作数: {len(action_sequence)}")
debug_print(f" ⏱️ 预计总时间: {total_time:.0f}s ({total_time / 60:.1f} 分钟)")
debug_print(f" 🥼 分离容器: {final_vessel_id}")
debug_print(f" 🎯 分离目的: {purpose}")
debug_print(f" 📊 产物相: {product_phase}")
debug_print(f" 🔄 重复次数: {repeats}")
debug_print(f"💧 体积变化统计:")
debug_print(f" - 分离前体积: {original_liquid_volume:.2f}mL")
debug_print(f" - 分离后体积: {final_liquid_volume:.2f}mL")
if solvent:
debug_print(f" 💧 溶剂: {solvent} ({final_volume}mL × {repeats}轮 = {final_volume * repeats:.2f}mL)")
if final_to_vessel_id:
debug_print(f" 🎯 产物容器: {final_to_vessel_id}")
if final_waste_vessel_id:
debug_print(f" 🗑️ 废液容器: {final_waste_vessel_id}")
debug_print("🌀" * 20)
# 添加完成日志
summary_msg = f"分离协议完成: {final_vessel_id} ({purpose}{repeats} 次循环)"
if solvent:
summary_msg += f",使用 {final_volume * repeats:.2f}mL {solvent}"
action_sequence.append(action_log(summary_msg, "🎉", prefix="[SEPARATE]"))
action_sequence.append(create_action_log(summary_msg, "🎉"))
return action_sequence
def parse_volume_input(volume_input: Union[str, float]) -> float:
"""
解析体积输入,支持带单位的字符串
Args:
volume_input: 体积输入(如 "200 mL", "?", 50.0
Returns:
float: 体积(毫升)
"""
if isinstance(volume_input, (int, float)):
debug_print(f"📏 体积输入为数值: {volume_input}")
return float(volume_input)
if not volume_input or not str(volume_input).strip():
debug_print(f"⚠️ 体积输入为空,返回 0.0mL")
return 0.0
volume_str = str(volume_input).lower().strip()
debug_print(f"🔍 解析体积输入: '{volume_str}'")
# 处理未知体积
if volume_str in ['?', 'unknown', 'tbd', 'to be determined', '未知', '待定']:
default_volume = 100.0 # 默认100mL
debug_print(f"❓ 检测到未知体积,使用默认值: {default_volume}mL")
return default_volume
# 移除空格并提取数字和单位
volume_clean = re.sub(r'\s+', '', volume_str)
# 匹配数字和单位的正则表达式
match = re.match(r'([0-9]*\.?[0-9]+)\s*(ml|l|μl|ul|microliter|milliliter|liter|毫升|升|微升)?', volume_clean)
if not match:
debug_print(f"⚠️ 无法解析体积: '{volume_str}',使用默认值 100mL")
return 100.0
value = float(match.group(1))
unit = match.group(2) or 'ml' # 默认单位为毫升
# 转换为毫升
if unit in ['l', 'liter', '']:
volume = value * 1000.0 # L -> mL
debug_print(f"🔄 体积转换: {value}L -> {volume}mL")
elif unit in ['μl', 'ul', 'microliter', '微升']:
volume = value / 1000.0 # μL -> mL
debug_print(f"🔄 体积转换: {value}μL -> {volume}mL")
else: # ml, milliliter, 毫升 或默认
volume = value # 已经是mL
debug_print(f"✅ 体积已为毫升单位: {volume}mL")
return volume
def find_solvent_vessel(G: nx.DiGraph, solvent: str) -> str:
"""查找溶剂容器,支持多种匹配模式"""
if not solvent or not solvent.strip():
debug_print("⏭️ 未指定溶剂,跳过溶剂容器查找")
return ""
debug_print(f"🔍 正在查找溶剂 '{solvent}' 的容器...")
# 🔧 方法1直接搜索 data.reagent_name 和 config.reagent
debug_print(f"📋 方法1: 搜索试剂字段...")
for node in G.nodes():
node_data = G.nodes[node].get('data', {})
node_type = G.nodes[node].get('type', '')
config_data = G.nodes[node].get('config', {})
# 只搜索容器类型的节点
if node_type == 'container':
reagent_name = node_data.get('reagent_name', '').lower()
config_reagent = config_data.get('reagent', '').lower()
# 精确匹配
if reagent_name == solvent.lower() or config_reagent == solvent.lower():
debug_print(f"✅ 通过试剂字段精确匹配找到容器: {node}")
return node
# 模糊匹配
if (solvent.lower() in reagent_name and reagent_name) or \
(solvent.lower() in config_reagent and config_reagent):
debug_print(f"✅ 通过试剂字段模糊匹配找到容器: {node}")
return node
# 🔧 方法2常见的容器命名规则
debug_print(f"📋 方法2: 使用命名规则...")
solvent_clean = solvent.lower().replace(' ', '_').replace('-', '_')
possible_names = [
f"flask_{solvent_clean}",
f"bottle_{solvent_clean}",
f"vessel_{solvent_clean}",
f"{solvent_clean}_flask",
f"{solvent_clean}_bottle",
f"solvent_{solvent_clean}",
f"reagent_{solvent_clean}",
f"reagent_bottle_{solvent_clean}",
f"reagent_bottle_1", # 通用试剂瓶
f"reagent_bottle_2",
f"reagent_bottle_3"
]
debug_print(f"🎯 尝试的容器名称: {possible_names[:5]}... (共 {len(possible_names)} 个)")
for name in possible_names:
if name in G.nodes():
node_type = G.nodes[name].get('type', '')
if node_type == 'container':
debug_print(f"✅ 通过命名规则找到容器: {name}")
return name
# 🔧 方法3使用第一个试剂瓶作为备选
debug_print(f"📋 方法3: 查找备用试剂瓶...")
for node_id in G.nodes():
node_data = G.nodes[node_id]
if (node_data.get('type') == 'container' and
('reagent' in node_id.lower() or 'bottle' in node_id.lower())):
debug_print(f"⚠️ 未找到专用容器,使用备用容器: {node_id}")
return node_id
debug_print(f"❌ 无法找到溶剂 '{solvent}' 的容器")
return ""
def find_separator_device(G: nx.DiGraph, vessel: str) -> str:
"""查找分离器设备,支持多种查找方式"""
debug_print(f"🔍 正在查找容器 '{vessel}' 的分离器设备...")
# 方法1查找连接到容器的分离器设备
debug_print(f"📋 方法1: 检查连接的分离器...")
separator_nodes = []
for node in G.nodes():
node_class = G.nodes[node].get('class', '').lower()
if 'separator' in node_class:
separator_nodes.append(node)
debug_print(f"📋 发现分离器设备: {node}")
# 检查是否连接到目标容器
if G.has_edge(node, vessel) or G.has_edge(vessel, node):
debug_print(f"✅ 找到连接的分离器: {node}")
return node
debug_print(f"📊 找到的分离器总数: {len(separator_nodes)}")
# 方法2根据命名规则查找
debug_print(f"📋 方法2: 使用命名规则...")
possible_names = [
f"{vessel}_controller",
f"{vessel}_separator",
vessel, # 容器本身可能就是分离器
"separator_1",
"virtual_separator",
"liquid_handler_1",
"liquid_handler_1", # 液体处理器也可能用于分离
"controller_1"
]
debug_print(f"🎯 尝试的分离器名称: {possible_names}")
for name in possible_names:
if name in G.nodes():
node_class = G.nodes[name].get('class', '').lower()
if 'separator' in node_class or 'controller' in node_class:
debug_print(f"✅ 通过命名规则找到分离器: {name}")
return name
# 方法3使用第一个可用分离器
# 方法3查找第一个分离器设备
debug_print(f"📋 方法3: 使用第一个可用分离器...")
if separator_nodes:
debug_print(f"⚠️ 使用第一个分离器设备: {separator_nodes[0]}")
return separator_nodes[0]
debug_print(f"❌ 未找到分离器设备")
return ""
def find_connected_stirrer(G: nx.DiGraph, vessel: str) -> str:
"""查找连接到指定容器的搅拌器"""
debug_print(f"🔍 正在查找与容器 {vessel} 连接的搅拌器...")
stirrer_nodes = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if 'stirrer' in node_class.lower():
stirrer_nodes.append(node)
debug_print(f"📋 发现搅拌器: {node}")
debug_print(f"📊 找到的搅拌器总数: {len(stirrer_nodes)}")
# 检查哪个搅拌器与目标容器相连
for stirrer in stirrer_nodes:
if G.has_edge(stirrer, vessel) or G.has_edge(vessel, stirrer):
debug_print(f"✅ 找到连接的搅拌器: {stirrer}")
return stirrer
# 如果没有连接的搅拌器,返回第一个可用的
if stirrer_nodes:
debug_print(f"⚠️ 未找到直接连接的搅拌器,使用第一个可用的: {stirrer_nodes[0]}")
return stirrer_nodes[0]
debug_print("❌ 未找到搅拌器")
return ""
def get_vessel_liquid_volume(vessel: dict) -> float:
"""
获取容器中的液体体积 - 支持vessel字典
Args:
vessel: 容器字典
Returns:
float: 液体体积mL
"""
if not vessel or "data" not in vessel:
debug_print(f"⚠️ 容器数据为空,返回 0.0mL")
return 0.0
vessel_data = vessel["data"]
vessel_id = vessel.get("id", "unknown")
debug_print(f"🔍 读取容器 '{vessel_id}' 体积数据: {vessel_data}")
# 检查liquid_volume字段
if "liquid_volume" in vessel_data:
liquid_volume = vessel_data["liquid_volume"]
# 处理列表格式
if isinstance(liquid_volume, list):
if len(liquid_volume) > 0:
volume = liquid_volume[0]
if isinstance(volume, (int, float)):
debug_print(f"✅ 容器 '{vessel_id}' 体积: {volume}mL (列表格式)")
return float(volume)
# 处理直接数值格式
elif isinstance(liquid_volume, (int, float)):
debug_print(f"✅ 容器 '{vessel_id}' 体积: {liquid_volume}mL (数值格式)")
return float(liquid_volume)
# 检查其他可能的体积字段
volume_keys = ['current_volume', 'total_volume', 'volume']
for key in volume_keys:
if key in vessel_data:
try:
volume = float(vessel_data[key])
if volume > 0:
debug_print(f"✅ 容器 '{vessel_id}' 体积: {volume}mL (字段: {key})")
return volume
except (ValueError, TypeError):
continue
debug_print(f"⚠️ 无法获取容器 '{vessel_id}' 的体积,返回默认值 50.0mL")
return 50.0
def update_vessel_volume(vessel: dict, G: nx.DiGraph, new_volume: float, description: str = "") -> None:
"""
更新容器体积同时更新vessel字典和图节点
Args:
vessel: 容器字典
G: 网络图
new_volume: 新体积
description: 更新描述
"""
vessel_id = vessel.get("id", "unknown")
if description:
debug_print(f"🔧 更新容器体积 - {description}")
# 更新vessel字典中的体积
if "data" in vessel:
if "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
if len(current_volume) > 0:
vessel["data"]["liquid_volume"][0] = new_volume
else:
vessel["data"]["liquid_volume"] = [new_volume]
else:
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"] = {"liquid_volume": new_volume}
# 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = new_volume
else:
G.nodes[vessel_id]['data']['liquid_volume'] = [new_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = new_volume
debug_print(f"📊 容器 '{vessel_id}' 体积已更新为: {new_volume:.2f}mL")
def find_separation_vessel_bottom(G: nx.DiGraph, vessel_id: str) -> str:
"""
智能查找分离容器的底部容器假设为flask或vessel类型
Args:
G: 网络图
vessel_id: 分离容器ID
Returns:
str: 底部容器ID
"""
debug_print(f"🔍 查找分离容器 {vessel_id} 的底部容器...")
# 方法1根据命名规则推测
possible_bottoms = [
f"{vessel_id}_bottom",
@@ -467,25 +814,32 @@ def find_separation_vessel_bottom(G: nx.DiGraph, vessel_id: str) -> str:
f"{vessel_id}_flask",
f"{vessel_id}_vessel"
]
debug_print(f"📋 尝试的底部容器名称: {possible_bottoms}")
for bottom_id in possible_bottoms:
if bottom_id in G.nodes():
node_type = G.nodes[bottom_id].get('type', '')
if node_type == 'container':
debug_print(f"✅ 通过命名规则找到底部容器: {bottom_id}")
return bottom_id
# 方法2查找与分离器相连的容器
# 方法2查找与分离器相连的容器(假设底部容器会与分离器相连)
debug_print(f"📋 方法2: 查找连接的容器...")
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if 'separator' in node_class.lower():
# 检查分离器的输入端
if G.has_edge(node, vessel_id):
for neighbor in G.neighbors(node):
if neighbor != vessel_id:
neighbor_type = G.nodes[neighbor].get('type', '')
if neighbor_type == 'container':
debug_print(f"✅ 通过连接找到底部容器: {neighbor}")
return neighbor
debug_print(f"❌ 无法找到分离容器 {vessel_id} 的底部容器")
return ""

View File

@@ -1,40 +1,116 @@
from typing import List, Dict, Any, Union
import networkx as nx
import logging
import re
from .utils.unit_parser import parse_time_input
from .utils.resource_helper import get_resource_id, get_resource_display_info
from .utils.logger_util import debug_print
from .utils.vessel_parser import find_connected_stirrer
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[STIR] {message}")
def find_connected_stirrer(G: nx.DiGraph, vessel: str = None) -> str:
"""查找与指定容器相连的搅拌设备"""
debug_print(f"🔍 查找搅拌设备,目标容器: {vessel} 🥽")
# 🔧 查找所有搅拌设备
stirrer_nodes = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
if 'stirrer' in node_class.lower() or 'virtual_stirrer' in node_class:
stirrer_nodes.append(node)
debug_print(f"🎉 找到搅拌设备: {node} 🌪️")
# 🔗 检查连接
if vessel and stirrer_nodes:
for stirrer in stirrer_nodes:
if G.has_edge(stirrer, vessel) or G.has_edge(vessel, stirrer):
debug_print(f"✅ 搅拌设备 '{stirrer}' 与容器 '{vessel}' 相连 🔗")
return stirrer
# 🎯 使用第一个可用设备
if stirrer_nodes:
selected = stirrer_nodes[0]
debug_print(f"🔧 使用第一个搅拌设备: {selected} 🌪️")
return selected
# 🆘 默认设备
debug_print("⚠️ 未找到搅拌设备,使用默认设备 🌪️")
return "stirrer_1"
def validate_and_fix_params(stir_time: float, stir_speed: float, settling_time: float) -> tuple:
"""验证和修正参数"""
# ⏰ 搅拌时间验证
if stir_time < 0:
debug_print(f"搅拌时间 {stir_time}s 无效,修正为 100s")
debug_print(f"⚠️ 搅拌时间 {stir_time}s 无效,修正为 100s 🕐")
stir_time = 100.0
elif stir_time > 100: # 限制为100s
debug_print(f"搅拌时间 {stir_time}s 过长,仿真运行时修正为 100s")
debug_print(f"⚠️ 搅拌时间 {stir_time}s 过长,仿真运行时修正为 100s 🕐")
stir_time = 100.0
else:
debug_print(f"✅ 搅拌时间 {stir_time}s ({stir_time/60:.1f}分钟) 有效 ⏰")
# 🌪️ 搅拌速度验证
if stir_speed < 10.0 or stir_speed > 1500.0:
debug_print(f"搅拌速度 {stir_speed} RPM 超出范围,修正为 300 RPM")
debug_print(f"⚠️ 搅拌速度 {stir_speed} RPM 超出范围,修正为 300 RPM 🌪️")
stir_speed = 300.0
else:
debug_print(f"✅ 搅拌速度 {stir_speed} RPM 在正常范围内 🌪️")
# ⏱️ 沉降时间验证
if settling_time < 0 or settling_time > 600: # 限制为10分钟
debug_print(f"沉降时间 {settling_time}s 超出范围,修正为 60s")
debug_print(f"⚠️ 沉降时间 {settling_time}s 超出范围,修正为 60s ⏱️")
settling_time = 60.0
else:
debug_print(f"✅ 沉降时间 {settling_time}s 在正常范围内 ⏱️")
return stir_time, stir_speed, settling_time
def extract_vessel_id(vessel) -> str:
"""从vessel参数中提取vessel_id兼容 str / dict / ResourceDictInstance"""
return get_resource_id(vessel)
def extract_vessel_id(vessel: Union[str, dict]) -> str:
"""
从vessel参数中提取vessel_id
Args:
vessel: vessel字典或vessel_id字符串
Returns:
str: vessel_id
"""
if isinstance(vessel, dict):
vessel_id = list(vessel.values())[0].get("id", "")
debug_print(f"🔧 从vessel字典提取ID: {vessel_id}")
return vessel_id
elif isinstance(vessel, str):
debug_print(f"🔧 vessel参数为字符串: {vessel}")
return vessel
else:
debug_print(f"⚠️ 无效的vessel参数类型: {type(vessel)}")
return ""
def get_vessel_display_info(vessel) -> str:
"""获取容器的显示信息(用于日志),兼容 str / dict / ResourceDictInstance"""
return get_resource_display_info(vessel)
def get_vessel_display_info(vessel: Union[str, dict]) -> str:
"""
获取容器的显示信息(用于日志)
Args:
vessel: vessel字典或vessel_id字符串
Returns:
str: 显示信息
"""
if isinstance(vessel, dict):
vessel_id = vessel.get("id", "unknown")
vessel_name = vessel.get("name", "")
if vessel_name:
return f"{vessel_id} ({vessel_name})"
else:
return vessel_id
else:
return str(vessel)
def generate_stir_protocol(
G: nx.DiGraph,
@@ -49,13 +125,16 @@ def generate_stir_protocol(
) -> List[Dict[str, Any]]:
"""生成搅拌操作的协议序列 - 修复vessel参数传递"""
# 🔧 核心修改正确处理vessel参数
vessel_id = extract_vessel_id(vessel)
vessel_display = get_vessel_display_info(vessel)
# 确保vessel_resource是完整的Resource对象
# 🔧 关键修复:确保vessel_resource是完整的Resource对象
if isinstance(vessel, dict):
vessel_resource = vessel
vessel_resource = vessel # 已经是完整的Resource字典
debug_print(f"✅ 使用传入的vessel Resource对象")
else:
# 如果只是字符串构建一个基本的Resource对象
vessel_resource = {
"id": vessel,
"name": "",
@@ -71,60 +150,91 @@ def generate_stir_protocol(
"sample_id": "",
"type": ""
}
# 参数验证
if not vessel_id:
debug_print(f"🔧 构建了基本的vessel Resource对象: {vessel}")
debug_print("🌪️" * 20)
debug_print("🚀 开始生成搅拌协议支持vessel字典")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 vessel: {vessel_display} (ID: {vessel_id})")
debug_print(f" ⏰ time: {time}")
debug_print(f" 🕐 stir_time: {stir_time}")
debug_print(f" 🎯 time_spec: {time_spec}")
debug_print(f" 🌪️ stir_speed: {stir_speed} RPM")
debug_print(f" ⏱️ settling_time: {settling_time}")
debug_print("🌪️" * 20)
# 📋 参数验证
debug_print("📍 步骤1: 参数验证... 🔧")
if not vessel_id: # 🔧 使用 vessel_id
debug_print("❌ vessel 参数不能为空! 😱")
raise ValueError("vessel 参数不能为空")
if vessel_id not in G.nodes():
if vessel_id not in G.nodes(): # 🔧 使用 vessel_id
debug_print(f"❌ 容器 '{vessel_id}' 不存在于系统中! 😞")
raise ValueError(f"容器 '{vessel_id}' 不存在于系统中")
# 参数解析 — 确定实际时间优先级time_spec > stir_time > time
debug_print("✅ 基础参数验证通过 🎯")
# 🔄 参数解析
debug_print("📍 步骤2: 参数解析... ⚡")
# 确定实际时间优先级time_spec > stir_time > time
if time_spec:
parsed_time = parse_time_input(time_spec)
debug_print(f"🎯 使用time_spec: '{time_spec}'{parsed_time}s")
elif stir_time not in ["0", 0, 0.0]:
parsed_time = parse_time_input(stir_time)
debug_print(f"🎯 使用stir_time: {stir_time}{parsed_time}s")
else:
parsed_time = parse_time_input(time)
debug_print(f"🎯 使用time: {time}{parsed_time}s")
# 解析沉降时间
parsed_settling_time = parse_time_input(settling_time)
# 模拟运行时间优化
# 🕐 模拟运行时间优化
debug_print(" ⏱️ 检查模拟运行时间限制...")
original_stir_time = parsed_time
original_settling_time = parsed_settling_time
# 搅拌时间限制为60秒
stir_time_limit = 60.0
if parsed_time > stir_time_limit:
parsed_time = stir_time_limit
debug_print(f" 🎮 搅拌时间优化: {original_stir_time}s → {parsed_time}s ⚡")
# 沉降时间限制为30秒
settling_time_limit = 30.0
if parsed_settling_time > settling_time_limit:
parsed_settling_time = settling_time_limit
debug_print(f" 🎮 沉降时间优化: {original_settling_time}s → {parsed_settling_time}s ⚡")
# 参数修正
parsed_time, stir_speed, parsed_settling_time = validate_and_fix_params(
parsed_time, stir_speed, parsed_settling_time
)
debug_print(f"最终参数: time={parsed_time}s, speed={stir_speed}RPM, settling={parsed_settling_time}s")
# 查找设备
debug_print(f"🎯 最终参数: time={parsed_time}s, speed={stir_speed}RPM, settling={parsed_settling_time}s")
# 🔍 查找设备
debug_print("📍 步骤3: 查找搅拌设备... 🔍")
try:
stirrer_id = find_connected_stirrer(G, vessel_id)
stirrer_id = find_connected_stirrer(G, vessel_id) # 🔧 使用 vessel_id
debug_print(f"🎉 使用搅拌设备: {stirrer_id}")
except Exception as e:
debug_print(f"❌ 设备查找失败: {str(e)} 😭")
raise ValueError(f"无法找到搅拌设备: {str(e)}")
# 生成动作
# 🚀 生成动作
debug_print("📍 步骤4: 生成搅拌动作... 🌪️")
action_sequence = []
stir_action = {
"device_id": stirrer_id,
"action_name": "stir",
"action_kwargs": {
"vessel": {"id": vessel_id},
# 🔧 关键修复传递vessel_id字符串而不是完整的Resource对象
"vessel": {"id": vessel_id}, # 传递字符串ID不是Resource对象
"time": str(time),
"event": event,
"time_spec": time_spec,
@@ -134,14 +244,22 @@ def generate_stir_protocol(
}
}
action_sequence.append(stir_action)
# 时间优化信息
debug_print("✅ 搅拌动作已添加 🌪️✨")
# 显示时间优化信息
if original_stir_time != parsed_time or original_settling_time != parsed_settling_time:
debug_print(f"模拟优化: 搅拌 {original_stir_time/60:.1f}min→{parsed_time/60:.1f}min, "
f"沉降 {original_settling_time/60:.1f}min→{parsed_settling_time/60:.1f}min")
debug_print(f"搅拌协议生成完成: {vessel_display}, {stir_speed}RPM, "
f"{parsed_time}s, 沉降{parsed_settling_time}s, 总{(parsed_time + parsed_settling_time)/60:.1f}min")
debug_print(f" 🎭 模拟优化说明:")
debug_print(f" 搅拌时间: {original_stir_time/60:.1f}分钟 → {parsed_time/60:.1f}分钟")
debug_print(f" 沉降时间: {original_settling_time/60:.1f}分钟 → {parsed_settling_time/60:.1f}分钟")
# 🎊 总结
debug_print("🎊" * 20)
debug_print(f"🎉 搅拌协议生成完成! ✨")
debug_print(f"📊 总动作数: {len(action_sequence)}")
debug_print(f"🥽 搅拌容器: {vessel_display}")
debug_print(f"🌪️ 搅拌参数: {stir_speed} RPM, {parsed_time}s, 沉降 {parsed_settling_time}s")
debug_print(f"⏱️ 预计总时间: {(parsed_time + parsed_settling_time)/60:.1f} 分钟 ⌛")
debug_print("🎊" * 20)
return action_sequence
@@ -154,13 +272,16 @@ def generate_start_stir_protocol(
) -> List[Dict[str, Any]]:
"""生成开始搅拌操作的协议序列 - 修复vessel参数传递"""
# 🔧 核心修改正确处理vessel参数
vessel_id = extract_vessel_id(vessel)
vessel_display = get_vessel_display_info(vessel)
# 确保vessel_resource是完整的Resource对象
# 🔧 关键修复:确保vessel_resource是完整的Resource对象
if isinstance(vessel, dict):
vessel_resource = vessel
vessel_resource = vessel # 已经是完整的Resource字典
debug_print(f"✅ 使用传入的vessel Resource对象")
else:
# 如果只是字符串构建一个基本的Resource对象
vessel_resource = {
"id": vessel,
"name": "",
@@ -176,29 +297,39 @@ def generate_start_stir_protocol(
"sample_id": "",
"type": ""
}
debug_print(f"🔧 构建了基本的vessel Resource对象: {vessel}")
debug_print("🔄 开始生成启动搅拌协议修复vessel参数")
debug_print(f"🥽 vessel: {vessel_display} (ID: {vessel_id})")
debug_print(f"🌪️ speed: {stir_speed} RPM")
debug_print(f"🎯 purpose: {purpose}")
# 基础验证
if not vessel_id or vessel_id not in G.nodes():
debug_print("❌ 容器验证失败!")
raise ValueError("vessel 参数无效")
# 参数修正
if stir_speed < 10.0 or stir_speed > 1500.0:
debug_print(f"⚠️ 搅拌速度修正: {stir_speed} → 300 RPM 🌪️")
stir_speed = 300.0
# 查找设备
stirrer_id = find_connected_stirrer(G, vessel_id)
# 🔧 关键修复传递vessel_id字符串
action_sequence = [{
"device_id": stirrer_id,
"action_name": "start_stir",
"action_kwargs": {
"vessel": {"id": vessel_id},
# 🔧 关键修复传递vessel_id字符串而不是完整的Resource对象
"vessel": {"id": vessel_id}, # 传递字符串ID不是Resource对象
"stir_speed": stir_speed,
"purpose": purpose or f"启动搅拌 {stir_speed} RPM"
}
}]
debug_print(f"启动搅拌协议: {vessel_display}, {stir_speed}RPM, device={stirrer_id}")
debug_print(f"启动搅拌协议生成完成 🎯")
return action_sequence
def generate_stop_stir_protocol(
@@ -208,13 +339,16 @@ def generate_stop_stir_protocol(
) -> List[Dict[str, Any]]:
"""生成停止搅拌操作的协议序列 - 修复vessel参数传递"""
# 🔧 核心修改正确处理vessel参数
vessel_id = extract_vessel_id(vessel)
vessel_display = get_vessel_display_info(vessel)
# 确保vessel_resource是完整的Resource对象
# 🔧 关键修复:确保vessel_resource是完整的Resource对象
if isinstance(vessel, dict):
vessel_resource = vessel
vessel_resource = vessel # 已经是完整的Resource字典
debug_print(f"✅ 使用传入的vessel Resource对象")
else:
# 如果只是字符串构建一个基本的Resource对象
vessel_resource = {
"id": vessel,
"name": "",
@@ -230,103 +364,115 @@ def generate_stop_stir_protocol(
"sample_id": "",
"type": ""
}
debug_print(f"🔧 构建了基本的vessel Resource对象: {vessel}")
debug_print("🛑 开始生成停止搅拌协议修复vessel参数")
debug_print(f"🥽 vessel: {vessel_display} (ID: {vessel_id})")
# 基础验证
if not vessel_id or vessel_id not in G.nodes():
debug_print("❌ 容器验证失败!")
raise ValueError("vessel 参数无效")
# 查找设备
stirrer_id = find_connected_stirrer(G, vessel_id)
# 🔧 关键修复传递vessel_id字符串
action_sequence = [{
"device_id": stirrer_id,
"action_name": "stop_stir",
"action_kwargs": {
"vessel": {"id": vessel_id},
# 🔧 关键修复传递vessel_id字符串而不是完整的Resource对象
"vessel": {"id": vessel_id}, # 传递字符串ID不是Resource对象
}
}]
debug_print(f"停止搅拌协议: {vessel_display}, device={stirrer_id}")
debug_print(f"停止搅拌协议生成完成 🎯")
return action_sequence
# 便捷函数
# 🔧 新增:便捷函数
def stir_briefly(G: nx.DiGraph, vessel: Union[str, dict],
speed: float = 300.0) -> List[Dict[str, Any]]:
"""短时间搅拌30秒"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"短时间搅拌: {vessel_display} @ {speed}RPM (30s)")
debug_print(f"短时间搅拌: {vessel_display} @ {speed}RPM (30s)")
return generate_stir_protocol(G, vessel, time="30", stir_speed=speed)
def stir_slowly(G: nx.DiGraph, vessel: Union[str, dict],
time: Union[str, float] = "10 min") -> List[Dict[str, Any]]:
"""慢速搅拌"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"慢速搅拌: {vessel_display} @ 150RPM")
debug_print(f"🐌 慢速搅拌: {vessel_display} @ 150RPM")
return generate_stir_protocol(G, vessel, time=time, stir_speed=150.0)
def stir_vigorously(G: nx.DiGraph, vessel: Union[str, dict],
time: Union[str, float] = "5 min") -> List[Dict[str, Any]]:
"""剧烈搅拌"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"剧烈搅拌: {vessel_display} @ 800RPM")
debug_print(f"💨 剧烈搅拌: {vessel_display} @ 800RPM")
return generate_stir_protocol(G, vessel, time=time, stir_speed=800.0)
def stir_for_reaction(G: nx.DiGraph, vessel: Union[str, dict],
time: Union[str, float] = "1 h") -> List[Dict[str, Any]]:
"""反应搅拌(标准速度,长时间)"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"反应搅拌: {vessel_display} @ 400RPM")
debug_print(f"🧪 反应搅拌: {vessel_display} @ 400RPM")
return generate_stir_protocol(G, vessel, time=time, stir_speed=400.0)
def stir_for_dissolution(G: nx.DiGraph, vessel: Union[str, dict],
time: Union[str, float] = "15 min") -> List[Dict[str, Any]]:
"""溶解搅拌(中等速度)"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"溶解搅拌: {vessel_display} @ 500RPM")
debug_print(f"💧 溶解搅拌: {vessel_display} @ 500RPM")
return generate_stir_protocol(G, vessel, time=time, stir_speed=500.0)
def stir_gently(G: nx.DiGraph, vessel: Union[str, dict],
time: Union[str, float] = "30 min") -> List[Dict[str, Any]]:
"""温和搅拌"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"温和搅拌: {vessel_display} @ 200RPM")
debug_print(f"🍃 温和搅拌: {vessel_display} @ 200RPM")
return generate_stir_protocol(G, vessel, time=time, stir_speed=200.0)
def stir_overnight(G: nx.DiGraph, vessel: Union[str, dict]) -> List[Dict[str, Any]]:
"""过夜搅拌模拟时缩短为2小时"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"过夜搅拌模拟2小时: {vessel_display} @ 300RPM")
debug_print(f"🌙 过夜搅拌模拟2小时: {vessel_display} @ 300RPM")
return generate_stir_protocol(G, vessel, time="2 h", stir_speed=300.0)
def start_continuous_stirring(G: nx.DiGraph, vessel: Union[str, dict],
speed: float = 300.0, purpose: str = "continuous stirring") -> List[Dict[str, Any]]:
"""开始连续搅拌"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"开始连续搅拌: {vessel_display} @ {speed}RPM")
debug_print(f"🔄 开始连续搅拌: {vessel_display} @ {speed}RPM")
return generate_start_stir_protocol(G, vessel, stir_speed=speed, purpose=purpose)
def stop_all_stirring(G: nx.DiGraph, vessel: Union[str, dict]) -> List[Dict[str, Any]]:
"""停止所有搅拌"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"停止搅拌: {vessel_display}")
debug_print(f"🛑 停止搅拌: {vessel_display}")
return generate_stop_stir_protocol(G, vessel)
# 测试函数
def test_stir_protocol():
"""测试搅拌协议"""
debug_print("🧪 === STIR PROTOCOL 测试 === ✨")
# 测试vessel参数处理
debug_print("🔧 测试vessel参数处理...")
# 测试字典格式
vessel_dict = {"id": "flask_1", "name": "反应瓶1"}
vessel_id = extract_vessel_id(vessel_dict)
vessel_display = get_vessel_display_info(vessel_dict)
debug_print(f"字典格式: {vessel_dict} -> ID: {vessel_id}, 显示: {vessel_display}")
debug_print(f" 字典格式: {vessel_dict} ID: {vessel_id}, 显示: {vessel_display}")
# 测试字符串格式
vessel_str = "flask_2"
vessel_id = extract_vessel_id(vessel_str)
vessel_display = get_vessel_display_info(vessel_str)
debug_print(f"字符串格式: {vessel_str} -> ID: {vessel_id}, 显示: {vessel_display}")
debug_print("测试完成")
debug_print(f" 字符串格式: {vessel_str} ID: {vessel_id}, 显示: {vessel_display}")
debug_print("测试完成 🎉")
if __name__ == "__main__":
test_stir_protocol()

View File

@@ -1,57 +1,36 @@
"""编译器共享日志工具"""
import inspect
# 🆕 创建进度日志动作
import logging
from typing import Dict, Any
# 模块名到前缀的映射
_MODULE_PREFIXES = {
"add_protocol": "[ADD]",
"adjustph_protocol": "[ADJUSTPH]",
"clean_vessel_protocol": "[CLEAN_VESSEL]",
"dissolve_protocol": "[DISSOLVE]",
"dry_protocol": "[DRY]",
"evacuateandrefill_protocol": "[EVACUATE]",
"evaporate_protocol": "[EVAPORATE]",
"filter_protocol": "[FILTER]",
"heatchill_protocol": "[HEATCHILL]",
"hydrogenate_protocol": "[HYDROGENATE]",
"pump_protocol": "[PUMP]",
"recrystallize_protocol": "[RECRYSTALLIZE]",
"reset_handling_protocol": "[RESET]",
"run_column_protocol": "[RUN_COLUMN]",
"separate_protocol": "[SEPARATE]",
"stir_protocol": "[STIR]",
"wash_solid_protocol": "[WASH_SOLID]",
"vessel_parser": "[VESSEL_PARSER]",
"unit_parser": "[UNIT_PARSER]",
"resource_helper": "[RESOURCE_HELPER]",
}
logger = logging.getLogger(__name__)
def debug_print(message, prefix=None):
"""调试输出 — 自动根据调用模块设置前缀"""
if prefix is None:
frame = inspect.currentframe()
caller = frame.f_back if frame else None
module_name = ""
if caller:
module_name = caller.f_globals.get("__name__", "")
# 取最后一段作为模块短名
module_name = module_name.rsplit(".", 1)[-1]
prefix = _MODULE_PREFIXES.get(module_name, f"[{module_name.upper()}]")
logger = logging.getLogger("unilabos.compile")
def debug_print(message, prefix="[UNIT_PARSER]"):
"""调试输出"""
logger.info(f"{prefix} {message}")
def action_log(message: str, emoji: str = "📝", prefix="[HIGH-LEVEL OPERATION]") -> Dict[str, Any]:
"""创建一个动作日志"""
full_message = f"{prefix} {emoji} {message}"
return {
"action_name": "wait",
"action_kwargs": {
"time": 0.1,
"log_message": full_message,
"progress_message": full_message
"""创建一个动作日志 - 支持中文和emoji"""
try:
full_message = f"{prefix} {emoji} {message}"
return {
"action_name": "wait",
"action_kwargs": {
"time": 0.1,
"log_message": full_message,
"progress_message": full_message
}
}
}
except Exception as e:
# 如果emoji有问题使用纯文本
safe_message = f"{prefix} {message}"
return {
"action_name": "wait",
"action_kwargs": {
"time": 0.1,
"log_message": safe_message,
"progress_message": safe_message
}
}

View File

@@ -1,172 +0,0 @@
"""
资源实例兼容层
提供 ensure_resource_instance() 将 dict / ResourceDictInstance 统一转为
ResourceDictInstance使编译器可以渐进式迁移到强类型资源。
"""
from typing import Any, Dict, Optional, Union
from unilabos.resources.resource_tracker import ResourceDictInstance
def ensure_resource_instance(
resource: Union[Dict[str, Any], ResourceDictInstance, None],
) -> Optional[ResourceDictInstance]:
"""将 dict 或 ResourceDictInstance 统一转为 ResourceDictInstance
编译器入口统一调用此函数,即可同时兼容旧 dict 传参和新 ResourceDictInstance 传参。
Args:
resource: 资源数据,可以是 plain dict、ResourceDictInstance 或 None
Returns:
ResourceDictInstance 或 None当输入为 None 时)
"""
if resource is None:
return None
if isinstance(resource, ResourceDictInstance):
return resource
if isinstance(resource, dict):
return ResourceDictInstance.get_resource_instance_from_dict(resource)
raise TypeError(f"不支持的资源类型: {type(resource)}, 期望 dict 或 ResourceDictInstance")
def resource_to_dict(resource: Union[Dict[str, Any], ResourceDictInstance]) -> Dict[str, Any]:
"""将 ResourceDictInstance 或 dict 统一转为 plain dict
用于需要 dict 操作的场景(如 children dict 操作)。
Args:
resource: ResourceDictInstance 或 dict
Returns:
plain dict
"""
if isinstance(resource, dict):
return resource
if isinstance(resource, ResourceDictInstance):
return resource.get_plr_nested_dict()
raise TypeError(f"不支持的资源类型: {type(resource)}")
def get_resource_id(resource: Union[str, Dict[str, Any], ResourceDictInstance]) -> str:
"""从资源对象中提取 ID
Args:
resource: 字符串 ID、dict 或 ResourceDictInstance
Returns:
资源 ID 字符串
"""
if isinstance(resource, str):
return resource
if isinstance(resource, ResourceDictInstance):
return resource.res_content.id
if isinstance(resource, dict):
if "id" in resource:
return resource["id"]
# 兼容 {station_id: {...}} 格式
first_val = next(iter(resource.values()), {})
if isinstance(first_val, dict):
return first_val.get("id", "")
return ""
raise TypeError(f"不支持的资源类型: {type(resource)}")
def get_resource_data(resource: Union[str, Dict[str, Any], ResourceDictInstance]) -> Dict[str, Any]:
"""从资源对象中提取 data 字段
Args:
resource: 字符串、dict 或 ResourceDictInstance
Returns:
data 字典
"""
if isinstance(resource, str):
return {}
if isinstance(resource, ResourceDictInstance):
return dict(resource.res_content.data)
if isinstance(resource, dict):
return resource.get("data", {})
return {}
def get_resource_display_info(resource: Union[str, Dict[str, Any], ResourceDictInstance]) -> str:
"""获取资源的显示信息(用于日志)
Args:
resource: 字符串 ID、dict 或 ResourceDictInstance
Returns:
显示信息字符串
"""
if isinstance(resource, str):
return resource
if isinstance(resource, ResourceDictInstance):
res = resource.res_content
return f"{res.id} ({res.name})" if res.name and res.name != res.id else res.id
if isinstance(resource, dict):
res_id = resource.get("id", "unknown")
res_name = resource.get("name", "")
if res_name and res_name != res_id:
return f"{res_id} ({res_name})"
return res_id
return str(resource)
def get_resource_liquid_volume(resource: Union[Dict[str, Any], ResourceDictInstance]) -> float:
"""从资源中获取液体体积
Args:
resource: dict 或 ResourceDictInstance
Returns:
液体总体积 (mL)
"""
data = get_resource_data(resource)
liquids = data.get("liquid", [])
if isinstance(liquids, list):
return sum(l.get("volume", 0.0) for l in liquids if isinstance(l, dict))
return 0.0
def update_vessel_volume(vessel, G, new_volume: float, description: str = "") -> None:
"""
更新容器体积同时更新vessel字典和图节点
Args:
vessel: 容器字典或 ResourceDictInstance
G: 网络图 (nx.DiGraph)
new_volume: 新体积 (mL)
description: 更新描述(用于日志)
"""
import logging
logger = logging.getLogger("unilabos.compile")
vessel_id = get_resource_id(vessel)
if description:
logger.info(f"[RESOURCE] 更新容器体积 - {description}")
# 更新 vessel 字典中的体积
if isinstance(vessel, dict):
if "data" not in vessel:
vessel["data"] = {}
lv = vessel["data"].get("liquid_volume")
if isinstance(lv, list) and len(lv) > 0:
vessel["data"]["liquid_volume"][0] = new_volume
else:
vessel["data"]["liquid_volume"] = new_volume
# 同时更新图中的容器数据
if vessel_id and vessel_id in G.nodes():
if "data" not in G.nodes[vessel_id]:
G.nodes[vessel_id]["data"] = {}
node_lv = G.nodes[vessel_id]["data"].get("liquid_volume")
if isinstance(node_lv, list) and len(node_lv) > 0:
G.nodes[vessel_id]["data"]["liquid_volume"][0] = new_volume
else:
G.nodes[vessel_id]["data"]["liquid_volume"] = new_volume
logger.info(f"[RESOURCE] 容器 '{vessel_id}' 体积已更新为: {new_volume:.2f}mL")

View File

@@ -184,42 +184,6 @@ def parse_time_input(time_input: Union[str, float]) -> float:
return time_sec
def parse_temperature_input(temp_input: Union[str, float], default_temp: float = 25.0) -> float:
"""
解析温度输入,支持字符串和数值
Args:
temp_input: 温度输入(如 "256 °C", "reflux", 45.0
default_temp: 默认温度
Returns:
float: 温度°C
"""
if not temp_input:
return default_temp
if isinstance(temp_input, (int, float)):
return float(temp_input)
temp_str = str(temp_input).lower().strip()
# 特殊温度关键词
special_temps = {
"room temperature": 25.0, "reflux": 78.0, "ice bath": 0.0,
"boiling": 100.0, "hot": 60.0, "warm": 40.0, "cold": 10.0,
}
if temp_str in special_temps:
return special_temps[temp_str]
# 正则解析(如 "256 °C", "45°C", "45"
match = re.search(r'(\d+(?:\.\d+)?)\s*°?[cf]?', temp_str)
if match:
return float(match.group(1))
debug_print(f"无法解析温度: '{temp_str}',使用默认值: {default_temp}°C")
return default_temp
# 测试函数
def test_unit_parser():
"""测试单位解析功能"""

View File

@@ -1,23 +1,27 @@
import networkx as nx
from .logger_util import debug_print
from .resource_helper import get_resource_id, get_resource_data
def get_vessel(vessel):
"""
统一处理vessel参数返回vessel_id和vessel_data。
支持 dict、str、ResourceDictInstance。
Args:
vessel: 可以是一个字典字符串或 ResourceDictInstance表示vessel的ID或数据。
vessel: 可以是一个字典字符串表示vessel的ID或数据。
Returns:
tuple: 包含vessel_id和vessel_data。
"""
# 统一使用 resource_helper 处理
vessel_id = get_resource_id(vessel)
vessel_data = get_resource_data(vessel)
if isinstance(vessel, dict):
if "id" not in vessel:
vessel_id = list(vessel.values())[0].get("id", "")
else:
vessel_id = vessel.get("id", "")
vessel_data = vessel.get("data", {})
else:
vessel_id = str(vessel)
vessel_data = {}
return vessel_id, vessel_data
@@ -274,31 +278,4 @@ def find_solid_dispenser(G: nx.DiGraph) -> str:
return node
debug_print(f"❌ 未找到固体加样器")
return ""
def find_connected_heatchill(G: nx.DiGraph, vessel: str) -> str:
"""查找与指定容器相连的加热/冷却设备"""
heatchill_nodes = []
for node in G.nodes():
node_data = G.nodes[node]
node_class = node_data.get('class', '') or ''
node_name = node.lower()
if ('heatchill' in node_class.lower() or 'virtual_heatchill' in node_class
or 'heater' in node_name or 'heat' in node_name):
heatchill_nodes.append(node)
# 检查连接
if vessel and heatchill_nodes:
for hc in heatchill_nodes:
if G.has_edge(hc, vessel) or G.has_edge(vessel, hc):
debug_print(f"加热设备 '{hc}' 与容器 '{vessel}' 相连")
return hc
# 使用第一个可用设备
if heatchill_nodes:
debug_print(f"使用第一个加热设备: {heatchill_nodes[0]}")
return heatchill_nodes[0]
debug_print("未找到加热设备,使用默认设备")
return "heatchill_1"
return ""

View File

@@ -4,55 +4,199 @@ import logging
import re
from .utils.unit_parser import parse_time_input, parse_volume_input
from .utils.resource_helper import get_resource_id, get_resource_display_info, get_resource_liquid_volume, update_vessel_volume
from .utils.logger_util import debug_print
logger = logging.getLogger(__name__)
def debug_print(message):
"""调试输出"""
logger.info(f"[WASH_SOLID] {message}")
def find_solvent_source(G: nx.DiGraph, solvent: str) -> str:
"""查找溶剂源"""
"""查找溶剂源(精简版)"""
debug_print(f"🔍 查找溶剂源: {solvent}")
# 简化搜索列表
search_patterns = [
f"flask_{solvent}", f"bottle_{solvent}", f"reagent_{solvent}",
"liquid_reagent_bottle_1", "flask_1", "solvent_bottle"
]
for pattern in search_patterns:
if pattern in G.nodes():
debug_print(f"找到溶剂源: {pattern}")
debug_print(f"🎉 找到溶剂源: {pattern}")
return pattern
debug_print(f"使用默认溶剂源: flask_{solvent}")
debug_print(f"⚠️ 使用默认溶剂源: flask_{solvent}")
return f"flask_{solvent}"
def find_filtrate_vessel(G: nx.DiGraph, filtrate_vessel: str = "") -> str:
"""查找滤液容器"""
"""查找滤液容器(精简版)"""
debug_print(f"🔍 查找滤液容器: {filtrate_vessel}")
# 如果指定了且存在,直接使用
if filtrate_vessel and filtrate_vessel in G.nodes():
debug_print(f"✅ 使用指定容器: {filtrate_vessel}")
return filtrate_vessel
# 简化搜索列表
default_vessels = ["waste_workup", "filtrate_vessel", "flask_1", "collection_bottle_1"]
for vessel in default_vessels:
if vessel in G.nodes():
debug_print(f"找到滤液容器: {vessel}")
debug_print(f"🎉 找到滤液容器: {vessel}")
return vessel
debug_print(f"⚠️ 使用默认滤液容器: waste_workup")
return "waste_workup"
def extract_vessel_id(vessel) -> str:
"""从vessel参数中提取vessel_id兼容 str / dict / ResourceDictInstance"""
return get_resource_id(vessel)
def extract_vessel_id(vessel: Union[str, dict]) -> str:
"""
从vessel参数中提取vessel_id
Args:
vessel: vessel字典或vessel_id字符串
Returns:
str: vessel_id
"""
if isinstance(vessel, dict):
vessel_id = list(vessel.values())[0].get("id", "")
debug_print(f"🔧 从vessel字典提取ID: {vessel_id}")
return vessel_id
elif isinstance(vessel, str):
debug_print(f"🔧 vessel参数为字符串: {vessel}")
return vessel
else:
debug_print(f"⚠️ 无效的vessel参数类型: {type(vessel)}")
return ""
def get_vessel_display_info(vessel) -> str:
"""获取容器的显示信息(用于日志),兼容 str / dict / ResourceDictInstance"""
return get_resource_display_info(vessel)
def get_vessel_display_info(vessel: Union[str, dict]) -> str:
"""
获取容器的显示信息(用于日志)
Args:
vessel: vessel字典或vessel_id字符串
Returns:
str: 显示信息
"""
if isinstance(vessel, dict):
vessel_id = vessel.get("id", "unknown")
vessel_name = vessel.get("name", "")
if vessel_name:
return f"{vessel_id} ({vessel_name})"
else:
return vessel_id
else:
return str(vessel)
def get_vessel_liquid_volume(vessel: dict) -> float:
"""
获取容器中的液体体积 - 支持vessel字典
Args:
vessel: 容器字典
Returns:
float: 液体体积mL
"""
if not vessel or "data" not in vessel:
debug_print(f"⚠️ 容器数据为空,返回 0.0mL")
return 0.0
vessel_data = vessel["data"]
vessel_id = vessel.get("id", "unknown")
debug_print(f"🔍 读取容器 '{vessel_id}' 体积数据: {vessel_data}")
# 检查liquid_volume字段
if "liquid_volume" in vessel_data:
liquid_volume = vessel_data["liquid_volume"]
# 处理列表格式
if isinstance(liquid_volume, list):
if len(liquid_volume) > 0:
volume = liquid_volume[0]
if isinstance(volume, (int, float)):
debug_print(f"✅ 容器 '{vessel_id}' 体积: {volume}mL (列表格式)")
return float(volume)
# 处理直接数值格式
elif isinstance(liquid_volume, (int, float)):
debug_print(f"✅ 容器 '{vessel_id}' 体积: {liquid_volume}mL (数值格式)")
return float(liquid_volume)
# 检查其他可能的体积字段
volume_keys = ['current_volume', 'total_volume', 'volume']
for key in volume_keys:
if key in vessel_data:
try:
volume = float(vessel_data[key])
if volume > 0:
debug_print(f"✅ 容器 '{vessel_id}' 体积: {volume}mL (字段: {key})")
return volume
except (ValueError, TypeError):
continue
debug_print(f"⚠️ 无法获取容器 '{vessel_id}' 的体积,返回默认值 0.0mL")
return 0.0
def update_vessel_volume(vessel: dict, G: nx.DiGraph, new_volume: float, description: str = "") -> None:
"""
更新容器体积同时更新vessel字典和图节点
Args:
vessel: 容器字典
G: 网络图
new_volume: 新体积
description: 更新描述
"""
vessel_id = vessel.get("id", "unknown")
if description:
debug_print(f"🔧 更新容器体积 - {description}")
# 更新vessel字典中的体积
if "data" in vessel:
if "liquid_volume" in vessel["data"]:
current_volume = vessel["data"]["liquid_volume"]
if isinstance(current_volume, list):
if len(current_volume) > 0:
vessel["data"]["liquid_volume"][0] = new_volume
else:
vessel["data"]["liquid_volume"] = [new_volume]
else:
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"]["liquid_volume"] = new_volume
else:
vessel["data"] = {"liquid_volume": new_volume}
# 同时更新图中的容器数据
if vessel_id in G.nodes():
if 'data' not in G.nodes[vessel_id]:
G.nodes[vessel_id]['data'] = {}
vessel_node_data = G.nodes[vessel_id]['data']
current_node_volume = vessel_node_data.get('liquid_volume', 0.0)
if isinstance(current_node_volume, list):
if len(current_node_volume) > 0:
G.nodes[vessel_id]['data']['liquid_volume'][0] = new_volume
else:
G.nodes[vessel_id]['data']['liquid_volume'] = [new_volume]
else:
G.nodes[vessel_id]['data']['liquid_volume'] = new_volume
debug_print(f"📊 容器 '{vessel_id}' 体积已更新为: {new_volume:.2f}mL")
def generate_wash_solid_protocol(
G: nx.DiGraph,
vessel: Union[str, dict],
vessel: Union[str, dict], # 🔧 修改支持vessel字典
solvent: str,
volume: Union[float, str] = "50",
filtrate_vessel: Union[str, dict] = "",
filtrate_vessel: Union[str, dict] = "", # 🔧 修改支持vessel字典
temp: float = 25.0,
stir: bool = False,
stir_speed: float = 0.0,
@@ -66,7 +210,7 @@ def generate_wash_solid_protocol(
) -> List[Dict[str, Any]]:
"""
生成固体清洗协议 - 支持vessel字典和体积运算
Args:
G: 有向图,节点为设备和容器,边为流体管道
vessel: 清洗容器字典从XDL传入或容器ID字符串
@@ -83,78 +227,106 @@ def generate_wash_solid_protocol(
mass: 固体质量(用于计算溶剂用量)
event: 事件描述
**kwargs: 其他可选参数
Returns:
List[Dict[str, Any]]: 固体清洗操作的动作序列
"""
# 🔧 核心修改从vessel参数中提取vessel_id
vessel_id = extract_vessel_id(vessel)
vessel_display = get_vessel_display_info(vessel)
# 🔧 处理filtrate_vessel参数
filtrate_vessel_id = extract_vessel_id(filtrate_vessel) if filtrate_vessel else ""
debug_print(f"开始生成固体清洗协议: vessel={vessel_id}, solvent={solvent}, volume={volume}, repeats={repeats}")
# 记录清洗前的容器状态
debug_print("🧼" * 20)
debug_print("🚀 开始生成固体清洗协议支持vessel字典和体积运算")
debug_print(f"📝 输入参数:")
debug_print(f" 🥽 vessel: {vessel_display} (ID: {vessel_id})")
debug_print(f" 🧪 solvent: {solvent}")
debug_print(f" 💧 volume: {volume}")
debug_print(f" 🗑️ filtrate_vessel: {filtrate_vessel_id}")
debug_print(f" ⏰ time: {time}")
debug_print(f" 🔄 repeats: {repeats}")
debug_print("🧼" * 20)
# 🔧 新增:记录清洗前的容器状态
debug_print("🔍 记录清洗前容器状态...")
if isinstance(vessel, dict):
original_volume = get_resource_liquid_volume(vessel)
original_volume = get_vessel_liquid_volume(vessel)
debug_print(f"📊 清洗前液体体积: {original_volume:.2f}mL")
else:
original_volume = 0.0
# 快速验证
if not vessel_id or vessel_id not in G.nodes():
debug_print(f"📊 vessel为字符串格式无法获取体积信息")
# 📋 快速验证
if not vessel_id or vessel_id not in G.nodes(): # 🔧 使用 vessel_id
debug_print("❌ 容器验证失败! 😱")
raise ValueError("vessel 参数无效")
if not solvent:
debug_print("❌ 溶剂不能为空! 😱")
raise ValueError("solvent 参数不能为空")
# 参数解析
debug_print("✅ 基础验证通过 🎯")
# 🔄 参数解析
debug_print("📍 步骤1: 参数解析... ⚡")
final_volume = parse_volume_input(volume, volume_spec, mass)
final_time = parse_time_input(time)
# 重复次数处理
# 重复次数处理(简化)
if repeats_spec:
spec_map = {'few': 2, 'several': 3, 'many': 4, 'thorough': 5}
final_repeats = next((v for k, v in spec_map.items() if k in repeats_spec.lower()), repeats)
else:
final_repeats = max(1, min(repeats, 5))
# 模拟时间优化
final_repeats = max(1, min(repeats, 5)) # 限制1-5次
# 🕐 模拟时间优化
debug_print(" ⏱️ 模拟时间优化...")
original_time = final_time
if final_time > 60.0:
final_time = 60.0
debug_print(f"时间优化: {original_time}s -> {final_time}s")
final_time = 60.0 # 限制最长60秒
debug_print(f" 🎮 时间优化: {original_time}s {final_time}s")
# 参数修正
temp = max(25.0, min(temp, 80.0))
stir_speed = max(0.0, min(stir_speed, 300.0)) if stir else 0.0
debug_print(f"最终参数: 体积={final_volume}mL, 时间={final_time}s, 重复={final_repeats}")
# 查找设备
temp = max(25.0, min(temp, 80.0)) # 温度范围25-80°C
stir_speed = max(0.0, min(stir_speed, 300.0)) if stir else 0.0 # 速度范围0-300
debug_print(f"🎯 最终参数: 体积={final_volume}mL, 时间={final_time}s, 重复={final_repeats}")
# 🔍 查找设备
debug_print("📍 步骤2: 查找设备... 🔍")
try:
solvent_source = find_solvent_source(G, solvent)
actual_filtrate_vessel = find_filtrate_vessel(G, filtrate_vessel_id)
debug_print(f"🎉 设备配置完成 ✨")
debug_print(f" 🧪 溶剂源: {solvent_source}")
debug_print(f" 🗑️ 滤液容器: {actual_filtrate_vessel}")
except Exception as e:
debug_print(f"❌ 设备查找失败: {str(e)} 😭")
raise ValueError(f"设备查找失败: {str(e)}")
# 生成动作序列
# 🚀 生成动作序列
debug_print("📍 步骤3: 生成清洗动作... 🧼")
action_sequence = []
# 🔧 新增:体积变化跟踪变量
current_volume = original_volume
total_solvent_used = 0.0
for cycle in range(final_repeats):
debug_print(f"{cycle+1}/{final_repeats}次清洗")
debug_print(f" 🔄 {cycle+1}/{final_repeats}次清洗...")
# 1. 转移溶剂
try:
from .pump_protocol import generate_pump_protocol_with_rinsing
debug_print(f" 💧 添加溶剂: {final_volume}mL {solvent}")
transfer_actions = generate_pump_protocol_with_rinsing(
G=G,
from_vessel=solvent_source,
to_vessel=vessel_id,
to_vessel=vessel_id, # 🔧 使用 vessel_id
volume=final_volume,
amount="",
time=0.0,
@@ -166,160 +338,211 @@ def generate_wash_solid_protocol(
flowrate=2.5,
transfer_flowrate=0.5
)
if transfer_actions:
action_sequence.extend(transfer_actions)
debug_print(f" ✅ 转移动作: {len(transfer_actions)}个 🚚")
# 🔧 新增:更新体积 - 添加溶剂后
current_volume += final_volume
total_solvent_used += final_volume
if isinstance(vessel, dict):
update_vessel_volume(vessel, G, current_volume,
update_vessel_volume(vessel, G, current_volume,
f"{cycle+1}次清洗添加{final_volume}mL溶剂后")
except Exception as e:
debug_print(f"转移失败: {str(e)}")
debug_print(f"转移失败: {str(e)} 😞")
# 2. 搅拌(如果需要)
if stir and final_time > 0:
debug_print(f" 🌪️ 搅拌: {final_time}s @ {stir_speed}RPM")
stir_action = {
"device_id": "stirrer_1",
"action_name": "stir",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
"time": str(time),
"stir_time": final_time,
"stir_speed": stir_speed,
"settling_time": 10.0
"settling_time": 10.0 # 🕐 缩短沉降时间
}
}
action_sequence.append(stir_action)
debug_print(f" ✅ 搅拌动作: {final_time}s, {stir_speed}RPM 🌪️")
# 3. 过滤
debug_print(f" 🌊 过滤到: {actual_filtrate_vessel}")
filter_action = {
"device_id": "filter_1",
"action_name": "filter",
"action_kwargs": {
"vessel": {"id": vessel_id},
"vessel": {"id": vessel_id}, # 🔧 使用 vessel_id
"filtrate_vessel": actual_filtrate_vessel,
"temp": temp,
"volume": final_volume
}
}
action_sequence.append(filter_action)
# 更新体积 - 过滤后
filtered_volume = current_volume * 0.9
debug_print(f" ✅ 过滤动作: → {actual_filtrate_vessel} 🌊")
# 🔧 新增:更新体积 - 过滤后(液体被滤除)
# 假设滤液完全被移除,固体残留在容器中
filtered_volume = current_volume * 0.9 # 假设90%的液体被过滤掉
current_volume = current_volume - filtered_volume
if isinstance(vessel, dict):
update_vessel_volume(vessel, G, current_volume,
update_vessel_volume(vessel, G, current_volume,
f"{cycle+1}次清洗过滤后")
# 4. 等待
wait_time = 5.0
# 4. 等待(缩短时间)
wait_time = 5.0 # 🕐 缩短等待时间10s → 5s
action_sequence.append({
"action_name": "wait",
"action_kwargs": {"time": wait_time}
})
# 最终状态
debug_print(f" ✅ 等待: {wait_time}s ⏰")
# 🔧 新增:清洗完成后的最终状态报告
if isinstance(vessel, dict):
final_volume_vessel = get_resource_liquid_volume(vessel)
final_volume_vessel = get_vessel_liquid_volume(vessel)
else:
final_volume_vessel = current_volume
debug_print(f"固体清洗协议生成完成: {len(action_sequence)} 个动作, {final_repeats}次清洗, 溶剂总用量={total_solvent_used:.2f}mL")
# 🎊 总结
debug_print("🧼" * 20)
debug_print(f"🎉 固体清洗协议生成完成! ✨")
debug_print(f"📊 协议统计:")
debug_print(f" 📋 总动作数: {len(action_sequence)}")
debug_print(f" 🥽 清洗容器: {vessel_display}")
debug_print(f" 🧪 使用溶剂: {solvent}")
debug_print(f" 💧 单次体积: {final_volume}mL")
debug_print(f" 🔄 清洗次数: {final_repeats}")
debug_print(f" 💧 总溶剂用量: {total_solvent_used:.2f}mL")
debug_print(f"📊 体积变化统计:")
debug_print(f" - 清洗前体积: {original_volume:.2f}mL")
debug_print(f" - 清洗后体积: {final_volume_vessel:.2f}mL")
debug_print(f" - 溶剂总用量: {total_solvent_used:.2f}mL")
debug_print(f"⏱️ 预计总时间: {(final_time + 5) * final_repeats / 60:.1f} 分钟")
debug_print("🧼" * 20)
return action_sequence
# 便捷函数
def wash_with_water(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "50",
# 🔧 新增:便捷函数
def wash_with_water(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "50",
repeats: int = 2) -> List[Dict[str, Any]]:
"""用水清洗固体"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"💧 水洗固体: {vessel_display} ({repeats} 次)")
return generate_wash_solid_protocol(G, vessel, "water", volume=volume, repeats=repeats)
def wash_with_ethanol(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "30",
def wash_with_ethanol(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "30",
repeats: int = 1) -> List[Dict[str, Any]]:
"""用乙醇清洗固体"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"🍺 乙醇洗固体: {vessel_display} ({repeats} 次)")
return generate_wash_solid_protocol(G, vessel, "ethanol", volume=volume, repeats=repeats)
def wash_with_acetone(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "25",
def wash_with_acetone(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "25",
repeats: int = 1) -> List[Dict[str, Any]]:
"""用丙酮清洗固体"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"💨 丙酮洗固体: {vessel_display} ({repeats} 次)")
return generate_wash_solid_protocol(G, vessel, "acetone", volume=volume, repeats=repeats)
def wash_with_ether(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "40",
def wash_with_ether(G: nx.DiGraph, vessel: Union[str, dict],
volume: Union[float, str] = "40",
repeats: int = 2) -> List[Dict[str, Any]]:
"""用乙醚清洗固体"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"🌬️ 乙醚洗固体: {vessel_display} ({repeats} 次)")
return generate_wash_solid_protocol(G, vessel, "diethyl_ether", volume=volume, repeats=repeats)
def wash_with_cold_solvent(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "30",
def wash_with_cold_solvent(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "30",
repeats: int = 1) -> List[Dict[str, Any]]:
"""用冷溶剂清洗固体"""
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume,
vessel_display = get_vessel_display_info(vessel)
debug_print(f"❄️ 冷{solvent}洗固体: {vessel_display} ({repeats} 次)")
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume,
temp=5.0, repeats=repeats)
def wash_with_hot_solvent(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "50",
def wash_with_hot_solvent(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "50",
repeats: int = 1) -> List[Dict[str, Any]]:
"""用热溶剂清洗固体"""
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume,
vessel_display = get_vessel_display_info(vessel)
debug_print(f"🔥 热{solvent}洗固体: {vessel_display} ({repeats} 次)")
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume,
temp=60.0, repeats=repeats)
def wash_with_stirring(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "50",
stir_time: Union[str, float] = "5 min",
def wash_with_stirring(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "50",
stir_time: Union[str, float] = "5 min",
repeats: int = 1) -> List[Dict[str, Any]]:
"""带搅拌的溶剂清洗"""
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume,
stir=True, stir_speed=200.0,
vessel_display = get_vessel_display_info(vessel)
debug_print(f"🌪️ 搅拌清洗: {vessel_display} with {solvent} ({repeats} 次)")
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume,
stir=True, stir_speed=200.0,
time=stir_time, repeats=repeats)
def thorough_wash(G: nx.DiGraph, vessel: Union[str, dict],
def thorough_wash(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "50") -> List[Dict[str, Any]]:
"""彻底清洗(多次重复)"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"🔄 彻底清洗: {vessel_display} with {solvent} (5 次)")
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume, repeats=5)
def quick_rinse(G: nx.DiGraph, vessel: Union[str, dict],
def quick_rinse(G: nx.DiGraph, vessel: Union[str, dict],
solvent: str, volume: Union[float, str] = "20") -> List[Dict[str, Any]]:
"""快速冲洗(单次,小体积)"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"⚡ 快速冲洗: {vessel_display} with {solvent}")
return generate_wash_solid_protocol(G, vessel, solvent, volume=volume, repeats=1)
def sequential_wash(G: nx.DiGraph, vessel: Union[str, dict],
def sequential_wash(G: nx.DiGraph, vessel: Union[str, dict],
solvents: list, volume: Union[float, str] = "40") -> List[Dict[str, Any]]:
"""连续多溶剂清洗"""
vessel_display = get_vessel_display_info(vessel)
debug_print(f"📝 连续清洗: {vessel_display} with {''.join(solvents)}")
action_sequence = []
for solvent in solvents:
wash_actions = generate_wash_solid_protocol(G, vessel, solvent,
wash_actions = generate_wash_solid_protocol(G, vessel, solvent,
volume=volume, repeats=1)
action_sequence.extend(wash_actions)
return action_sequence
# 测试函数
def test_wash_solid_protocol():
"""测试固体清洗协议"""
debug_print("=== WASH SOLID PROTOCOL 测试 ===")
vessel_dict = {"id": "filter_flask_1", "name": "过滤瓶1",
debug_print("🧪 === WASH SOLID PROTOCOL 测试 ===")
# 测试vessel参数处理
debug_print("🔧 测试vessel参数处理...")
# 测试字典格式
vessel_dict = {"id": "filter_flask_1", "name": "过滤瓶1",
"data": {"liquid_volume": 25.0}}
vessel_id = extract_vessel_id(vessel_dict)
vessel_display = get_vessel_display_info(vessel_dict)
volume = get_resource_liquid_volume(vessel_dict)
debug_print(f"字典格式: ID={vessel_id}, 显示={vessel_display}, 体积={volume}mL")
volume = get_vessel_liquid_volume(vessel_dict)
debug_print(f" 字典格式: {vessel_dict}")
debug_print(f" → ID: {vessel_id}, 显示: {vessel_display}, 体积: {volume}mL")
# 测试字符串格式
vessel_str = "filter_flask_2"
vessel_id = extract_vessel_id(vessel_str)
vessel_display = get_vessel_display_info(vessel_str)
debug_print(f"字符串格式: ID={vessel_id}, 显示={vessel_display}")
debug_print("测试完成")
debug_print(f" 字符串格式: {vessel_str}")
debug_print(f" → ID: {vessel_id}, 显示: {vessel_display}")
debug_print("✅ 测试完成 🎉")
if __name__ == "__main__":
test_wash_solid_protocol()
test_wash_solid_protocol()

View File

@@ -46,7 +46,7 @@ class WSConfig:
# HTTP配置
class HTTPConfig:
remote_addr = "https://uni-lab.bohrium.com/api/v1"
remote_addr = "https://leap-lab.bohrium.com/api/v1"
# ROS配置

View File

@@ -0,0 +1,78 @@
# Donghua EC 用户指南UniLab 接入版)
## 概述
- 提供两套使用方式:
- 测试封装动作:一条指令完成“启动实验 → 实时采样写文件 → 导出数据”,可选自动停止。
- 基础启动动作:按需组合“启动实验、实时输出、停止、导出”,更灵活可编排。
## 设备配置
- `interface_dir`DHInterface 目录(包含 `ECCore.dll` 与配置文件),示例:`d:\Uni-Lab-OS\Uni-Lab-OS\unilabos\devices\donghua_ec\x64release\DHInterface`(注册见 `unilabos/registry/devices/donghua_ec.yaml:1940`)。
- `dll_path`(可选):若与 `interface_dir` 不一致,可直接指定 `ECCore.dll` 完整路径(`donghua_ec.yaml:1936`)。
- 默认通道:`machine_id``donghua_ec.yaml:1944`)。
## 初始化
- 后端自动:设备注册后会自动调用 `auto-initialize`(加载 DLL`auto-post_init`(注入),无需前端干预(`donghua_ec.yaml:27``donghua_ec.yaml:48`)。
- 手动(可选):
- 调用 `auto-initialize``{"device_id":"<设备ID>","action":"auto-initialize"}`
- 调用 `auto-post_init``{"device_id":"<设备ID>","action":"auto-post_init"}`
## 动作总览
- 测试封装动作(均要求传入 `output_dir`
- `test_open_circuit_energy`(默认 `stop_after=true`,使用轮询检测实验结束后再停止与导出,不再使用 `wait_seconds`
- `test_eis`(默认 `stop_after=false`,避免提前结束,`donghua_ec.yaml:1480`
- `test_gitt`(默认 `stop_after=false``donghua_ec.yaml:1627`
- `test_linear_scan_voltammetry`(默认 `stop_after=false`,必填 `output_dir`,参考 `donghua_ec.yaml:1750` 及后续)
- 基础启动与组合:
- `start_open_circuit_energy``start_eis``start_gitt``start_linear_scan_voltammetry`
- 实时输出:`start_realtime_output` / `stop_realtime_output``donghua_ec.yaml:1068``donghua_ec.yaml:1155`
- 停止实验:`stop_experiment``donghua_ec.yaml:1118`
- 导出数据:`export_*_data`(如 `export_eis_data``export_gitt_data` 等,均要求 `output_dir/dest_dir`
## 快速测试流程(推荐)
- 开路电位:
- 请求:
```json
{"device_id":"<设备ID>","action":"test_open_circuit_energy","action_args":{"output_dir":"d:/data/oc","interval":0.5,"stop_after":true}}
```
- 返回包含:`success`、`realtime_file`、`export_files`、`export_dest`。
- 阻抗EIS
- 请求(只需给导出目录,其他用默认即可):
```json
{"device_id":"<设备ID>","action":"test_eis","action_args":{"output_dir":"d:/data/eis","start_freq":10000,"end_freq":0.1,"amplitude":0.01,"point_count":10,"interval":0.5}}
```
- 默认不自动停止(`stop_after=false`),可在完成采样后继续扫频;若需自动停,传 `stop_after=true`。
- GITT
- 请求:
```json
{"device_id":"<设备ID>","action":"test_gitt","action_args":{"output_dir":"d:/data/gitt","current":1.0,"time_per_point_cc":0.1,"continue_time_cc":60,"time_per_point_oc":0.1,"continue_time_oc":60,"is_voltage_trig":true,"voltage_or_current_trig_direction":0,"voltage_or_current_trig_value":0,"interval":0.5}}
```
## 基础启动与组合(灵活编排)
- 启动 EIS
- `{"device_id":"<设备ID>","action":"start_eis","action_args":{"start_freq":10000,"end_freq":0.1,"amplitude":0.01,"point_count":10}}`
- 开启实时输出:
- `{"device_id":"<设备ID>","action":"start_realtime_output","action_args":{"interval":0.5}}`
- 关闭实时输出并获取文件:
- `{"device_id":"<设备ID>","action":"stop_realtime_output"}`
- 导出数据到目录:
- `{"device_id":"<设备ID>","action":"export_eis_data","action_args":{"output_dir":"d:/data/eis"}}`
- 停止实验(可选):
- `{"device_id":"<设备ID>","action":"stop_experiment"}`
## 重要说明
- 必填导出目录:所有 `test_*` 和 `export_*` 动作需要提供 `output_dir`(或 `dest_dir`),否则不会复制数据到目标位置(`donghua_ec.yaml:1545`、`donghua_ec.yaml:1710`)。
- 关于提前结束:非开路的测试封装动作默认 `stop_after=false`,避免在实时采样后调用 `stop_experiment`,从而导致频率扫描未达到 `end_freq` 就停止(修复见 `donghua_ec.yaml:1480`、`donghua_ec.yaml:1627`)。
- 实时文件位置:若未指定 `dest_dir`,实时输出会写入 `interface_dir/SourceData/<日期>/<实验子目录>`(实现参考 `unilabos/devices/donghua_ec/donghua_ec.py:1042`)。
## 数据字段(参考)
- EIS 拆分:`time/zre/zim/z/freq/phase/edc`(实现参考 `unilabos/devices/donghua_ec/donghua_ec.py:1109`)。
- 线性扫描与循环伏安:`time/potential/current` 等(实现参考 `donghua_ec.py:1111`、`donghua_ec.py:1114`)。
- 开路电位:写入时间序列与电位(`donghua_ec.py:1045`)。

View File

@@ -0,0 +1,3 @@
from .donghua_ec import DonghuaEC
__all__ = ["DonghuaEC"]

View File

@@ -0,0 +1,24 @@
{
"nodes": [
{
"id": "donghua_ec_device",
"name": "Donghua_EC",
"parent": null,
"type": "device",
"class": "donghua_ec",
"position": {
"x": 620.6111111111111,
"y": 171,
"z": 0
},
"config": {
"interface_dir": "D:/Uni-Lab-OS/Uni-Lab-OS/unilabos/devices/donghua_ec/x64release/DHInterface",
"dll_path": "",
"machine_id": 0
},
"data": {},
"children": []
}
],
"links": []
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,358 @@
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000

View File

@@ -0,0 +1,398 @@
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 1992.742065 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 1992.826050 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 1993.161743 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 1993.077881 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 1992.154907 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 1992.909912 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 1993.077881 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 1993.161743 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 1992.826050 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 1993.161743 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 1992.742065 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 1992.993896 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 1992.742065 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 1992.909912 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 1993.077881 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 1993.916748 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 1994.000732 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 1993.413452 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 1992.993896 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 1993.581177 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 1993.413452 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 1993.497314 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 1993.161743 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 1993.916748 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 1993.749023 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 1994.000732 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 1994.084717 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 1993.749023 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 1993.916748 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 1993.497314 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 1993.749023 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 1993.413452 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 1993.749023 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 1994.168579 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 1993.916748 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 1993.497314 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 1994.084717 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 1994.084717 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 1994.420288 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 1994.504150 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 1994.168579 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 1994.336426 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 1994.504150 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 1994.923706 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 1995.427246 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 1994.923706 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 1995.678833 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 1995.762817 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 1994.923706 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 1996.685791 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 1995.762817 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 1994.420288 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 1993.329590 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 1993.077881 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 1992.742065 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 1993.245605 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 1993.329590 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 1994.336426 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 1995.343262 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 1995.427246 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 1995.594971 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
10.100000 1994.504150 0.000000 0.000000 0.000000 0.000000 0.000000
10.200000 1994.336426 0.000000 0.000000 0.000000 0.000000 0.000000
10.300000 1994.000732 0.000000 0.000000 0.000000 0.000000 0.000000
10.400000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
10.500000 1993.329590 0.000000 0.000000 0.000000 0.000000 0.000000
10.600000 1994.000732 0.000000 0.000000 0.000000 0.000000 0.000000
10.700000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
10.800000 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
10.900000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
11.000000 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
11.100000 1994.923706 0.000000 0.000000 0.000000 0.000000 0.000000
11.200000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
11.300000 1996.014404 0.000000 0.000000 0.000000 0.000000 0.000000
11.400000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
11.500000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
11.600000 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
11.700000 1995.343262 0.000000 0.000000 0.000000 0.000000 0.000000
11.800000 1996.014404 0.000000 0.000000 0.000000 0.000000 0.000000
11.900000 1995.762817 0.000000 0.000000 0.000000 0.000000 0.000000
12.000000 1995.678833 0.000000 0.000000 0.000000 0.000000 0.000000
12.100000 1996.434082 0.000000 0.000000 0.000000 0.000000 0.000000
12.200000 1996.098389 0.000000 0.000000 0.000000 0.000000 0.000000
12.300000 1995.343262 0.000000 0.000000 0.000000 0.000000 0.000000
12.400000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
12.500000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
12.600000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
12.700000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
12.800000 1995.678833 0.000000 0.000000 0.000000 0.000000 0.000000
12.900000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
13.000000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
13.100000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
13.200000 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
13.300000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
13.400000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
13.500000 1995.762817 0.000000 0.000000 0.000000 0.000000 0.000000
13.600000 1995.930542 0.000000 0.000000 0.000000 0.000000 0.000000
13.700000 1995.343262 0.000000 0.000000 0.000000 0.000000 0.000000
13.800000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
13.900000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
14.000000 1995.678833 0.000000 0.000000 0.000000 0.000000 0.000000
14.100000 1996.182251 0.000000 0.000000 0.000000 0.000000 0.000000
14.200000 1996.434082 0.000000 0.000000 0.000000 0.000000 0.000000
14.300000 1995.846680 0.000000 0.000000 0.000000 0.000000 0.000000
14.400000 1996.350220 0.000000 0.000000 0.000000 0.000000 0.000000
14.500000 1996.098389 0.000000 0.000000 0.000000 0.000000 0.000000
14.600000 1995.343262 0.000000 0.000000 0.000000 0.000000 0.000000
14.700000 1995.427246 0.000000 0.000000 0.000000 0.000000 0.000000
14.800000 1995.427246 0.000000 0.000000 0.000000 0.000000 0.000000
14.900000 1995.511108 0.000000 0.000000 0.000000 0.000000 0.000000
15.000000 1995.678833 0.000000 0.000000 0.000000 0.000000 0.000000
15.100000 1995.343262 0.000000 0.000000 0.000000 0.000000 0.000000
15.200000 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
15.300000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
15.400000 1995.427246 0.000000 0.000000 0.000000 0.000000 0.000000
15.500000 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
15.600000 1995.175415 0.000000 0.000000 0.000000 0.000000 0.000000
15.700000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
15.800000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
15.900000 1993.665161 0.000000 0.000000 0.000000 0.000000 0.000000
16.000000 1994.084717 0.000000 0.000000 0.000000 0.000000 0.000000
16.100000 1994.168579 0.000000 0.000000 0.000000 0.000000 0.000000
16.200001 1994.252563 0.000000 0.000000 0.000000 0.000000 0.000000
16.299999 1994.839722 0.000000 0.000000 0.000000 0.000000 0.000000
16.400000 1996.350220 0.000000 0.000000 0.000000 0.000000 0.000000
16.500000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
16.600000 1994.588135 0.000000 0.000000 0.000000 0.000000 0.000000
16.700001 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
16.799999 1995.259399 0.000000 0.000000 0.000000 0.000000 0.000000
16.900000 1995.427246 0.000000 0.000000 0.000000 0.000000 0.000000
17.000000 1995.427246 0.000000 0.000000 0.000000 0.000000 0.000000
17.100000 1995.091431 0.000000 0.000000 0.000000 0.000000 0.000000
17.200001 1994.839722 0.000000 0.000000 0.000000 0.000000 0.000000
17.299999 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
17.400000 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
17.500000 1994.588135 0.000000 0.000000 0.000000 0.000000 0.000000
17.600000 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
17.700001 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
17.799999 1994.420288 0.000000 0.000000 0.000000 0.000000 0.000000
17.900000 1994.336426 0.000000 0.000000 0.000000 0.000000 0.000000
18.000000 1994.420288 0.000000 0.000000 0.000000 0.000000 0.000000
18.100000 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
18.200001 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
18.299999 1994.923706 0.000000 0.000000 0.000000 0.000000 0.000000
18.400000 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
18.500000 1994.839722 0.000000 0.000000 0.000000 0.000000 0.000000
18.600000 1993.832886 0.000000 0.000000 0.000000 0.000000 0.000000
18.700001 1994.588135 0.000000 0.000000 0.000000 0.000000 0.000000
18.799999 1994.839722 0.000000 0.000000 0.000000 0.000000 0.000000
18.900000 1994.839722 0.000000 0.000000 0.000000 0.000000 0.000000
19.000000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
19.100000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
19.200001 1994.588135 0.000000 0.000000 0.000000 0.000000 0.000000
19.299999 1994.420288 0.000000 0.000000 0.000000 0.000000 0.000000
19.400000 1994.336426 0.000000 0.000000 0.000000 0.000000 0.000000
19.500000 1994.336426 0.000000 0.000000 0.000000 0.000000 0.000000
19.600000 1994.671997 0.000000 0.000000 0.000000 0.000000 0.000000
19.700001 1994.755859 0.000000 0.000000 0.000000 0.000000 0.000000
19.799999 1995.007568 0.000000 0.000000 0.000000 0.000000 0.000000
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 2057.013672 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 2057.684814 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 2057.936523 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 2058.020508 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 2058.523682 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 2058.775635 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 2058.775635 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 2058.859619 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 2059.362793 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 2059.279053 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 2059.446777 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 2060.034180 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 2060.285889 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 2060.201904 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 2060.537598 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 2060.789307 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 2061.041016 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 2061.125000 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 2061.628418 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 2061.880127 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 2061.963867 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 2062.047852 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 2062.383545 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 2062.718994 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 2062.718994 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 2062.970703 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 2063.306396 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 2063.306396 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 2063.558105 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 2063.642090 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 2064.061523 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 2064.061523 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 2064.229248 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 2064.229248 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 2064.732910 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 2064.732910 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 2065.236328 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 2065.152344 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 2065.404053 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 2065.320068 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 2065.739746 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 2065.907471 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 2065.991455 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 2065.991455 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 2065.991455 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 2066.326904 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 2066.830566 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 2066.578613 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 2066.998291 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 2067.333984 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 2067.585449 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 2067.585449 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 2067.669434 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 2067.837402 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 2067.921387 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 2068.173096 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 2068.340820 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 2068.592529 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 2068.760254 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 2068.592529 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 2068.760254 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 2069.095947 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 2069.095947 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 2069.011963 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 2069.683105 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 2069.599365 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 2069.767090 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 2069.767090 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 2069.851074 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 2070.186768 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 2069.851074 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 2070.354492 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 2070.186768 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 2070.606201 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 2070.773926 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 2070.606201 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 2071.109619 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 2070.773926 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 2071.109619 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 2071.025635 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 2071.361328 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 2071.445312 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 2071.445312 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 2071.529297 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 2071.864746 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 2072.116455 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 2071.948730 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 2071.948730 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 2072.284424 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 2072.368164 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 2072.452148 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 2072.619873 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 2072.955566 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 2072.871582 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 2072.955566 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 2073.207275 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 2073.207275 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 2073.458984 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 2073.291016 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 2073.458984 0.000000 0.000000 0.000000 0.000000 0.000000
10.100000 2073.458984 0.000000 0.000000 0.000000 0.000000 0.000000
10.200000 2073.878418 0.000000 0.000000 0.000000 0.000000 0.000000
10.300000 2073.794678 0.000000 0.000000 0.000000 0.000000 0.000000
10.400000 2074.046387 0.000000 0.000000 0.000000 0.000000 0.000000
10.500000 2074.046387 0.000000 0.000000 0.000000 0.000000 0.000000
10.600000 2073.962402 0.000000 0.000000 0.000000 0.000000 0.000000
10.700000 2074.214111 0.000000 0.000000 0.000000 0.000000 0.000000
10.800000 2074.214111 0.000000 0.000000 0.000000 0.000000 0.000000
10.900000 2074.130127 0.000000 0.000000 0.000000 0.000000 0.000000
11.000000 2074.717529 0.000000 0.000000 0.000000 0.000000 0.000000
11.100000 2074.549805 0.000000 0.000000 0.000000 0.000000 0.000000
11.200000 2074.801514 0.000000 0.000000 0.000000 0.000000 0.000000
11.300000 2074.885498 0.000000 0.000000 0.000000 0.000000 0.000000
11.400000 2074.885498 0.000000 0.000000 0.000000 0.000000 0.000000
11.500000 2074.801514 0.000000 0.000000 0.000000 0.000000 0.000000
11.600000 2075.137207 0.000000 0.000000 0.000000 0.000000 0.000000
11.700000 2075.137207 0.000000 0.000000 0.000000 0.000000 0.000000
11.800000 2075.220947 0.000000 0.000000 0.000000 0.000000 0.000000
11.900000 2075.304932 0.000000 0.000000 0.000000 0.000000 0.000000
12.000000 2075.556641 0.000000 0.000000 0.000000 0.000000 0.000000
12.100000 2075.388672 0.000000 0.000000 0.000000 0.000000 0.000000
12.200000 2075.808350 0.000000 0.000000 0.000000 0.000000 0.000000
12.300000 2075.808350 0.000000 0.000000 0.000000 0.000000 0.000000
12.400000 2075.808350 0.000000 0.000000 0.000000 0.000000 0.000000
12.500000 2075.892334 0.000000 0.000000 0.000000 0.000000 0.000000
12.600000 2075.892334 0.000000 0.000000 0.000000 0.000000 0.000000
12.700000 2075.976074 0.000000 0.000000 0.000000 0.000000 0.000000
12.800000 2076.144043 0.000000 0.000000 0.000000 0.000000 0.000000
12.900000 2076.060059 0.000000 0.000000 0.000000 0.000000 0.000000
13.000000 2076.395752 0.000000 0.000000 0.000000 0.000000 0.000000
13.100000 2076.395752 0.000000 0.000000 0.000000 0.000000 0.000000
13.200000 2076.479492 0.000000 0.000000 0.000000 0.000000 0.000000
13.300000 2076.563477 0.000000 0.000000 0.000000 0.000000 0.000000
13.400000 2076.563477 0.000000 0.000000 0.000000 0.000000 0.000000
13.500000 2076.731201 0.000000 0.000000 0.000000 0.000000 0.000000
13.600000 2076.983154 0.000000 0.000000 0.000000 0.000000 0.000000
13.700000 2077.150879 0.000000 0.000000 0.000000 0.000000 0.000000
13.800000 2077.066895 0.000000 0.000000 0.000000 0.000000 0.000000
13.900000 2077.402588 0.000000 0.000000 0.000000 0.000000 0.000000
14.000000 2077.318604 0.000000 0.000000 0.000000 0.000000 0.000000
14.100000 2077.402588 0.000000 0.000000 0.000000 0.000000 0.000000
14.200000 2077.486328 0.000000 0.000000 0.000000 0.000000 0.000000
14.300000 2077.570312 0.000000 0.000000 0.000000 0.000000 0.000000
14.400000 2077.570312 0.000000 0.000000 0.000000 0.000000 0.000000
14.500000 2078.073730 0.000000 0.000000 0.000000 0.000000 0.000000
14.600000 2077.906006 0.000000 0.000000 0.000000 0.000000 0.000000
14.700000 2077.822021 0.000000 0.000000 0.000000 0.000000 0.000000
14.800000 2078.073730 0.000000 0.000000 0.000000 0.000000 0.000000
14.900000 2078.157715 0.000000 0.000000 0.000000 0.000000 0.000000
15.000000 2078.157715 0.000000 0.000000 0.000000 0.000000 0.000000
15.100000 2078.241699 0.000000 0.000000 0.000000 0.000000 0.000000
15.200000 2078.409424 0.000000 0.000000 0.000000 0.000000 0.000000
15.300000 2078.409424 0.000000 0.000000 0.000000 0.000000 0.000000
15.400000 2078.661133 0.000000 0.000000 0.000000 0.000000 0.000000
15.500000 2078.828857 0.000000 0.000000 0.000000 0.000000 0.000000
15.600000 2078.577148 0.000000 0.000000 0.000000 0.000000 0.000000
15.700000 2078.912842 0.000000 0.000000 0.000000 0.000000 0.000000
15.800000 2078.996582 0.000000 0.000000 0.000000 0.000000 0.000000
15.900000 2078.996582 0.000000 0.000000 0.000000 0.000000 0.000000
16.000000 2079.248535 0.000000 0.000000 0.000000 0.000000 0.000000
16.100000 2079.332275 0.000000 0.000000 0.000000 0.000000 0.000000
16.200001 2079.248535 0.000000 0.000000 0.000000 0.000000 0.000000
16.299999 2079.500244 0.000000 0.000000 0.000000 0.000000 0.000000
16.400000 2079.667969 0.000000 0.000000 0.000000 0.000000 0.000000
16.500000 2079.835693 0.000000 0.000000 0.000000 0.000000 0.000000
16.600000 2079.835693 0.000000 0.000000 0.000000 0.000000 0.000000
16.700001 2079.583984 0.000000 0.000000 0.000000 0.000000 0.000000
16.799999 2079.919678 0.000000 0.000000 0.000000 0.000000 0.000000
16.900000 2080.171387 0.000000 0.000000 0.000000 0.000000 0.000000
17.000000 2080.003662 0.000000 0.000000 0.000000 0.000000 0.000000
17.100000 2080.087402 0.000000 0.000000 0.000000 0.000000 0.000000
17.200001 2080.171387 0.000000 0.000000 0.000000 0.000000 0.000000
17.299999 2080.003662 0.000000 0.000000 0.000000 0.000000 0.000000
17.400000 2080.255371 0.000000 0.000000 0.000000 0.000000 0.000000
17.500000 2080.507080 0.000000 0.000000 0.000000 0.000000 0.000000
17.600000 2080.674805 0.000000 0.000000 0.000000 0.000000 0.000000
17.700001 2080.758789 0.000000 0.000000 0.000000 0.000000 0.000000
17.799999 2080.591064 0.000000 0.000000 0.000000 0.000000 0.000000
17.900000 2080.758789 0.000000 0.000000 0.000000 0.000000 0.000000
18.000000 2080.926514 0.000000 0.000000 0.000000 0.000000 0.000000
18.100000 2080.926514 0.000000 0.000000 0.000000 0.000000 0.000000
18.200001 2081.094238 0.000000 0.000000 0.000000 0.000000 0.000000
18.299999 2081.262207 0.000000 0.000000 0.000000 0.000000 0.000000
18.400000 2081.346191 0.000000 0.000000 0.000000 0.000000 0.000000
18.500000 2081.429932 0.000000 0.000000 0.000000 0.000000 0.000000
18.600000 2081.262207 0.000000 0.000000 0.000000 0.000000 0.000000
18.700001 2081.597900 0.000000 0.000000 0.000000 0.000000 0.000000
18.799999 2081.681641 0.000000 0.000000 0.000000 0.000000 0.000000
18.900000 2081.513916 0.000000 0.000000 0.000000 0.000000 0.000000
19.000000 2081.681641 0.000000 0.000000 0.000000 0.000000 0.000000
19.100000 2082.101318 0.000000 0.000000 0.000000 0.000000 0.000000
19.200001 2082.017334 0.000000 0.000000 0.000000 0.000000 0.000000
19.299999 2081.849609 0.000000 0.000000 0.000000 0.000000 0.000000
19.400000 2082.017334 0.000000 0.000000 0.000000 0.000000 0.000000
19.500000 2082.101318 0.000000 0.000000 0.000000 0.000000 0.000000
19.600000 2082.352783 0.000000 0.000000 0.000000 0.000000 0.000000
19.700001 2082.269043 0.000000 0.000000 0.000000 0.000000 0.000000
19.799999 2082.604736 0.000000 0.000000 0.000000 0.000000 0.000000

View File

@@ -0,0 +1,597 @@
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
11.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
12.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
13.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
14.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
15.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
16.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
17.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
18.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.200001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.299999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.700001 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
19.799999 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000

View File

@@ -0,0 +1,101 @@
Time(s) E(mV) I(mA) Q(mC) Capacity(mAh) Energy(Wh) P(W)
0.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
4.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
5.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
6.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
7.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
8.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.100000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.200000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.300000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.400000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.500000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.600000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.700000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.800000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
9.900000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
10.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000

View File

@@ -0,0 +1,981 @@
Time(s) E(mV) I(mA)
0.010000 -997.723450 -5.245421
0.020000 -996.045349 -5.010738
0.030000 -993.947693 -4.961776
0.040000 -991.682251 -4.928009
0.050000 -989.752441 -4.899306
0.060000 -987.990417 -5.074349
0.070000 -985.641052 -4.800336
0.080000 -983.879028 -4.896254
0.090000 -981.697510 -4.842570
0.100000 -979.935486 -4.868352
0.110000 -978.005676 -4.946120
0.120000 -975.656372 -4.801778
0.130000 -973.978271 -4.739869
0.140000 -971.880615 -4.706879
0.150000 -969.866882 -4.946629
0.160000 -967.769287 -4.942389
0.170000 -966.007263 -4.839263
0.180000 -963.657898 -4.812040
0.190000 -961.811951 -4.663457
0.200000 -959.798279 -4.709678
0.210000 -957.784485 -4.658539
0.220000 -955.938599 -4.624955
0.230000 -953.757080 -4.610198
0.240000 -951.995056 -4.587724
0.250000 -949.897400 -4.594509
0.260000 -947.883728 -4.307436
0.270000 -946.037842 -4.310320
0.280000 -943.940186 -4.356200
0.290000 -941.926453 -4.364511
0.300000 -939.661011 -4.595781
0.310000 -937.731201 -4.543455
0.320000 -935.717407 -4.559314
0.330000 -933.871521 -4.562452
0.340000 -931.606079 -4.427014
0.350000 -929.844116 -4.489263
0.360000 -927.662537 -4.452202
0.370000 -925.732788 -4.399452
0.380000 -923.886780 -4.405304
0.390000 -921.873108 -4.408611
0.400000 -919.691589 -4.333557
0.410000 -917.593933 -4.334066
0.420000 -915.831909 -4.386562
0.430000 -913.482544 -4.543200
0.440000 -913.146973 -4.722992
0.450000 -909.622925 -4.428881
0.460000 -907.777039 -4.410053
0.470000 -905.679382 -4.363664
0.480000 -903.581787 -4.374688
0.490000 -901.735840 -4.188112
0.500000 -899.973816 -3.465724
0.510000 -898.127930 -3.826409
0.520000 -895.694702 -3.733291
0.530000 -893.848755 -3.535859
0.540000 -891.751160 -3.213846
0.550000 -889.821289 -3.182298
0.560000 -888.059265 -2.966124
0.570000 -885.961731 -2.916851
0.580000 -883.360596 -3.444437
0.590000 -881.682495 -3.675622
0.600000 -880.004395 -3.014973
0.610000 -877.738953 -2.964597
0.620000 -875.893066 -2.955438
0.630000 -873.543701 -3.789857
0.640000 -871.781738 -2.904723
0.650000 -869.767944 -3.019892
0.660000 -867.838196 -2.876482
0.670000 -865.572754 -2.871055
0.680000 -863.894653 -2.873005
0.690000 -861.796997 -2.856468
0.700000 -859.699341 -2.857570
0.710000 -857.685669 -3.277282
0.720000 -855.755798 -3.240815
0.730000 -853.909912 -2.812538
0.740000 -851.812256 -2.800071
0.750000 -849.714661 -2.830602
0.760000 -847.617004 -2.861980
0.770000 -845.687134 -2.828651
0.780000 -843.673462 -2.989106
0.790000 -841.575806 -3.356577
0.800000 -839.981567 -3.497866
0.810000 -837.212769 -3.823356
0.820000 -835.534668 -3.269310
0.830000 -833.437012 -3.710393
0.840000 -831.842834 -2.778360
0.850000 -829.829041 -2.802276
0.860000 -827.815369 -2.759279
0.870000 -825.717712 -2.751392
0.880000 -823.787903 -2.733328
0.890000 -821.942017 -2.720352
0.900000 -819.844360 -2.750289
0.910000 -817.830627 -2.919310
0.920000 -815.733032 -2.894377
0.930000 -813.803162 -2.898023
0.940000 -811.789490 -2.866390
0.950000 -809.859619 -2.864864
0.960000 -807.510315 -3.323078
0.970000 -805.916077 -2.828821
0.980000 -803.566772 -2.821018
0.990000 -801.888611 -2.812368
1.000000 -799.874939 -2.779124
1.010000 -797.777283 -2.807873
1.020000 -795.847534 -2.797611
1.030000 -793.498108 -2.787180
1.040000 -791.903992 -2.775138
1.050000 -789.974121 -2.762417
1.060000 -787.792542 -2.723151
1.070000 -785.694946 -2.718826
1.080000 -784.016846 -2.685411
1.090000 -782.003113 -2.675913
1.100000 -779.653748 -2.651997
1.110000 -777.807861 -2.652761
1.120000 -775.877991 -2.638598
1.130000 -773.864319 -2.628506
1.140000 -771.682800 -2.617651
1.150000 -769.501221 -2.629269
1.160000 -767.907043 -2.609424
1.170000 -765.809387 -2.601622
1.180000 -763.879578 -2.593480
1.190000 -761.698059 -2.583049
1.200000 -759.600464 -2.560490
1.210000 -757.586731 -2.555995
1.220000 -755.740784 -2.563713
1.230000 -753.894836 -2.534794
1.240000 -752.048950 -2.521224
1.250000 -749.699585 -2.530044
1.260000 -747.685913 -2.603827
1.270000 -745.672180 -2.536320
1.280000 -743.658386 -2.561847
1.290000 -741.728638 -2.517239
1.300000 -739.798828 -2.482468
1.310000 -737.868958 -2.469068
1.320000 -736.023071 -2.464319
1.330000 -733.925415 -2.457025
1.340000 -731.659973 -2.449054
1.350000 -729.981873 -2.444898
1.360000 -727.800293 -2.441421
1.370000 -725.618835 -2.437435
1.380000 -723.688965 -2.433025
1.390000 -721.759216 -2.430905
1.400000 -719.661560 -2.424205
1.410000 -717.899536 -2.414367
1.420000 -715.718018 -2.416233
1.430000 -713.788208 -2.403003
1.440000 -711.522766 -2.391639
1.450000 -709.760742 -2.383328
1.460000 -707.998657 -2.383158
1.470000 -705.984985 -2.372218
1.480000 -703.635681 -2.377137
1.490000 -701.705811 -2.377391
1.500000 -699.776001 -2.370183
1.510000 -697.846252 -2.365434
1.520000 -695.748596 -2.726034
1.530000 -693.734802 -2.722727
1.540000 -691.888916 -2.729681
1.550000 -689.707397 -2.716281
1.560000 -687.777588 -2.697030
1.570000 -685.763794 -2.677355
1.580000 -684.001831 -2.668111
1.590000 -681.652466 -2.662683
1.600000 -679.890503 -2.646909
1.610000 -677.625061 -2.631474
1.620000 -675.611267 -2.621382
1.630000 -673.849304 -3.134382
1.640000 -671.919495 -2.953148
1.650000 -669.905762 -2.917614
1.660000 -667.975952 -2.634273
1.670000 -665.710510 -2.670146
1.680000 -663.864624 -2.665312
1.690000 -661.431335 -2.793032
1.700000 -659.753174 -2.684648
1.710000 -657.655640 -2.447781
1.720000 -655.809631 -2.459400
1.730000 -653.795959 -2.214307
1.740000 -651.782227 -2.323878
1.750000 -649.852417 -2.461605
1.760000 -648.174316 -2.134334
1.770000 -645.741089 -2.281559
1.780000 -643.727356 -2.102955
1.790000 -641.881409 -2.146970
1.800000 -639.615967 -2.266039
1.810000 -637.518311 -2.363737
1.820000 -635.924133 -2.080481
1.830000 -633.742554 -2.538271
1.840000 -631.812805 -2.472121
1.850000 -630.218567 -2.064707
1.860000 -627.869263 -2.240512
1.870000 -625.687683 -2.340161
1.880000 -623.925720 -2.479245
1.890000 -621.911987 -2.518935
1.900000 -619.898254 -2.519359
1.910000 -617.716675 -2.306577
1.920000 -615.786865 -2.513168
1.930000 -613.689270 -2.541833
1.940000 -611.675537 -2.324556
1.950000 -609.745728 -2.314549
1.960000 -607.815857 -2.303355
1.970000 -605.634399 -2.315228
1.980000 -603.704529 -2.314719
1.990000 -601.858643 -2.302506
2.000000 -599.593201 -2.500277
2.010000 -597.663391 -2.252131
2.020000 -595.817444 -2.413774
2.030000 -593.803711 -2.275283
2.040000 -591.622192 -2.237290
2.050000 -589.608459 -2.236442
2.060000 -587.510864 -2.239834
2.070000 -585.832764 -2.233049
2.080000 -583.567322 -2.228130
2.090000 -581.805298 -2.237968
2.100000 -579.791565 -2.244583
2.110000 -577.777832 -2.200483
2.120000 -575.848022 -2.377306
2.130000 -573.666504 -2.203367
2.140000 -571.820557 -2.181995
2.150000 -569.639038 -2.179366
2.160000 -567.960938 -2.190815
2.170000 -565.779419 -2.180808
2.180000 -563.513977 -2.163507
2.190000 -561.835815 -2.375780
2.200000 -559.654297 -2.135267
2.210000 -557.808411 -2.128567
2.220000 -555.542969 -2.308697
2.230000 -553.613159 -2.307595
2.240000 -551.767212 -2.303100
2.250000 -549.417847 -2.100495
2.260000 -548.075439 -2.131026
2.270000 -545.642151 -2.087011
2.280000 -543.880127 -2.080057
2.290000 -541.614685 -2.073527
2.300000 -539.768738 -2.067590
2.310000 -537.755066 -2.068438
2.320000 -535.657410 -2.062162
2.330000 -533.727600 -2.055802
2.340000 -531.546082 -2.048509
2.350000 -530.035767 -2.043674
2.360000 -527.854248 -2.043081
2.370000 -525.756592 -2.047661
2.380000 -523.658936 -2.039265
2.390000 -521.813049 -2.032904
2.400000 -519.715393 -2.150956
2.410000 -517.953430 -1.847176
2.420000 -515.771851 -1.889410
2.430000 -513.842102 -1.841409
2.440000 -511.492706 -1.839289
2.450000 -509.730713 -1.833098
2.460000 -507.633087 -1.832844
2.470000 -505.787170 -1.824787
2.480000 -503.689545 -1.819614
2.490000 -501.843597 -1.815373
2.500000 -499.829895 -1.807317
2.510000 -497.816162 -1.817493
2.520000 -495.802460 -1.808674
2.530000 -493.872620 -1.803670
2.540000 -491.691071 -1.797394
2.550000 -489.845184 -1.784334
2.560000 -487.915344 -1.786624
2.570000 -485.733795 -1.790440
2.580000 -483.804016 -1.777719
2.590000 -481.706360 -1.768560
2.600000 -479.524841 -2.182335
2.610000 -477.595032 -2.161981
2.620000 -475.749084 -2.157316
2.630000 -473.819275 -2.149853
2.640000 -471.721649 -2.136030
2.650000 -469.875763 -2.134334
2.660000 -467.862000 -1.757959
2.670000 -465.512665 -1.756602
2.680000 -463.582825 -1.761521
2.690000 -461.736938 -1.756008
2.700000 -459.723206 -1.751344
2.710000 -457.793396 -1.748715
2.720000 -455.611847 -1.743117
2.730000 -453.849854 -1.735146
2.740000 -451.668304 -1.734976
2.750000 -449.654572 -1.741337
2.760000 -447.808685 -1.721067
2.770000 -445.627136 -1.710212
2.780000 -443.697296 -1.699527
2.790000 -442.019196 -1.702495
2.800000 -439.585968 -1.699611
2.810000 -437.823944 -1.703173
2.820000 -435.726318 -1.711060
2.830000 -433.544769 -1.708092
2.840000 -431.866669 -1.703852
2.850000 -429.852936 -1.702749
2.860000 -427.671417 -1.695032
2.870000 -425.825500 -1.695286
2.880000 -423.560059 -2.050544
2.890000 -421.546326 -1.687653
2.900000 -419.868225 -1.682735
2.910000 -417.518890 -2.099732
2.920000 -415.672974 -1.665688
2.930000 -413.659241 -1.658904
2.940000 -411.813354 -1.656784
2.950000 -409.463989 -1.658225
2.960000 -407.618073 -1.653815
2.970000 -405.856079 -1.647285
2.980000 -403.758423 -1.653815
2.990000 -401.576874 -1.646013
3.000000 -399.814880 -1.641349
3.010000 -397.801147 -1.643723
3.020000 -395.619598 -1.639144
3.030000 -393.857605 -1.638720
3.040000 -392.011719 -1.634055
3.050000 -389.578461 -1.647116
3.060000 -387.732544 -1.625490
3.070000 -385.634888 -1.627779
3.080000 -383.705078 -1.600980
3.090000 -381.859161 -1.595637
3.100000 -379.845459 -1.591312
3.110000 -377.747803 -1.587496
3.120000 -375.650177 -1.584782
3.130000 -373.804260 -1.583595
3.140000 -371.538818 -1.574605
3.150000 -369.525085 -1.561799
3.160000 -367.846985 -1.559086
3.170000 -365.917206 -1.556626
3.180000 -363.735657 -1.562902
3.190000 -361.889709 -1.554676
3.200000 -359.792114 -1.550605
3.210000 -357.694489 -1.556541
3.220000 -355.596832 -1.542887
3.230000 -353.834839 -1.540089
3.240000 -351.569397 -1.535000
3.250000 -349.807404 -1.529233
3.260000 -347.625854 -1.527198
3.270000 -345.528229 -1.526265
3.280000 -343.682281 -1.525671
3.290000 -341.416870 -1.520837
3.300000 -339.570953 -1.515410
3.310000 -337.389404 -1.511678
3.320000 -335.963013 -1.508201
3.330000 -333.613678 -1.503197
3.340000 -331.599945 -1.501247
3.350000 -329.754028 -1.499296
3.360000 -327.656433 -1.494971
3.370000 -325.558777 -1.491240
3.380000 -323.712860 -1.487339
3.390000 -321.783051 -1.486660
3.400000 -320.021057 -1.483437
3.410000 -317.671661 -1.479536
3.420000 -315.741852 -1.478603
3.430000 -313.812042 -1.473854
3.440000 -311.462708 -1.471734
3.450000 -309.868500 -1.466306
3.460000 -307.770874 -1.463169
3.470000 -305.673248 -1.458334
3.480000 -303.491699 -1.455366
3.490000 -301.729706 -1.451465
3.500000 -299.799866 -1.449260
3.510000 -297.702240 -1.449175
3.520000 -295.604614 -1.445444
3.530000 -293.674805 -1.441712
3.540000 -291.744995 -1.438829
3.550000 -289.563446 -1.436030
3.560000 -287.633636 -1.432723
3.570000 -285.619873 -1.430602
3.580000 -283.690094 -1.427719
3.590000 -281.844177 -1.422800
3.600000 -279.662628 -1.423055
3.610000 -277.816711 -1.418051
3.620000 -275.802979 -1.414659
3.630000 -273.705353 -1.413387
3.640000 -271.523834 -1.409825
3.650000 -269.761810 -1.407111
3.660000 -267.915894 -1.406348
3.670000 -265.650452 -1.401344
3.680000 -263.636719 -1.399054
3.690000 -261.790802 -1.394899
3.700000 -259.273651 -1.391591
3.710000 -257.595551 -1.389556
3.720000 -255.665741 -1.385231
3.730000 -253.652008 -1.383195
3.740000 -251.722183 -1.377852
3.750000 -249.540665 -1.376156
3.760000 -247.778641 -1.371661
3.770000 -245.681000 -1.368608
3.780000 -243.415573 -1.366064
3.790000 -241.821365 -1.364877
3.800000 -239.807648 -1.362248
3.810000 -237.626129 -1.359449
3.820000 -235.612381 -1.355378
3.830000 -233.514771 -1.354361
3.840000 -231.668854 -1.349357
3.850000 -229.655121 -1.345541
3.860000 -227.557480 -1.344269
3.870000 -225.543762 -1.340961
3.880000 -223.613953 -1.337993
3.890000 -221.600204 -1.335449
3.900000 -219.586487 -1.332904
3.910000 -217.572769 -1.329258
3.920000 -215.726852 -1.328325
3.930000 -213.713135 -1.323576
3.940000 -211.867218 -1.321201
3.950000 -209.769592 -1.318318
3.960000 -207.588058 -1.316876
3.970000 -205.658234 -1.314586
3.980000 -203.644516 -1.310091
3.990000 -201.714691 -1.307717
4.000000 -199.700958 -1.304155
4.010000 -197.603333 -1.301695
4.020000 -195.757416 -1.298473
4.030000 -193.491974 -1.295504
4.040000 -191.729965 -1.293130
4.050000 -189.716232 -1.291518
4.060000 -187.702515 -1.289568
4.070000 -185.688797 -1.284649
4.080000 -183.675064 -1.283801
4.090000 -181.745239 -1.278967
4.100000 -179.647614 -1.278458
4.110000 -177.633896 -1.277356
4.120000 -175.620163 -1.272691
4.130000 -173.690338 -1.268451
4.140000 -171.676620 -1.267094
4.150000 -169.662903 -1.263702
4.160000 -167.900879 -1.262005
4.170000 -165.719345 -1.259461
4.180000 -163.537827 -1.256154
4.190000 -161.608002 -1.254373
4.200000 -159.845993 -1.249115
4.210000 -157.748367 -1.248606
4.220000 -155.482910 -1.245129
4.230000 -153.888718 -1.243348
4.240000 -151.707184 -1.239871
4.250000 -149.693451 -1.238090
4.260000 -147.847549 -1.234274
4.270000 -145.749908 -1.232069
4.280000 -143.736191 -1.229609
4.290000 -141.554657 -1.227998
4.300000 -139.708740 -1.224521
4.310000 -137.946732 -1.222740
4.320000 -135.597382 -1.219178
4.330000 -133.919281 -1.217058
4.340000 -131.737732 -1.214344
4.350000 -129.640106 -1.212648
4.360000 -127.458580 -1.209255
4.370000 -125.612663 -1.205693
4.380000 -123.766747 -1.202810
4.390000 -121.669113 -1.200351
4.400000 -119.823204 -1.198485
4.410000 -117.725563 -1.195516
4.420000 -115.711845 -1.192209
4.430000 -113.698128 -1.190428
4.440000 -111.600487 -1.187460
4.450000 -109.586761 -1.185764
4.460000 -107.740845 -1.184068
4.470000 -105.643219 -1.180082
4.480000 -103.629494 -1.178385
4.490000 -101.615768 -1.174739
4.500000 -99.602043 -1.172534
4.510000 -97.504417 -1.170753
4.520000 -95.574600 -1.167445
4.530000 -93.644768 -1.163459
4.540000 -91.966675 -1.161848
4.550000 -89.701233 -1.162272
4.560000 -87.603600 -1.159473
4.570000 -85.925491 -1.154724
4.580000 -83.660049 -1.153876
4.590000 -81.730232 -1.149551
4.600000 -79.716515 -1.149890
4.610000 -77.534973 -1.146074
4.620000 -75.605156 -1.142003
4.630000 -73.591431 -1.140985
4.640000 -71.661606 -1.138865
4.650000 -69.731789 -1.136999
4.660000 -67.718063 -1.134540
4.670000 -65.452621 -1.131572
4.680000 -63.690613 -1.129621
4.690000 -61.676888 -1.126144
4.700000 -59.579258 -1.123430
4.710000 -57.649437 -1.121225
4.720000 -55.635715 -1.119614
4.730000 -53.538082 -1.116985
4.740000 -51.776077 -1.115543
4.750000 -49.594540 -1.115798
4.760000 -47.664719 -1.147431
4.770000 -45.567089 -1.146667
4.780000 -43.469460 -1.141240
4.790000 -41.539642 -1.135727
4.800000 -39.525917 -1.134540
4.810000 -37.680000 -1.132081
4.820000 -35.834084 -1.127671
4.830000 -33.904266 -1.125635
4.840000 -31.806633 -1.123345
4.850000 -29.709005 -1.122582
4.860000 -27.611376 -1.120547
4.870000 -25.513744 -1.115628
4.880000 -23.583923 -1.113678
4.890000 -21.486296 -1.112914
4.900000 -19.808189 -1.109352
4.910000 -17.458843 -1.107487
4.920000 -15.529024 -1.105536
4.930000 -13.431395 -1.103077
4.940000 -11.501575 -1.099091
4.950000 -9.403944 -1.095020
4.960000 -7.474124 -1.092645
4.970000 -5.879925 -1.090016
4.980000 -3.698390 -1.088914
4.990000 -1.684664 -1.086709
5.000000 0.412966 -1.084080
5.010000 2.510596 -1.081620
5.020000 4.524321 -1.077804
5.030000 6.538046 -1.077550
5.040000 8.635676 -1.074581
5.050000 10.145969 -1.070765
5.060000 12.327506 -1.068984
5.070000 14.341230 -1.064404
5.080000 16.438860 -1.065168
5.090000 18.536491 -1.062454
5.100000 20.466312 -1.057959
5.110000 22.563942 -1.056857
5.120000 24.493761 -1.054228
5.130000 26.423580 -1.052871
5.140000 28.353401 -1.052023
5.150000 30.451031 -1.048376
5.160000 32.464756 -1.046510
5.170000 34.562386 -1.044644
5.180000 36.408302 -1.042185
5.190000 38.422028 -1.042354
5.200000 40.435749 -1.040658
5.210000 42.197762 -1.037181
5.220000 44.295391 -1.035061
5.230000 46.393021 -1.032178
5.240000 48.155029 -1.032008
5.250000 50.420471 -1.028361
5.260000 52.685913 -1.025139
5.270000 54.447922 -1.024291
5.280000 56.293835 -1.022425
5.290000 58.307560 -1.022001
5.300000 60.321289 -1.017082
5.310000 62.502819 -1.015640
5.320000 64.516548 -1.013944
5.330000 66.698082 -1.009873
5.340000 68.376183 -1.006651
5.350000 70.389908 -1.005463
5.360000 72.571442 -1.003174
5.370000 74.669075 -1.001562
5.380000 76.514992 -0.999696
5.390000 78.528709 -0.997831
5.400000 80.626350 -0.995287
5.410000 82.640068 -0.993675
5.420000 84.485985 -0.992149
5.430000 86.499710 -0.990028
5.440000 88.513435 -0.987060
5.450000 90.443260 -0.984686
5.460000 92.205261 -0.982141
5.470000 94.302895 -0.980869
5.480000 96.316620 -0.977731
5.490000 98.330345 -0.975102
5.500000 100.427979 -0.975017
5.510000 102.525604 -0.972558
5.520000 104.455421 -0.970692
5.530000 106.636963 -0.967300
5.540000 108.231163 -0.966961
5.550000 110.412689 -0.965180
5.560000 112.510323 -0.963484
5.570000 114.524055 -0.961024
5.580000 116.705582 -0.958226
5.590000 118.383690 -0.956869
5.600000 120.397415 -0.954070
5.610000 122.327240 -0.952374
5.620000 124.508766 -0.950169
5.630000 126.354691 -0.946861
5.640000 128.620132 -0.946268
5.650000 130.466049 -0.942706
5.660000 132.395859 -0.941858
5.670000 134.241776 -0.939568
5.680000 136.507217 -0.937363
5.690000 138.520935 -0.936006
5.700000 140.534668 -0.932953
5.710000 142.464493 -0.931172
5.720000 144.646027 -0.930409
5.730000 145.988510 -0.926932
5.740000 148.421753 -0.926847
5.750000 150.603287 -0.923200
5.760000 152.617020 -0.922098
5.770000 154.546844 -0.919469
5.780000 156.392761 -0.917857
5.790000 158.406479 -0.914974
5.800000 160.336304 -0.912345
5.810000 162.517838 -0.911412
5.820000 164.363739 -0.910055
5.830000 166.461380 -0.906663
5.840000 168.475098 -0.903949
5.850000 170.404922 -0.901235
5.860000 172.502563 -0.899624
5.870000 174.516281 -0.899115
5.880000 176.613922 -0.899285
5.890000 178.459824 -0.894705
5.900000 180.725266 -0.892585
5.910000 182.235550 -0.890889
5.920000 184.500992 -0.888684
5.930000 186.598633 -0.886055
5.940000 188.612350 -0.885461
5.950000 190.542175 -0.883426
5.960000 192.304169 -0.880118
5.970000 194.317917 -0.879694
5.980000 196.499435 -0.876641
5.990000 198.429276 -0.874182
6.000000 200.442993 -0.874351
6.010000 202.624512 -0.869517
6.020000 204.470428 -0.869432
6.030000 206.484146 -0.866803
6.040000 208.413986 -0.864938
6.050000 210.679428 -0.864005
6.060000 212.525330 -0.863326
6.070000 214.371246 -0.860188
6.080000 216.384964 -0.860188
6.090000 218.398712 -0.856796
6.100000 220.412430 -0.854676
6.110000 222.426147 -0.852217
6.120000 224.355972 -0.850520
6.130000 226.537506 -0.849672
6.140000 228.299515 -0.848061
6.150000 230.397141 -0.845347
6.160000 232.578690 -0.843397
6.170000 234.676300 -0.841785
6.180000 236.270523 -0.840768
6.190000 238.368134 -0.839750
6.200000 240.381866 -0.836866
6.210000 242.311676 -0.835764
6.220000 244.577118 -0.833389
6.230000 246.506943 -0.831693
6.240000 248.520676 -0.830167
6.250000 250.198776 -0.827538
6.260000 252.380310 -0.825587
6.270000 254.561844 -0.823212
6.280000 256.407776 -0.821347
6.290000 258.673218 -0.819905
6.300000 260.351318 -0.816173
6.310000 262.365021 -0.814986
6.320000 264.462677 -0.814986
6.330000 266.224670 -0.813205
6.340000 268.574036 -0.810661
6.350000 270.503845 -0.807269
6.360000 272.433655 -0.805827
6.370000 274.615173 -0.804809
6.380000 276.712830 -0.804724
6.390000 278.558746 -0.801841
6.400000 280.488556 -0.799806
6.410000 282.334473 -0.798364
6.420000 284.683807 -0.796837
6.430000 286.529724 -0.794802
6.440000 288.543457 -0.792173
6.450000 290.305450 -0.791749
6.460000 292.487000 -0.787848
6.470000 294.416809 -0.786321
6.480000 296.430542 -0.784795
6.490000 298.695984 -0.783183
6.500000 300.290192 -0.781233
6.510000 302.387817 -0.779452
6.520000 304.401550 -0.778858
6.530000 306.499176 -0.775975
6.540000 308.680725 -0.774618
6.550000 310.526611 -0.773346
6.560000 312.288635 -0.771056
6.570000 314.470184 -0.769275
6.580000 316.735626 -0.767409
6.590000 318.413727 -0.766561
6.600000 320.343536 -0.765119
6.610000 322.441162 -0.764695
6.620000 324.538788 -0.762575
6.630000 326.384705 -0.760540
6.640000 328.482330 -0.759946
6.650000 330.663879 -0.759353
6.660000 332.425873 -0.756215
6.670000 334.439606 -0.753586
6.680000 336.621155 -0.752398
6.690000 338.550964 -0.750448
6.700000 340.564697 -0.748667
6.710000 342.662292 -0.746886
6.720000 344.424347 -0.744681
6.730000 346.438049 -0.742900
6.740000 348.535675 -0.740356
6.750000 350.549408 -0.739084
6.760000 352.647064 -0.739084
6.770000 354.576843 -0.735691
6.780000 356.674500 -0.734080
6.790000 358.436493 -0.731451
6.800000 360.534119 -0.729924
6.810000 362.547882 -0.729331
6.820000 364.477661 -0.727889
6.830000 366.407471 -0.725854
6.840000 368.589020 -0.724666
6.850000 370.518860 -0.722292
6.860000 372.532593 -0.734334
6.870000 374.462402 -0.732045
6.880000 376.560028 -0.729585
6.890000 378.573730 -0.728737
6.900000 380.419678 -0.728059
6.910000 382.517303 -0.726447
6.920000 384.531006 -0.724158
6.930000 386.544739 -0.726278
6.940000 388.558441 -0.723564
6.950000 390.739990 -0.720596
6.960000 392.585938 -0.717712
6.970000 394.599640 -0.714659
6.980000 396.361664 -0.715507
6.990000 398.375366 -0.701344
7.000000 400.305206 -0.699479
7.010000 402.570648 -0.696680
7.020000 404.668274 -0.698631
7.030000 406.262482 -0.695832
7.040000 408.444031 -0.695153
7.050000 410.457733 -0.692864
7.060000 412.555359 -0.691337
7.070000 414.485168 -0.689471
7.080000 416.582794 -0.688199
7.090000 418.344788 -0.685231
7.100000 420.442444 -0.685231
7.110000 422.372284 -0.683365
7.120000 424.637726 -0.681584
7.130000 426.567505 -0.679464
7.140000 428.581268 -0.678701
7.150000 430.678894 -0.677259
7.160000 432.608704 -0.674206
7.170000 434.454590 -0.672764
7.180000 436.720032 -0.671831
7.190000 438.649872 -0.669796
7.200000 440.579712 -0.670135
7.210000 442.677307 -0.666913
7.220000 444.607147 -0.665895
7.230000 446.788696 -0.663775
7.240000 448.550690 -0.662079
7.250000 450.648315 -0.659534
7.260000 452.745941 -0.658347
7.270000 454.591858 -0.655972
7.280000 456.437775 -0.653937
7.290000 458.535400 -0.653598
7.300000 460.465240 -0.651986
7.310000 462.562866 -0.650460
7.320000 464.492676 -0.648933
7.330000 466.506378 -0.647237
7.340000 468.687927 -0.644015
7.350000 470.533875 -0.642234
7.360000 472.379761 -0.642149
7.370000 474.645203 -0.640113
7.380000 476.407196 -0.637654
7.390000 478.588745 -0.636297
7.400000 480.518585 -0.634177
7.410000 482.364471 -0.632226
7.420000 484.462128 -0.630869
7.430000 486.475861 -0.629173
7.440000 488.573456 -0.627477
7.450000 490.671112 -0.625272
7.460000 492.768738 -0.625272
7.470000 494.530731 -0.624509
7.480000 496.628387 -0.622134
7.490000 498.642120 -0.620523
7.500000 500.571930 -0.618742
7.510000 502.501709 -0.616113
7.520000 504.767151 -0.614841
7.530000 506.780914 -0.613654
7.540000 508.626831 -0.612466
7.550000 510.472748 -0.610940
7.560000 512.318665 -0.609752
7.570000 514.500183 -0.608226
7.580000 516.346069 -0.607039
7.590000 518.359802 -0.605427
7.600000 520.373596 -0.602629
7.610000 522.471191 -0.601441
7.620000 524.568787 -0.600254
7.630000 526.750366 -0.598812
7.640000 528.764038 -0.597286
7.650000 530.609985 -0.595844
7.660000 532.623718 -0.593639
7.670000 534.553528 -0.593215
7.680000 536.567261 -0.591688
7.690000 538.664856 -0.590332
7.700000 540.510803 -0.588805
7.710000 542.440613 -0.586685
7.720000 544.538269 -0.585667
7.730000 546.468079 -0.584904
7.740000 548.565674 -0.583971
7.750000 550.327698 -0.581427
7.760000 552.677063 -0.581088
7.770000 554.522949 -0.578374
7.780000 556.620605 -0.577017
7.790000 558.550415 -0.575066
7.800000 560.648071 -0.574727
7.810000 562.577881 -0.572776
7.820000 564.507690 -0.570656
7.830000 566.353638 -0.568790
7.840000 568.283447 -0.569384
7.850000 570.464966 -0.566077
7.860000 572.478699 -0.564720
7.870000 574.492432 -0.563108
7.880000 576.673950 -0.562006
7.890000 578.435974 -0.560055
7.900000 580.617493 -0.558359
7.910000 582.463440 -0.557172
7.920000 584.728882 -0.555730
7.930000 586.574768 -0.553186
7.940000 588.672424 -0.552253
7.950000 590.434387 -0.550811
7.960000 592.364258 -0.548776
7.970000 594.461853 -0.546401
7.980000 596.727295 -0.546147
7.990000 598.741028 -0.544536
8.000000 600.502991 -0.542755
8.010000 602.432861 -0.543263
8.020000 604.446533 -0.540295
8.030000 606.628113 -0.540465
8.040000 608.641846 -0.538514
8.050000 610.487732 -0.536818
8.060000 612.585388 -0.535546
8.070000 614.682983 -0.533171
8.080000 616.361084 -0.531136
8.090000 618.542664 -0.529864
8.100000 620.388550 -0.529610
8.110000 622.570068 -0.528592
8.120000 624.583801 -0.526387
8.130000 626.597595 -0.526013
8.140000 628.527344 -0.524972
8.150000 630.625000 -0.523219
8.160000 632.722656 -0.521918
8.170000 634.484680 -0.519963
8.180000 636.414429 -0.519291
8.190000 638.679871 -0.517773
8.200000 640.525757 -0.516850
8.210000 642.455627 -0.514760
8.220000 644.553223 -0.513535
8.230000 646.399170 -0.512100
8.240000 648.580750 -0.511270
8.250000 650.510559 -0.509365
8.260000 652.356445 -0.508333
8.270000 654.537964 -0.507527
8.280000 656.803406 -0.505253
8.290000 658.733215 -0.504330
8.300000 660.579163 -0.502526
8.310000 662.592834 -0.501083
8.320000 664.606628 -0.499715
8.330000 666.620300 -0.498524
8.340000 668.466248 -0.497433
8.350000 670.563843 -0.496761
8.360000 672.409851 -0.494529
8.370000 674.423523 -0.492885
8.380000 676.521179 -0.492138
8.390000 678.702698 -0.495855
8.400000 680.548584 -0.494278
8.410000 682.562378 -0.493279
8.420000 684.995605 -0.492364
8.430000 686.589783 -0.489847
8.440000 688.435669 -0.489058
8.450000 690.533325 -0.487422
8.460000 692.463135 -0.485920
8.470000 694.476868 -0.484552
8.480000 696.490601 -0.483747
8.490000 698.336487 -0.481993
8.500000 700.518005 -0.480189
8.510000 702.363892 -0.479224
8.520000 704.629333 -0.477932
8.530000 706.643127 -0.477109
8.540000 708.740784 -0.475498
8.550000 710.670532 -0.474760
8.560000 712.768188 -0.473249
8.570000 714.614136 -0.471731
8.580000 716.627869 -0.469322
8.590000 718.725464 -0.467460
8.600000 720.823120 -0.466318
8.610000 722.417297 -0.464917
8.620000 724.682739 -0.463969
8.630000 726.528625 -0.463516
8.640000 728.542419 -0.461443
8.650000 730.472168 -0.460713
8.660000 732.569824 -0.458523
8.670000 734.667419 -0.457449
8.680000 736.597290 -0.455796
8.690000 738.443176 -0.454688
8.700000 740.624756 -0.453447
8.710000 742.470642 -0.451945
8.720000 744.568298 -0.451013
8.730000 746.414185 -0.449645
8.740000 748.595703 -0.448353
8.750000 750.609497 -0.447036
8.760000 752.707031 -0.446490
8.770000 754.804688 -0.444829
8.780000 756.734497 -0.443377
8.790000 758.580444 -0.442093
8.800000 760.510254 -0.440885
8.810000 762.859619 -0.439828
8.820000 764.621582 -0.438158
8.830000 766.551453 -0.437436
8.840000 768.481262 -0.435917
8.850000 770.662781 -0.435145
8.860000 772.676575 -0.433669
8.870000 774.522461 -0.433845
8.880000 776.703979 -0.432024
8.890000 778.382080 -0.430631
8.900000 780.731445 -0.428542
8.910000 782.577332 -0.427124
8.920000 784.423218 -0.425924
8.930000 786.604797 -0.424363
8.940000 788.534607 -0.423171
8.950000 790.380554 -0.421418
8.960000 792.645996 -0.420973
8.970000 794.407959 -0.420042
8.980000 796.505615 -0.418514
8.990000 798.435425 -0.417541
9.000000 800.616943 -0.416870
9.010000 802.798523 -0.415947
9.020000 804.644409 -0.416182
9.030000 806.574219 -0.413958
9.040000 808.587952 -0.415066
9.050000 810.685608 -0.416735
9.060000 812.699280 -0.413194
9.070000 814.964722 -0.410753
9.080000 816.642822 -0.411155
9.090000 818.740479 -0.408739
9.100000 820.670288 -0.408059
9.110000 822.516174 -0.408218
9.120000 824.446045 -0.407153
9.130000 826.627563 -0.403654
9.140000 828.557373 -0.404342
9.150000 830.571106 -0.402345
9.160000 832.584839 -0.401296
9.170000 834.514709 -0.399777
9.180000 836.528381 -0.398879
9.190000 838.458252 -0.398309
9.200000 840.639709 -0.398300
9.210000 842.569580 -0.396538
9.220000 844.583252 -0.397914
9.230000 846.596985 -0.393895
9.240000 848.526794 -0.392938
9.250000 850.624451 -0.392552
9.260000 852.638184 -0.424145
9.270000 854.567993 -0.424052
9.280000 856.581726 -0.420788
9.290000 858.511536 -0.420042
9.300000 860.860901 -0.421015
9.310000 862.622864 -0.420092
9.320000 864.636658 -0.418338
9.330000 866.482544 -0.417247
9.340000 868.412354 -0.416299
9.350000 870.258301 -0.413538
9.360000 872.439819 -0.413211
9.370000 874.537415 -0.412473
9.380000 876.299438 -0.410610
9.390000 878.564880 -0.410249
9.400000 880.578613 -0.407363
9.410000 882.844055 -0.406339
9.420000 884.438293 -0.405542
9.430000 886.535828 -0.404040
9.440000 888.633484 -0.402722
9.450000 890.647278 -0.402638
9.460000 892.744812 -0.401296
9.470000 894.758606 -0.398409
9.480000 896.604492 -0.397897
9.490000 898.450378 -0.396622
9.500000 900.715820 -0.396286
9.510000 902.310059 -0.394558
9.520000 904.659363 -0.392762
9.530000 906.673157 -0.390757
9.540000 908.519043 -0.390027
9.550000 910.784485 -0.387694
9.560000 912.630432 -0.387434
9.570000 914.560242 -0.385839
9.580000 916.406128 -0.384572
9.590000 918.755493 -0.382970
9.600000 920.937012 -0.382651
9.610000 922.531250 -0.381283
9.620000 924.544983 -0.381224
9.630000 926.642578 -0.378833
9.640000 928.656311 -0.376651
9.650000 930.502197 -0.376148
9.660000 932.767639 -0.374620
9.670000 934.529663 -0.374931
9.680000 936.375549 -0.373823
9.690000 938.724976 -0.372539
9.700000 940.654724 -0.370668
9.710000 942.584534 -0.369754
9.720000 944.598267 -0.367992
9.730000 946.528076 -0.366305
9.740000 948.877441 -0.364803
9.750000 950.471619 -0.363611
9.760000 952.485413 -0.362269
9.770000 954.666931 -0.361220
9.780000 956.764526 -0.359802
9.790000 958.610474 -0.358510
9.800000 960.624146 -0.356764

View File

@@ -0,0 +1,199 @@
Time(s) E(mV) I(mA)
0.100000 1.763577 -0.029101
0.200000 2.762724 -0.028610
0.300000 3.770268 -0.028559
0.400000 4.786208 -0.028826
0.500000 5.768563 -0.028349
0.600000 6.792899 -0.028234
0.700000 7.775254 -0.028022
0.800000 8.782798 -0.028118
0.900000 9.765153 -0.028299
1.000000 10.789489 -0.028453
1.100000 11.780240 -0.028453
1.200000 12.821369 -0.028657
1.300000 13.770139 -0.028915
1.400000 14.777682 -0.028546
1.500000 15.776831 -0.029188
1.600000 16.767582 -0.028683
1.700000 17.783520 -0.028601
1.800000 18.782669 -0.028970
1.900000 19.807005 -0.028870
2.000000 20.797756 -0.028791
2.100000 21.805300 -0.028462
2.200000 22.737278 -0.028364
2.300000 23.778406 -0.028617
2.400000 24.752365 -0.028738
2.500000 25.793493 -0.029199
2.600000 26.767452 -0.028708
2.700000 27.783392 -0.028065
2.800000 28.799332 -0.027991
2.900000 29.806875 -0.028424
3.000000 30.780836 -0.028417
3.100000 31.796772 -0.028475
3.200000 32.787525 -0.028331
3.300000 33.778278 -0.028108
3.400000 34.769028 -0.028230
3.500000 35.784969 -0.027984
3.600000 36.784115 -0.027942
3.700000 37.766468 -0.028032
3.800000 38.790806 -0.028286
3.900000 39.789955 -0.028354
4.000000 40.763912 -0.028207
4.100000 41.754665 -0.028099
4.200000 42.770603 -0.028197
4.300000 43.786545 -0.028176
4.400000 44.777294 -0.028192
4.500000 45.784836 -0.028307
4.600000 46.775589 -0.028396
4.700000 47.774738 -0.028483
4.800000 48.773884 -0.028376
4.900000 49.781429 -0.028730
5.000000 50.780575 -0.029071
5.100000 51.788116 -0.029210
5.200000 52.770473 -0.028525
5.300000 53.752831 -0.028479
5.400000 54.768772 -0.029232
5.500000 55.793106 -0.029103
5.600000 56.800652 -0.029043
5.700000 57.766212 -0.029321
5.800000 58.765362 -0.029204
5.900000 59.789696 -0.029369
6.000000 60.797237 -0.029143
6.100000 61.787991 -0.028959
6.200000 62.803932 -0.028818
6.300000 63.769493 -0.029102
6.400000 64.768639 -0.029005
6.500000 65.759392 -0.028507
6.600000 66.783730 -0.029151
6.700000 67.774475 -0.028881
6.800000 68.790421 -0.028720
6.900000 69.789566 -0.028786
7.000000 70.797112 -0.028745
7.100000 71.813049 -0.028627
7.200000 72.795403 -0.028186
7.300000 73.802956 -0.028823
7.400000 74.793701 -0.028599
7.500000 75.776054 -0.028958
7.600000 76.800392 -0.029110
7.700000 77.791145 -0.029458
7.800000 78.781891 -0.029195
7.900000 79.797829 -0.029496
8.000000 80.796974 -0.029733
8.100000 81.796127 -0.029937
8.200000 82.795273 -0.029791
8.300000 83.777634 -0.029210
8.400000 84.801971 -0.029492
8.500000 85.792717 -0.029031
8.600000 86.775070 -0.029057
8.700000 87.816200 -0.029236
8.800000 88.790161 -0.028967
8.900000 89.772514 -0.029038
9.000000 90.796852 -0.028881
9.100000 91.795998 -0.029188
9.200000 92.803543 -0.029207
9.300000 93.760704 -0.029310
9.400000 94.810234 -0.029037
9.500000 95.784195 -0.029098
9.600000 96.800133 -0.029167
9.700000 97.807678 -0.029221
9.800000 98.790031 -0.029132
9.900000 99.797577 -0.028941
10.000000 100.796722 -0.029081
10.100000 101.804268 -0.029024
10.200000 102.803413 -0.028922
10.300000 103.802567 -0.028957
10.400000 104.801712 -0.028903
10.500000 105.800858 -0.029129
10.600000 106.783211 -0.029139
10.700000 107.807549 -0.029148
10.800000 108.815094 -0.029216
10.900000 109.805840 -0.028921
11.000000 110.813385 -0.028742
11.100000 111.804138 -0.028889
11.200000 112.769699 -0.028884
11.300000 113.802429 -0.028933
11.400000 114.809982 -0.028740
11.500000 115.809128 -0.028485
11.600000 116.816666 -0.029093
11.700000 117.807419 -0.028899
11.800000 118.814964 -0.029117
11.900000 119.797318 -0.029162
12.000000 120.788063 -0.029299
12.100000 121.787216 -0.029617
12.200000 122.794762 -0.029564
12.300000 123.785507 -0.029263
12.400000 124.809845 -0.028942
12.500000 125.800598 -0.029249
12.600000 126.799744 -0.029054
12.700000 127.815689 -0.029312
12.800000 128.823242 -0.029264
12.900000 129.813980 -0.029597
13.000000 130.813126 -0.029762
13.100000 131.803879 -0.029987
13.200000 132.803024 -0.029859
13.300000 133.793777 -0.029861
13.400000 134.792923 -0.029838
13.500000 135.808868 -0.029612
13.600000 136.791214 -0.029442
13.700000 137.790359 -0.029729
13.800000 138.806320 -0.029585
13.900000 139.805466 -0.029730
14.000000 140.829788 -0.029783
14.100000 141.812134 -0.029521
14.200000 142.802902 -0.029773
14.300000 143.802048 -0.029522
14.400000 144.801193 -0.029461
14.500000 145.775146 -0.029776
14.600000 146.816284 -0.029446
14.700000 147.807022 -0.029666
14.800000 148.822968 -0.029733
14.900000 149.805328 -0.029659
15.000000 150.796066 -0.029416
15.100000 151.812012 -0.029498
15.200000 152.819565 -0.029405
15.300000 153.801910 -0.029533
15.400000 154.809464 -0.029788
15.500000 155.817001 -0.029578
15.600000 156.790955 -0.029868
15.700000 157.815308 -0.029453
15.800000 158.814453 -0.029587
15.900000 159.821991 -0.029697
16.000000 160.795944 -0.029583
16.100000 161.795090 -0.029541
16.200001 162.794235 -0.029603
16.299999 163.826965 -0.029526
16.400000 164.800934 -0.029500
16.500000 165.833664 -0.029578
16.600000 166.824417 -0.029656
16.700001 167.798370 -0.029669
16.799999 168.814316 -0.029662
16.900000 169.805069 -0.029525
17.000000 170.812607 -0.029632
17.100000 171.803375 -0.029763
17.200001 172.827698 -0.029450
17.299999 173.818451 -0.029243
17.400000 174.809189 -0.029499
17.500000 175.799957 -0.029474
17.600000 176.799103 -0.029973
17.700001 177.823441 -0.029679
17.799999 178.805786 -0.029621
17.900000 179.813339 -0.029742
18.000000 180.829285 -0.029791
18.100000 181.786438 -0.029615
18.200001 182.810776 -0.029776
18.299999 183.826721 -0.029699
18.400000 184.809067 -0.029858
18.500000 185.799820 -0.029694
18.600000 186.782181 -0.029660
18.700001 187.814911 -0.029505
18.799999 188.822464 -0.029578
18.900000 189.813202 -0.029569
19.000000 190.812363 -0.029655
19.100000 191.811508 -0.029725
19.200001 192.810654 -0.029956
19.299999 193.809799 -0.029307
19.400000 194.808945 -0.029470
19.500000 195.799698 -0.029415
19.600000 196.807236 -0.029424
19.700001 197.856766 -0.029606
19.799999 198.813934 -0.029029

View File

@@ -0,0 +1,89 @@
Time(s) E(mV) I(mA)
0.100000 1100.313599 0.099854
0.200000 1100.313599 0.099846
0.300000 1100.313599 0.099829
0.400000 1100.313599 0.099829
0.500000 1100.313599 0.099821
0.600000 1100.313599 0.099829
0.700000 1100.313599 0.099846
0.800000 1100.313599 0.099812
0.900000 1100.313599 0.099812
1.000000 1100.313599 0.099829
1.100000 1100.313599 0.099812
1.200000 1100.313599 0.099804
1.300000 1100.313599 0.099796
1.400000 1100.313599 0.099804
1.500000 1100.313599 0.099804
1.600000 1100.313599 0.099787
1.700000 1100.313599 0.099796
1.800000 1100.313599 0.099796
1.900000 1100.313599 0.099787
2.000000 1100.313599 0.099821
2.100000 1100.313599 0.099821
2.200000 1100.313599 0.099812
2.300000 1100.313599 0.099829
2.400000 1100.313599 0.099829
2.500000 1100.313599 0.099838
2.600000 1100.313599 0.099854
2.700000 1100.313599 0.099863
2.800000 1100.313599 0.099854
2.900000 1100.313599 0.099846
3.000000 1100.313599 0.099863
3.100000 1100.313599 0.099871
3.200000 1100.313599 0.099879
3.300000 1100.313599 0.099888
3.400000 1100.313599 0.099896
3.500000 1100.313599 0.099913
3.600000 1100.313599 0.099930
3.700000 1100.313599 0.099938
3.800000 1100.313599 0.099930
3.900000 1100.313599 0.099947
4.000000 1100.313599 0.099963
4.100000 1100.313599 0.099947
4.200000 1100.313599 0.099980
4.300000 1100.313599 0.099997
4.400000 1100.313599 0.099972
4.500000 1100.313599 0.099947
4.600000 1100.313599 0.099947
4.700000 1100.313599 0.099955
4.800000 1100.313599 0.099955
4.900000 1100.313599 0.099989
5.000000 1100.313599 0.099997
5.100000 1100.313599 0.099980
5.200000 1100.313599 0.099989
5.300000 1100.313599 0.099963
5.400000 1100.313599 0.099980
5.500000 1100.313599 0.099989
5.600000 1100.313599 0.100005
5.700000 1100.313599 0.099963
5.800000 1100.313599 0.099980
5.900000 1100.313599 0.099980
6.000000 1100.313599 0.099980
6.100000 1100.313599 0.099972
6.200000 1100.313599 0.099997
6.300000 1100.313599 0.099972
6.400000 1100.313599 0.099955
6.500000 1100.313599 0.099972
6.600000 1100.313599 0.099963
6.700000 1100.313599 0.099980
6.800000 1100.313599 0.099963
6.900000 1100.313599 0.099955
7.000000 1100.313599 0.099989
7.100000 1100.313599 0.099989
7.200000 1100.313599 0.099980
7.300000 1100.313599 0.099980
7.400000 1100.313599 0.099980
7.500000 1100.313599 0.099963
7.600000 1100.313599 0.099980
7.700000 1100.313599 0.099955
7.800000 1100.313599 0.099980
7.900000 1100.313599 0.099963
8.000000 1100.313599 0.099989
8.100000 1100.313599 0.099980
8.200000 1100.313599 0.099989
8.300000 1100.313599 0.099989
8.400000 1100.313599 0.099972
8.500000 1100.313599 0.100005
8.600000 1100.313599 0.099980
8.700000 1100.313599 0.100005
8.800000 1100.313599 0.099997

View File

@@ -0,0 +1,49 @@
Time(s) Zre(Ohm) Zim(Ohm) Z(Ohm) Freq(Hz) Phase(deg) EDC(mV)
0.128000 6755.462891 3996.161133 7848.922363 10000.000000 -30.606230 0.000000
0.272000 6824.638672 3994.455811 7907.677734 8888.900391 -30.340406 0.000000
0.436571 7059.030762 4099.418457 8163.035156 7777.799805 -30.145187 0.000000
0.628570 7516.110840 4371.320312 8694.846680 6666.700195 -30.181999 0.000000
Time(s) Zre(Ohm) Zim(Ohm) Z(Ohm) Freq(Hz) Phase(deg) EDC(mV)
0.128000 4004.078857 1725.499268 4360.045410 10000.000000 -23.312920 0.000000
0.272000 3751.894043 1407.421021 4007.186523 8888.900391 -20.562214 0.000000
0.436571 3795.918457 1347.885742 4028.125244 7777.799805 -19.549349 0.000000
0.628570 3988.254883 1406.353516 4228.948730 6666.700195 -19.423862 0.000000
0.858968 4340.244629 1560.648071 4612.303711 5555.600098 -19.777370 0.000000
1.146964 4953.287598 1795.551514 5268.687012 4444.500000 -19.925425 0.000000
1.530957 5583.770020 2229.389648 6012.375977 3333.399902 -21.764971 0.000000
2.106936 6545.107422 2367.948486 6960.288086 2222.300049 -19.889572 0.000000
3.258844 7567.829590 1800.241089 7779.004395 1111.199951 -13.380868 0.000000
23.258844 7841.500488 363.667908 7849.928711 0.100000 -2.655323 0.000000
Time(s) Zre(Ohm) Zim(Ohm) Z(Ohm) Freq(Hz) Phase(deg) EDC(mV)
0.128000 4585.909668 1983.974854 4996.671387 10000.000000 -23.394470 0.000000
0.272000 4468.743652 1882.592163 4849.105469 8888.900391 -22.844717 0.000000
0.436571 4585.427246 1862.162964 4949.120605 7777.799805 -22.102295 0.000000
0.628570 4762.757812 1835.767822 5104.302734 6666.700195 -21.078768 0.000000
0.858968 5040.085449 1868.267578 5375.210449 5555.600098 -20.338821 0.000000
1.146964 5369.222168 2009.491211 5732.939941 4444.500000 -20.518923 0.000000
1.530957 5790.665039 2128.829590 6169.580078 3333.399902 -20.185007 0.000000
2.106936 6104.018066 1879.055054 6386.695801 2222.300049 -17.110409 0.000000
3.258844 6228.028809 1268.160278 6355.830078 1111.199951 -11.509306 0.000000
23.258844 6003.355957 413.043579 6017.548340 0.100000 -3.935868 0.000000
Time(s) Zre(Ohm) Zim(Ohm) Z(Ohm) Freq(Hz) Phase(deg) EDC(mV)
0.128000 3572.804688 1110.373413 3741.371826 10000.000000 -17.264450 0.000000
0.272000 3733.689209 1029.676392 3873.069580 8888.900391 -15.417786 0.000000
0.436571 3814.144043 1035.226807 3952.137207 7777.799805 -15.185266 0.000000
0.628570 3763.235596 993.421204 3892.149414 6666.700195 -14.787639 0.000000
0.858968 3746.752197 922.539612 3858.656738 5555.600098 -13.832431 0.000000
1.146964 3835.638184 876.370972 3934.481689 4444.500000 -12.870085 0.000000
1.530957 3879.458496 808.279602 3962.765869 3333.399902 -11.769126 0.000000
2.106936 4037.450439 756.480225 4107.708496 2222.300049 -10.612228 0.000000
3.258844 4497.190430 741.943848 4557.982422 1111.199951 -9.368237 0.000000
23.258844 5525.440430 743.580078 5575.249023 0.100000 -7.664470 0.000000
Time(s) Zre(Ohm) Zim(Ohm) Z(Ohm) Freq(Hz) Phase(deg) EDC(mV)
0.128000 4508.749023 1480.736694 4745.671387 10000.000000 -18.180910 0.000000
0.272000 4432.497070 1333.723267 4628.806152 8888.900391 -16.746363 0.000000
0.436571 4782.034668 1541.624512 5024.386719 7777.799805 -17.868198 0.000000
0.628570 5205.424805 1835.522095 5519.563965 6666.700195 -19.423525 0.000000
0.858968 5297.061035 1830.112549 5604.298828 5555.600098 -19.059818 0.000000
1.146964 5442.899414 1763.836304 5721.562012 4444.500000 -17.955534 0.000000
1.530957 5554.852051 1871.875732 5861.766113 3333.399902 -18.622803 0.000000
2.106936 5667.162598 1750.656982 5931.402344 2222.300049 -17.166569 0.000000
3.258844 5834.244629 1325.616577 5982.948242 1111.199951 -12.801015 0.000000
23.258844 5939.145508 584.428345 5967.831055 0.100000 -5.619970 0.000000

View File

@@ -0,0 +1,55 @@
Time(s) Zre(Ω) Zim(Ω) Z(Ω) Freq(Hz) Phase(°) EDC(V)
0.128000 8836.014648 4088.676270 9736.140625 10000.000000 -24.831327 0.000000
0.289142 8947.045898 3906.468262 9762.690430 7943.282227 -23.587093 0.000000
0.492009 9445.424805 4166.807129 10323.678711 6309.573242 -23.804461 0.000000
0.747402 10144.289062 4494.853516 11095.508789 5011.872070 -23.897749 0.000000
1.068924 10604.609375 4514.041992 11525.376953 3981.071533 -23.057899 0.000000
1.473696 11142.434570 4558.653809 12038.902344 3162.277588 -22.250721 0.000000
1.983273 11883.416016 4958.137695 12876.284180 2511.886230 -22.647444 0.000000
2.624793 12497.970703 5309.595215 13579.067383 1995.262329 -23.017561 0.000000
3.432418 13203.150391 5649.524414 14361.069336 1584.893188 -23.165701 0.000000
4.449158 14128.726562 6126.426270 15399.805664 1258.925293 -23.442274 0.000000
4.481158 14911.369141 6479.161133 16258.181641 1000.000000 -23.485498 0.000000
4.521444 15656.686523 6829.202637 17081.271484 794.328247 -23.566080 0.000000
4.572160 16835.632812 7643.918945 18489.673828 630.957336 -24.419577 0.000000
4.636009 18222.216797 8657.716797 20174.371094 501.187225 -25.413269 0.000000
4.716389 22157.533203 11829.420898 25117.552734 398.107178 -28.096781 0.000000
4.817582 23357.978516 11746.929688 26145.468750 316.227753 -26.698219 0.000000
4.944976 24984.910156 12806.191406 28075.687500 251.188629 -27.137728 0.000000
4.716389 20656.267578 10043.393555 22968.482422 398.107178 -25.929729 0.000000
4.817582 23355.941406 11758.861328 26149.011719 316.227753 -26.723581 0.000000
4.944976 24946.281250 12709.506836 27997.294922 251.188629 -26.997705 0.000000
5.105356 25699.732422 12844.353516 28730.708984 199.526230 -26.555218 0.000000
5.307262 28007.763672 13781.557617 31214.837891 158.489319 -26.200048 0.000000
5.561448 32278.408203 15294.345703 35718.519531 125.892532 -25.352806 0.000000
5.601448 36631.953125 16377.120117 40126.175781 100.000000 -24.088081 0.000000
5.651804 36212.464844 14175.981445 38888.316406 79.432823 -21.378698 0.000000
5.715200 31005.900391 10025.936523 32586.580078 63.095734 -17.918913 0.000000
5.795011 27789.210938 7751.479004 28850.054688 50.118721 -15.585830 0.000000
5.895486 35634.070312 9420.209961 36858.207031 39.810719 -14.807939 0.000000
6.021977 42739.617188 10889.406250 44105.035156 31.622778 -14.293976 0.000000
6.181220 41334.429688 12303.883789 43126.796875 25.118862 -16.576517 0.000000
6.381695 44635.375000 13761.085938 46708.503906 19.952623 -17.134529 0.000000
6.634078 47430.500000 9581.280273 48388.566406 15.848931 -11.420444 0.000000
6.951809 47006.734375 6501.482910 47454.214844 12.589253 -7.874598 0.000000
7.351809 47260.820312 5934.597168 47631.968750 10.000000 -7.157238 0.000000
7.855379 51975.855469 140.047073 51976.042969 7.943282 -0.154381 0.000000
8.489336 58372.769531 2538.466309 58427.937500 6.309573 -2.490062 0.000000
9.287441 59285.113281 8795.745117 59934.046875 5.011872 -8.439040 0.000000
10.292196 55917.351562 9934.631836 56793.019531 3.981072 -10.074409 0.000000
11.557107 51669.527344 1365.285522 51687.562500 3.162278 -1.513598 0.000000
13.149536 nan nan nan 2.511886 2.248806 0.000000
15.154285 nan nan nan 1.995262 4.537589 0.000000
17.678116 nan nan nan 1.584893 1.901186 0.000000
20.855431 nan nan nan 1.258925 -14.520571 0.000000
22.855431 nan nan nan 1.000000 -21.347967 0.000000
25.373281 nan nan nan 0.794328 -16.286789 0.000000
28.543070 43693.843750 2706.736816 43777.601562 0.630957 -3.544817 0.000000
32.533596 34982.421875 -4359.896973 35253.062500 0.501187 7.104203 0.000000
37.557373 30128.955078 -116.846642 30129.181641 0.398107 0.222204 0.000000
43.881924 32771.234375 6115.649902 33336.992188 0.316228 -10.570740 0.000000
51.844055 18206.365234 -7035.584961 19518.482422 0.251189 21.128300 0.000000
61.867813 -1157.350342 -5457.016602 5578.395020 0.199526 101.974136 0.000000
74.486984 -7572.944336 -5757.060547 9512.792969 0.158489 142.757385 0.000000
90.373489 -6719.222656 -12092.010742 13833.461914 0.125893 119.059814 0.000000
110.373489 2759.366699 -3812.787109 4706.532715 0.100000 54.106220 0.000000

View File

@@ -0,0 +1,5 @@
Time(s) Zre(Ohm) Zim(Ohm) Z(Ohm) Freq(Hz) Phase(deg) EDC(mV)
0.128000 5301.714355 1606.345947 5539.722168 10000.000000 -16.856081 0.000000
0.272000 5303.290527 1594.772095 5537.886719 8888.900391 -16.736752 0.000000
0.436571 5347.800781 1595.693970 5580.789551 7777.799805 -16.614220 0.000000
0.628570 5478.396973 1635.483032 5717.310547 6666.700195 -16.622107 0.000000

View File

@@ -0,0 +1,70 @@
initialize: True
get_machine_ids: {'success': True, 'machine_ids': [1, 3, 2]}
version: reflect_linear_scan_signature
linear_scan_related_methods:
Add_ConstantPotential:['System.String', 'System.Single', 'System.Int32', 'System.Boolean', 'System.Boolean', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['parentTag', 'Voltage', 'VoltageVSType', 'IsAccrueQ', 'isVoltageTrig', 'VoltageOrCurrentTrigDirection', 'VoltageOrCurrentTrigValue', 'capacityTrigDirection', 'capacityTrigValue', 'timePerPoint', 'continueTime', 'IsUseResolution', 'Resolution', 'isUseDeltaI', 'deltaI', 'isUseDeltaQ', 'deltaQ', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_Circle_Voltammetry_Multi:['System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['IsUseInitialPotential', 'InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'IsUseFinallyPotential', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Staircase_Cyclic_Voltammetry_MultipleCycles:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Linear_Scan_Voltammetry:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Linear_Scan_Voltammetry_New:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'voltageInterval', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Circle_Voltammetry_Single:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['InitialPotential', 'InitialPotentialVSType', 'TopPotential', 'TopPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Staircase_Linear_Scan:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Potentiodynamic:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Staircase_Cyclic_Voltammetry_Single:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'TopPotential', 'TopPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_ChronoamperonetryParam:['System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'InitialPotential', 'InitialPotentialVSType', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_ChronopotentiometryParam:['System.Single', 'System.Single', 'System.Single', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'current', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_ChronocoulometryParam:['System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'potential', 'potentialotentialVSType', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_ConstantPotential:['System.Single', 'System.Int32', 'System.Boolean', 'System.Boolean', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['Voltage', 'VoltageVSType', 'IsAccrueQ', 'isVoltageTrig', 'VoltageOrCurrentTrigDirection', 'VoltageOrCurrentTrigValue', 'capacityTrigDirection', 'capacityTrigValue', 'timePerPoint', 'continueTime', 'IsUseResolution', 'Resolution', 'isUseDeltaI', 'deltaI', 'isUseDeltaQ', 'deltaQ', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_Potentiostatic_Staircase:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['OutputValue1', 'vsType1', 'OutputValue2', 'vsType2', 'OutputValue3', 'vsType3', 'timePerPoint', 'stepCount', 'measureDelay', 'plusTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Fast_Potential_Pulses:['System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['plusCount', 'OutputValue1', 'ContinueTime1', 'vsType1', 'OutputValue2', 'ContinueTime2', 'vsType2', 'OutputValue3', 'ContinueTime3', 'vsType3', 'OutputValue4', 'ContinueTime4', 'vsType4', 'OutputValue5', 'ContinueTime5', 'vsType5', 'timePerPoint', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
StartConstantPotential_LineScan:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StaticTime', 'CycleCount', 'TimePerPoint', 'ContinueTime', 'StepHeight', 'SweptRate', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Circle_Voltammetry_Multi_New:['System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['voltageInterval', 'IsUseInitialPotential', 'InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'IsUseFinallyPotential', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Staircase_Cyclic_Voltammetry_MultipleCycles_New:['System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['IsUseInitialPotential', 'InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'IsUseFinallyPotential', 'FinallyPotential', 'FinallyPotentialVSType', 'stepHeight', 'stepTime', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
all_start_methods:
Start_Circle_Voltammetry_Multi:['System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['IsUseInitialPotential', 'InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'IsUseFinallyPotential', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Staircase_Cyclic_Voltammetry_MultipleCycles:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_SplitLPR:['System.Single', 'System.Single', 'ECCore.VSType', 'System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['aNodeVoltage', 'cathodeVoltage', 'aNodeVSTye', 'stepHeight', 'stepTime', 'continueTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_OpenCircuit:['System.Single', 'System.Single', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'machineId']
Start_Galvanic_Corrosion:['System.Single', 'System.Single', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'machineId']
Start_Electrochemical_Noise_En:['System.Single', 'System.Single', 'System.Int32', 'System.Int32'] | names=['timePerPoint', 'timePerSegment', 'segmentCount', 'machineId']
Start_Linear_Scan_Voltammetry:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Linear_Scan_Voltammetry_New:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'voltageInterval', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Circle_Voltammetry_Single:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['InitialPotential', 'InitialPotentialVSType', 'TopPotential', 'TopPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Staircase_Linear_Scan:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Potentiodynamic:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Galvanodynamic:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Staircase_Cyclic_Voltammetry_Single:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'TopPotential', 'TopPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Cyclic_Polarization:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.String', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'TopPotential', 'TopPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'voltageTrigValue', 'currentTrigValue', 'machineId']
Start_ChronoamperonetryParam:['System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'InitialPotential', 'InitialPotentialVSType', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_ChronopotentiometryParam:['System.Single', 'System.Single', 'System.Single', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'current', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_ChronocoulometryParam:['System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'potential', 'potentialotentialVSType', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_SquareWare:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['initialPotential', 'initialPotentialVSType', 'finallyPotential', 'finallyPotentialVSType', 'stepHeight', 'pluseHeight', 'startFreq', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_DifferentialPulse:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['initialPotential', 'initialPotentialVSType', 'finallyPotential', 'finallyPotentialVSType', 'stepHeight', 'pluseHeight', 'pluseWidth', 'stepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_NormalPulse:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['initialPotential', 'initialPotentialVSType', 'finallyPotential', 'finallyPotentialVSType', 'stepHeight', 'pluseWidth', 'stepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_EIS:['System.Boolean', 'System.Double', 'System.Double', 'System.Single', 'System.Int32', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single', 'System.Int32'] | names=['isVolEIS', 'StartFreq', 'EndFreq', 'Amplitude', 'IntervalType', 'PointCount', 'Voltage', 'VoltageVSType', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime', 'dataQuality']
Start_EnergyOpenCircuit:['System.Boolean', 'System.Single', 'System.Boolean', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['isUseExcursionRate', 'excursionRate', 'isVoltageTrig', 'VoltageOrCurrentTrigDirection', 'VoltageOrCurrentTrigValue', 'capacityTrigDirection', 'capacityTrigValue', 'timePerPoint', 'continueTime', 'IsUseResolution', 'Resolution', 'isUseDeltaI', 'deltaI', 'isUseDeltaQ', 'deltaQ', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_ConstantPotential:['System.Single', 'System.Int32', 'System.Boolean', 'System.Boolean', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['Voltage', 'VoltageVSType', 'IsAccrueQ', 'isVoltageTrig', 'VoltageOrCurrentTrigDirection', 'VoltageOrCurrentTrigValue', 'capacityTrigDirection', 'capacityTrigValue', 'timePerPoint', 'continueTime', 'IsUseResolution', 'Resolution', 'isUseDeltaI', 'deltaI', 'isUseDeltaQ', 'deltaQ', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_ConstantContent:['System.Single', 'System.Boolean', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['current', 'isVoltageTrig', 'VoltageOrCurrentTrigDirection', 'VoltageOrCurrentTrigValue', 'capacityTrigDirection', 'capacityTrigValue', 'timePerPoint', 'continueTime', 'IsUseResolution', 'Resolution', 'isUseDeltaI', 'deltaI', 'isUseDeltaQ', 'deltaQ', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_CurrentChargeDisCharge:['System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Int32', 'ECCore.SwithPriority', 'ECCore.TimeType', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['CurrentValue1', 'TimeLimitValue1', 'Vol1LimitValue1', 'CurrentValue2', 'TimeLimitValue2', 'Vol1LimitValue2', 'timePerPoint', 'CycleCount', 'CurrentSwithPriority', 'timeType', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_ConstantPower:['System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['power', 'isCharge', 'currentUpLimit', 'isVoltageTrig', 'VoltageOrCurrentTrigDirection', 'VoltageOrCurrentTrigValue', 'capacityTrigDirection', 'capacityTrigValue', 'timePerPoint', 'continueTime', 'IsUseResolution', 'Resolution', 'isUseDeltaI', 'deltaI', 'isUseDeltaQ', 'deltaQ', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_ConstantResistance:['System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['resistance', 'isCharge', 'currentUpLimit', 'isVoltageTrig', 'VoltageOrCurrentTrigDirection', 'VoltageOrCurrentTrigValue', 'capacityTrigDirection', 'capacityTrigValue', 'timePerPoint', 'continueTime', 'IsUseResolution', 'Resolution', 'isUseDeltaI', 'deltaI', 'isUseDeltaQ', 'deltaQ', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'machineId']
Start_Tafel:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_LPR:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['InitialPotential', 'InitialPotentialVSType', 'FinallyPotential', 'FinallyPotentialVSType', 'StepHeight', 'StepTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Zra:['System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['timePerPoint', 'continueTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Potentiostatic_Staircase:['System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['OutputValue1', 'vsType1', 'OutputValue2', 'vsType2', 'OutputValue3', 'vsType3', 'timePerPoint', 'stepCount', 'measureDelay', 'plusTime', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Fast_Potential_Pulses:['System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['plusCount', 'OutputValue1', 'ContinueTime1', 'vsType1', 'OutputValue2', 'ContinueTime2', 'vsType2', 'OutputValue3', 'ContinueTime3', 'vsType3', 'OutputValue4', 'ContinueTime4', 'vsType4', 'OutputValue5', 'ContinueTime5', 'vsType5', 'timePerPoint', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Fast_Galvanic_Pulses:['System.Int32', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32'] | names=['plusCount', 'OutputValue1', 'ContinueTime1', 'OutputValue2', 'ContinueTime2', 'OutputValue3', 'ContinueTime3', 'OutputValue4', 'ContinueTime4', 'OutputValue5', 'ContinueTime5', 'timePerPoint', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId']
Start_Circle_Voltammetry_Multi_New:['System.Single', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['voltageInterval', 'IsUseInitialPotential', 'InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'IsUseFinallyPotential', 'FinallyPotential', 'FinallyPotentialVSType', 'ScanRate', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_Staircase_Cyclic_Voltammetry_MultipleCycles_New:['System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Single', 'System.Int32', 'System.Boolean', 'System.Single', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.Single'] | names=['IsUseInitialPotential', 'InitialPotential', 'InitialPotentialVSType', 'TopPotential1', 'TopPotential1VSType', 'TopPotential2', 'TopPotential2VSType', 'IsUseFinallyPotential', 'FinallyPotential', 'FinallyPotentialVSType', 'stepHeight', 'stepTime', 'cycleCount', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'machineId', 'delayTime']
Start_OpenCircuit_All:['System.Single', 'System.Single'] | names=['timePerPoint', 'continueTime']
Start_EIS_All:['System.Boolean', 'System.Double', 'System.Double', 'System.Single', 'System.Int32', 'System.Int32', 'System.Single', 'System.Single', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Int32', 'System.String', 'System.Single', 'System.Int32'] | names=['isVolEIS', 'StartFreq', 'EndFreq', 'Amplitude', 'IntervalType', 'PointCount', 'Voltage', 'VoltageVSType', 'isVoltageRandAuto', 'VoltageRand', 'isCurrentRandAuto', 'currentRand', 'isVoltageFilterAuto', 'VoltageFilter', 'isCurrentFilterAuto', 'currentFilter', 'delayTime', 'dataQuality']
version: lsv_v1
version: lsv_v1
start_cv_params: {'is_use_initial_potential': True, 'initial_potential': -1.0, 'initial_potential_vs_type': 0, 'top_potential1': 1.0, 'top_potential1_vs_type': 0, 'top_potential2': -2.0, 'top_potential2_vs_type': 0, 'is_use_finally_potential': True, 'finally_potential': -1.0, 'finally_potential_vs_type': 0, 'scan_rate': 0.2, 'cycle_count': 2, 'is_voltage_rand_auto': 1, 'voltage_rand': '1000', 'is_current_rand_auto': 1, 'current_rand': '1000', 'is_voltage_filter_auto': 1, 'voltage_filter': '10Hz', 'is_current_filter_auto': 1, 'current_filter': '10Hz', 'machine_id': 2}
start_cv: {'success': True, 'return_info': 'ok', 'machine_id': 2}
start_realtime_output_cv: {'success': True, 'running': True, 'machine_id': 2, 'file': 'D:\\Uni-Lab-OS\\Uni-Lab-OS\\unilabos\\devices\\donghua_ec\\x64release\\DHInterface\\SourceData\\2025-12-12\\循环伏安\\2号机(循环伏安(多循环)).txt'}
result_types: [0]
data_details: [{'cand': 0, 'len': 0, 'd3': (0, 0, 0), 'd4': (0, 0, 0, 0), 'd7': (0, 0, 0, 0, 0, 0, 0)}]
stop_realtime_output_cv: {'success': True, 'machine_id': 2, 'file': 'D:\\Uni-Lab-OS\\Uni-Lab-OS\\unilabos\\devices\\donghua_ec\\x64release\\DHInterface\\SourceData\\2025-12-12\\循环伏安\\2号机(循环伏安(多循环)).txt'}
export_cyclic_voltammetry: {'success': True, 'files': ['D:\\Uni-Lab-OS\\Uni-Lab-OS\\unilabos\\devices\\donghua_ec\\exports\\循环伏安\\2号机(循环伏安(多循环)).txt'], 'dest': 'D:\\Uni-Lab-OS\\Uni-Lab-OS\\unilabos\\devices\\donghua_ec\\exports\\循环伏安'}
stop_experiment_cv: {'success': True, 'machine_id': 2}

Some files were not shown because too many files have changed in this diff Show More