
knowledge-work-plugins 实战将 Allotrope ASM JSON 扁平化为 2D CSV 的完整指南【免费下载链接】knowledge-work-pluginsOpen source repository of plugins primarily intended for knowledge workers to use in Claude Cowork项目地址: https://gitcode.com/GitHub_Trending/kn/knowledge-work-plugins本文是instrument-data-to-allotrope技能中 flattening_guide.md 的深度展开版面向需要在 LIMS 导入、Excel/CSV 分析、数据库加载与数据工程流水线中使用实验室仪器数据的科学家与数据工程师。读完本文你将掌握 ASM 分层 JSON 到二维表格的转换策略、列命名约定、数据立方体的三种处理方式以及仓库内 flatten_asm.py 的完整调用方式与底层实现原理。为什么需要扁平化Allotrope Simple ModelASM是一种语义丰富但结构高度分层的 JSON 标准它能完整表达仪器硬件信息、设备控制参数、样品信息与测量结果之间的嵌套关系。然而正是这种分层结构给下游系统带来了集成障碍LIMS 导入Benchling、STARLIMS、LabWare——大多数 LIMS 以关系表形式存储数据期望每行是一条记录Excel / CSV 分析——科学家日常使用的电子表格无法直接解析多层 JSON数据库加载——关系型数据库的批量导入工具通常只接受扁平的二维结构快速可视化检查——人眼阅读表格远比阅读嵌套 JSON 高效。扁平化的目标就是在不丢失实验数据语义的前提下把分层 ASM 转换为一表到底的二维结构。扁平化策略核心原则每条测量一行元数据逐行重复扁平化的根本准则是每个measurement-document中的测量项measurement生成一行记录。位于测量项之外的元数据——如仪器序列号、型号、操作员、测量时间——属于通用上下文会在每一行中重复出现。这样既保证了行的独立性单行即可理解又符合 LIMS 与数据库表一行一实体的建模习惯。有意排除的内容扁平化过程有意省略 ASM 顶层的元数据包括$asm.manifest模型版本、schema URI 等技术聚合文档technique-aggregate-document之外根级字段。这样做的目的是让输出聚焦于实验数据本身。如果你的合规或审计流程需要追踪 schema 版本建议将原始 ASM JSON 与扁平化 CSV 一并归档或者修改扁平化脚本以保留这些字段。仓库中的 convert_to_asm.py 默认输出即包含$asm.manifest与$conversion_metadata含 allotropy 版本、输入文件 SHA256、转换时间等溯源信息可作为审计配套文件留存。层级到列的映射ASM 层级扁平列名device-system-document.device-identifierinstrument_serial_numberdevice-system-document.model-numberinstrument_modelmeasurement-aggregate-document.analystanalystmeasurement-aggregate-document.measurement-timemeasurement_datetimemeasurement-document[].sample-identifiersample_idmeasurement-document[].viable-cell-density.valueviable_cell_densitymeasurement-document[].viable-cell-density.unitviable_cell_density_unitmeasurement-document[].viability.valueviability_percent在仓库的 flatten_asm.py 中这一映射被实现为三级遍历先通过detect_technique()从顶层键识别技术类型如cell-counting-aggregate-document推断出cell-counting再提取device-system-document的共享设备信息最后逐条展开measurement-document。列命名约定扁平化列名统一使用snake_case并附加语义明确的后缀ASM 字段扁平列名viable-cell-densityviable_cell_density.value数值本身_value若含义已明确可省略.unit单位_unitmeasurement-timemeasurement_datetime这一约定的逻辑来自 ASM 的Value Datum 模式数值与单位成对出现如{value: 2500000, unit: (cell/mL)}。扁平化时数值直接作为主列值单位追加_unit后缀独立成列。在 flatten_asm.py 的flatten_value()函数中可以看到完整的处理逻辑命中value键即判定为 Value Datum同时展开unit嵌套字典则递归拍平并用下划线连接层级数组默认序列化为 JSON 字符串存入单元格。示例一细胞计数Cell CountingASM 输入简化{ cell-counting-aggregate-document: { device-system-document: { device-identifier: VCB001, model-number: Vi-CELL BLU }, cell-counting-document: [{ measurement-aggregate-document: { analyst: jsmith, measurement-time: 2024-01-15T10:30:00Z, measurement-document: [ { sample-identifier: Sample_A, viable-cell-density: {value: 2500000, unit: (cell/mL)}, viability: {value: 95.2, unit: %} }, { sample-identifier: Sample_B, viable-cell-density: {value: 1800000, unit: (cell/mL)}, viability: {value: 88.7, unit: %} } ] } }] } }扁平化输出sample_id,viable_cell_density,viable_cell_density_unit,viability_percent,analyst,measurement_datetime,instrument_serial_number,instrument_model Sample_A,2500000,(cell/mL),95.2,jsmith,2024-01-15T10:30:00Z,VCB001,Vi-CELL BLU Sample_B,1800000,(cell/mL),88.7,jsmith,2024-01-15T10:30:00Z,VCB001,Vi-CELL BLU注意两个测量项Sample_A、Sample_B各自成为一行而analyst、measurement_datetime、instrument_serial_number、instrument_model作为公共元数据被逐行重复。这正是一条测量一行原则的直观体现。补充测量级命名细节上例中viability.value对应列名为viability_percent而非viability。在 flatten_asm.py 的通用实现中Value Datum 会直接生成viability与viability_unit两列若你希望输出viability_percent这样的语义化列名可以在展开逻辑中加入自定义字段映射表。这种默认通用 按需定制的设计正是 SKILL.md 中Modify the references/ files to include your companys specific schemas所鼓励的扩展方式。示例二酶标仪Plate ReaderASM 输入简化{ plate-reader-aggregate-document: { plate-reader-document: [{ measurement-aggregate-document: { plate-identifier: ELISA_001, measurement-document: [ {well-location: A1, absorbance: {value: 0.125, unit: mAU}}, {well-location: A2, absorbance: {value: 0.892, unit: mAU}}, {well-location: A3, absorbance: {value: 1.456, unit: mAU}} ] } }] } }扁平化输出plate_id,well_position,absorbance,absorbance_unit ELISA_001,A1,0.125,mAU ELISA_001,A2,0.892,mAU ELISA_001,A3,1.456,mAU从 asm_schema_overview.md 可知plate-reader 技术的关键字段还包括fluorescence、luminescence、well-locationA1-H12、plate-identifier它们遵循完全相同的 Value Datum 展开规则。处理数据立方体Data Cubes时间序列、光谱这类多维数据数据立方体无法直接放入单个二维单元格需要特殊处理。文档提供三种可选方案方案一按点展开成多行长格式每个数据点一行适合时间序列的趋势分析与数据库存储sample_id,time_seconds,absorbance Sample_A,0,0.100 Sample_A,60,0.125 Sample_A,120,0.150方案二宽格式测量项作为列每个时间点一列适合 Excel 透视表式阅读sample_id,abs_0s,abs_60s,abs_120s Sample_A,0.100,0.125,0.150方案三单元格内保留 JSON 数组部分系统如支持 JSON 列的数据库可以直接承载数组sample_id,absorbance_timeseries Sample_A,[0.100,0.125,0.150]从实现角度看仓库 flatten_asm.py 默认采用方案三当叶节点值是数组时通过json.dumps将其序列化为 JSON 字符串存入单元格保证转换永不丢数据。若你需要方案一或方案二可以在展开逻辑中针对cube-structure/data键做专门的维度拆分数据立方体的结构定义可参考 asm_schema_overview.md 中的 Data Cube 示例。各技术的标准列集为了让输出列稳定、可预测文档按技术预定义了标准列集。这些列可作为扁平化脚本的列顺序模板也可作为列映射的目标。细胞计数Cell Countingsample_id, viable_cell_density, viable_cell_density_unit, total_cell_count, viability_percent, average_cell_diameter, average_cell_diameter_unit, analyst, measurement_datetime, instrument_serial_number分光光度法Spectrophotometrysample_id, wavelength_nm, absorbance, pathlength_cm, concentration, concentration_unit, a260_a280_ratio, a260_a230_ratio, analyst, measurement_datetime, instrument_serial_number酶标仪 / ELISAPlate Readerplate_id, well_position, sample_type, sample_id, absorbance, absorbance_unit, concentration, concentration_unit, dilution_factor, cv_percent, analyst, measurement_datetime, instrument_serial_numberqPCRsample_id, target_name, well_position, ct_value, ct_mean, ct_sd, quantity, quantity_unit, amplification_efficiency, analyst, measurement_datetime, instrument_serial_number仓库 flatten_asm.py 内置了一个优先级列排序逻辑sample_identifier、sample_id、well_location、well_position、measurement_time、measurement_datetime、analyst等列会被优先放到 CSV 前面其余列按字典序补在后面从而让输出与上述标准列集保持一致的阅读体验。Python 实现文档给出了一个完整、可直接运行的flatten_asm()函数import json import pandas as pd def flatten_asm(asm_dict, techniquecell-counting): Flatten ASM JSON to pandas DataFrame. Args: asm_dict: Parsed ASM JSON technique: ASM technique type Returns: pandas DataFrame with one row per measurement rows [] # Get aggregate document agg_key f{technique}-aggregate-document agg_doc asm_dict.get(agg_key, {}) # Extract device info device agg_doc.get(device-system-document, {}) device_info { instrument_serial_number: device.get(device-identifier), instrument_model: device.get(model-number) } # Get technique documents doc_key f{technique}-document for doc in agg_doc.get(doc_key, []): meas_agg doc.get(measurement-aggregate-document, {}) # Extract common metadata common { analyst: meas_agg.get(analyst), measurement_datetime: meas_agg.get(measurement-time), **device_info } # Extract each measurement for meas in meas_agg.get(measurement-document, []): row {**common} # Flatten measurement fields for key, value in meas.items(): if isinstance(value, dict) and value in value: # Value datum pattern col key.replace(-, _) row[col] value[value] if unit in value: row[f{col}_unit] value[unit] else: row[key.replace(-, _)] value rows.append(row) return pd.DataFrame(rows) # Usage with open(asm_output.json) as f: asm json.load(f) df flatten_asm(asm, cell-counting) df.to_csv(flattened_output.csv, indexFalse)仓库实现的增强版本上述示例函数是教学版。生产环境中建议直接使用仓库内的 flatten_asm.py它在教学版基础上增强了三点技术自动检测detect_technique()通过扫描顶层键中的-aggregate-document后缀自动判断技术类型无需手动传入technique参数见 flatten_asm.py更丰富的设备信息extract_device_info()除序列号与型号外还提取product-manufacturer厂商、software-name、software-version软件名与版本且自动过滤None空值列见 flatten_asm.py测量级元数据展开measurement-aggregate-document中除measurement-document外的标量字段如plate-identifier、sample-role-type会一并展开为公共列嵌套的 Value Datum 同样处理见 flatten_asm.py。命令行调用flatten_asm.py 同时提供 CLI 入口# 基本用法输入 ASM JSON输出 CSV python scripts/flatten_asm.py asm_output.json # 指定输出路径 python scripts/flatten_asm.py asm_output.json --output flattened.csv # 指定输出格式csv 或 json默认 csv python scripts/flatten_asm.py asm_output.json --format json参数说明参数说明默认值input输入 ASM JSON 文件路径必填无--output/-o输出文件路径输入名.flat.csv或输入名.flat.json--format输出格式csv或jsoncsv--format json会调用flatten_asm_to_dict()见 flatten_asm.py返回{columns: [...], rows: [[...]]}结构便于在非 CSV 的下游处理中复用。命令结束后会打印统计信息行数与列数便于核对转换完整性。CSV 输出依赖 pandas未安装时会提示pip install pandas。与转换流水线的集成在实际工作流中ASM 通常不是手工编写的而是由 convert_to_asm.py 从仪器原始文件CSV、Excel、TXT、PDF转换而来。该脚本内置了--flatten开关可在转换的同时直接生成扁平化 CSV# 将 Vi-CELL BLU 的 CSV 转为 ASM JSON并同时生成扁平化 CSV python scripts/convert_to_asm.py viCell_Results.csv --vendor BECKMAN_VI_CELL_BLU --flatten从源码可见convert_to_asm.py--flatten分支会调用flatten_asm_to_csv()将输出写入输入名.flat.csv。整个流水线检测仪器 → allotropy 原生解析或回退解析 → 校验 → 扁平化的完整流程与--vendor、--allow-fallback、--skip-validation、--force等参数说明见 SKILL.md。验证扁平化输出的正确性扁平化发生在 ASM 校验之后但仍有必要对输出本身做质量检查。仓库的 validate_asm.py 虽然面向 ASM JSON但其检查项对扁平化设计具有重要指导意义# 校验 ASM 输出 python scripts/validate_asm.py output.json # 对照已知良好样本校验 python scripts/validate_asm.py output.json --reference known_good.json # 严格模式警告视为错误 python scripts/validate_asm.py output.json --strict校验规则包括技术选择是否正确、字段命名是否符合规范、计算数据是否有data-source-aggregate-document溯源、测量项与计算值是否具有唯一标识、必要元数据是否存在、单位与样品角色是否合法未知值仅产生警告以保证前向兼容。这些规则中字段命名与嵌套文档结构两项与扁平化关系最密切——如果 ASM 构建时将sample-identifier之类的字段错误地平铺在测量文档上而非包在sample document中扁平化输出的列结构也会跟着错乱。因此建议在扁平化前后各运行一次校验相关嵌套规范详见 field_classification_guide.md。LIMS 导入注意事项将扁平化 CSV 导入 LIMS 前请逐项核对列名匹配将输出列名映射到你的 LIMS schema 字段名。各技术的标准列集上文第五节可作为映射基准时间戳格式使用 ISO 8601 格式如2024-01-15T10:30:00Z避免 LIMS 解析歧义样品 ID 一致性确保扁平化 CSV 中的样品 ID 与 LIMS 中已存在的样品标识完全一致否则关联会失败单位列策略确认你的 LIMS 期望单位放在独立列_unit列还是内嵌在数值中如2500000 (cell/mL)。文档默认输出独立_unit列若 LIMS 要求内嵌格式需在导出前做列合并处理。此外若实验包含计算值如细胞计数中的活力百分比、酶标仪中的标准曲线浓度ASM 中这些值位于calculated-data-aggregate-document而非measurement-document。从源码结构看flatten_asm.py 目前仅展开测量文档需要保留计算值及其data-source-aggregate-document溯源关系时建议单独扩展一个针对计算数据的展开函数以保证扁平化后的表格在审计时可追溯到原始测量计算数据的溯源 JSON 结构见 SKILL.md。小结ASM 扁平化的本质是一次有损于层级、无损于语义的视图转换每条测量一行公共元数据逐行重复Value Datum 自动拆分为数值列 单位列数据立方体按场景选择长格式、宽格式或 JSON 单元格。借助仓库中的 flatten_asm.py、convert_to_asm.py 与 validate_asm.py你可以在一条命令行内完成仪器文件 → ASM → 扁平 CSV → 校验的完整链路为 LIMS 导入与数据工程流水线提供稳定、可复现、可审计的标准化输出。【免费下载链接】knowledge-work-pluginsOpen source repository of plugins primarily intended for knowledge workers to use in Claude Cowork项目地址: https://gitcode.com/GitHub_Trending/kn/knowledge-work-plugins创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考