"""CHEM-167 Bio-Rad CFX Opus 96 Real-Time PCR System (catalog 12011319): process runtime. Device (Bulletin 7299, Bulletin 7279, Instrument Guide 10000119983): rear power switch; motorised retractable heated lid (30-110 C, default 105 C, opened / closed only from the touch screen or software, obstruction stop); fixed 96-well Peltier block 4-100 C, max ramp 5 C/s, average 3.3 C/s, accuracy +-0.2 C at 90 C, uniformity +-0.3 C, gradient across the rows (30-100 C, span 1-24 C); sample volume 1-50 ul with the calculated (volume > 0) or block (volume 0) temperature-control mode; protocol steps: temperature (4.0-100.0 C, hold 1 s-17:59:59 or infinite, ramp 0.1-5 C/s, increment -10..10 C/cycle, extend -60..60 s/cycle, plate read, beep), gradient, GOTO (default 39 repeats) and melt curve; optics shuttle with 6 filtered LEDs / 6 filtered photodiodes: channels 1-5 (FAM, HEX, Texas Red, Cy5, Quasar 705; documented bands) + FRET, scan 12 s all channels or 3 s single channel; LED status bar (green run, green flashing pause, blue flashing complete until the lid opens, red error). Process model (fixed 0.1 s grid, numpy over the 96 wells): block Peltier servo (slew-limited proportional approach calibrated to the documented average ramp), row gradient, a deterministic +-0.2 / +-0.3 C accuracy / uniformity pattern, per-well sample temperature lag depending on the volume, heated lid; PCR chemistry per well and assay: a synthesis event closes every time the sample is re-heated after a cool phase - new copies = copies x E_max x denaturation completeness (amplicon Tm, two-state) x primer annealing (primer Tm, with the mild low-temperature penalty of the brochure GAPDH gradient) x extension completeness (polymerase speed vs. amplicon length) x hot-start activation x inhibitor x primer reserve, capped by the polymerase capacity (linear phase); primer dimers in SYBR wells without template; TaqMan probes cleaved by synthesis; fluorescence = dye amount x brightness x channel response (FPbase spectra x documented bands) x plate factor, plus background and deterministic noise; the factory dye calibration unmixes the channels; analysis as CFX Maestro: baseline-subtracted curves, auto threshold (10 x baseline SD), fractional Cq, standard curve (slope, efficiency, R2, unknown quantities), melt peaks (-dRFU/dT) and DeltaCq / DeltaDeltaCq.""" import copy import csv import hashlib import io import json import math import os import tempfile from pathlib import Path import numpy as np PROTOCOL_VERSION = "1.0.0" ASSET_VERSION = '1.1.2' ASSET_TYPE_ID = "instrument.biorad_cfxopus" CATALOG_ID = "CHEM-167" ROOT = Path(__file__).resolve().parents[2] ASSET_DIR = ROOT / 'assets/expansion_batch04/t4_measure/biorad_cfxopus' LIBS = {'fluorophores': 'fluorophore_library.json', 'assays': 'assay_library.json', 'optics': 'optics_model.json'} # ---------------------------------------------------------------- constants (SI) R_GAS = 8.314462618 AVOGADRO = 6.02214076e23 DT = 0.1 # physics grid (s) ROWS, COLS = 'ABCDEFGH', 12 WELLS = [f'{r}{c}' for r in ROWS for c in range(1, COLS + 1)] WIDX = {w: i for i, w in enumerate(WELLS)} NW = len(WELLS) MAX_ASSAYS = 5 # up to 5 targets per well (documented multiplex) T_BLOCK_RANGE = (277.15, 373.15) # 4-100 C T_LID_RANGE = (303.15, 383.15) # 30-110 C LID_DEFAULT_K = 378.15 # 105 C (documented default for the 96-well block) LID_IDLE_K = 304.15 # lid keeps 31 C during an infinite hold below 30 C (documented) RAMP_MAX = 5.0 # K/s documented maximum RAMP_GAIN = 0.9 # 1/s proportional approach: 60 -> 95 C arrives (0.1 K) in ~10.4 s = 3.4 K/s average (documented average 3.3) ARRIVE_K = 0.1 VOLUME_RANGE = (0.0, 50e-9) # protocol sample volume setting (m3); 0 = block mode GRADIENT_RANGE = ((303.15, 372.15), 373.15, (1.0, 24.0)) SCAN_S = {'all_channels': 12.0, 'sybr_fam': 3.0, 'fret': 3.0} CHANNELS = ['1', '2', '3', '4', '5', '6'] CHANNEL_NAME = {'1': 'FAM', '2': 'HEX', '3': 'Texas Red', '4': 'Cy5', '5': 'Quasar 705', '6': 'FRET'} LID_TRAVEL = 0.232 # m, retracted (interface definition) LID_TIME_S = 6.0 # motorised lid travel time (engineering) SCREEN_RANGE = (0.0, (55.0 - 12.0) * math.pi / 180) MAX_STEPS = 40 # protocol length limit of this model (assumption; the guide gives none) MAX_GOTO_CYCLES = 99 # GOTO repeat limit of this model (assumption; the guide gives the default 39 only) GOTO_DEFAULT_CYCLES = 39 # documented default number of GOTO repeats MAX_RUNS = 50 MAX_EVENTS = 1000 PLATE_TYPES = {'white_lowprofile_96': dict(factor_key='white_wells', max_ul=200.0), 'clear_lowprofile_96': dict(factor_key='clear_wells', max_ul=200.0), 'white_8tube_strips': dict(factor_key='white_wells', max_ul=200.0)} # well capacity 200 ul: typical low-profile plate (assumption) SEALS = ['optical_film', 'heat_seal', 'none'] CHEMISTRIES = ['sybr', 'evagreen', 'probe'] SAMPLE_TYPES = ['unknown', 'standard', 'ntc', 'nrt', 'positive_control', 'negative_control'] # engineering chemistry constants (typical real-time PCR supermix; Bio-Rad does not publish the compositions) CHEM = dict(primer_mol_m3=4.0e-4, probe_mol_m3=2.5e-4, dntp_mol_m3=0.8, sybr_bp_sat_per_m3=1.5e22, sybr_free_fraction=0.002, sybr_temp_coeff=0.012, probe_residual=0.03, probe_bind=0.9, pol_capacity_per_m3=2.0e19, act_tau_s=30.0, act_t_k=367.15, anneal_width_k=1.0, anneal_offset_k=2.0, primer_mg_shift_k=4.0, low_penalty_per_k=0.0095, low_ref_offset_k=1.0, pol_speed_nt_s=70.0, pol_opt_k=345.15, pol_width_k=14.0, melt_width_k=1.6, melt_tm_offset_k=-3.0, pd_seed_base=0.3, pd_efficiency=0.95, pd_tm_k=348.15, pd_length_bp=45, tau_sample_base_s=1.0, tau_sample_per_volume_s_m3=0.15e9, evaporation_m3_per_s_k=5.5e-14) # primers 400 nM, probe 250 nM, dNTP 0.8 mM (stored in mol/m3); melt_tm_offset_k: the effective amplicon melting temperature in a SYBR supermix is # taken 3 K below the two-state nearest-neighbour value of the library (domain melting of long amplicons, supermix additives; assumption +-2 K) # primer annealing: the PrimerBank primer Tm (Primer3-type, monovalent salt only) is raised by ~4 K by the 3 mM Mg2+ of a PCR supermix (engineering); # annealing is complete up to ~(Tm + 4 K + 2 K); below the optimum (PrimerBank Tm + 1 K) mispriming / dimer competition costs 0.95 %/K (fitted to the # brochure GAPDH gradient in calibrate_cfx.py) FAULTS = ['power_loss', 'lid_obstructed', 'led_failure_channel_1', 'led_failure_channel_2', 'led_failure_channel_3', 'led_failure_channel_4', 'led_failure_channel_5', 'fan_failure', 'block_sensor_drift'] class ActionRejected(ValueError): """A capability call refused with a declared error code (no state change).""" # ---------------------------------------------------------------- libraries _LIBC = {} def _lib(name): if name not in _LIBC: _LIBC[name] = json.loads((ASSET_DIR / LIBS[name]).read_text()) return _LIBC[name] def fluorophores(): return _lib('fluorophores')['substances'] def assays(): return _lib('assays')['substances'] def optics(): return _lib('optics') CALIBRATED_DYES = ['fam', 'hex', 'rox_carboxy_x_rhodamine', 'texas_red', 'cy5', 'cy5_5', 'quasar_670', 'quasar_705', 'cal_fluor_orange_560', 'cal_fluor_red_610', 'sybr_green', 'evagreen'] # factory-calibrated dyes (assumption: the common CFX dyes; list in CFX Maestro guide) def dye_brightness(d): """Relative molar brightness ext. coeff. x quantum yield; FPbase gaps filled with 5e4 M-1 cm-1 and QY 0.5 (assumption).""" eps = d.get('ext_coeff_m1_cm1') or 5.0e4 qy = d.get('quantum_yield') or 0.5 return eps * qy / (7.13e4 * 0.5) # relative to FAM with the same fallback QY def resp_fam_ch1(): """FAM response in channel 1 x brightness: the detector scale rfu_per_nm_fam_ch1_20ul refers to it.""" f = fluorophores()['fam'] return f['channel_response']['1'] * dye_brightness(f) def response_matrix(dyes): """Channel response of each dye (rows: dyes, columns: channels 1-6) x brightness.""" fl = fluorophores() return np.array([[fl[d]['channel_response'].get(c, 0.0) * dye_brightness(fl[d]) for c in CHANNELS] for d in dyes]) # ---------------------------------------------------------------- deterministic noise _MASK = (1 << 64) - 1 def _mix(z): z = (z + 0x9E3779B97F4A7C15) & _MASK z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & _MASK z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & _MASK return z ^ (z >> 31) def _gauss(seed, a, b): x = _mix((seed * 1000003 + a * 4099 + b) & _MASK) y = _mix(x) u1 = ((x >> 11) + 0.5) / 9007199254740992.0 u2 = ((y >> 11) + 0.5) / 9007199254740992.0 return math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2) def _uniform(seed, a, b): return ((_mix((seed * 7919 + a * 131 + b) & _MASK) >> 11) + 0.5) / 9007199254740992.0 class _Sum: def __init__(self): self.s = 0.0 self.c = 0.0 def add(self, x): t = self.s + x if abs(self.s) >= abs(x): self.c += (self.s - t) + x else: self.c += (x - t) + self.s self.s = t def value(self): return self.s + self.c # ---------------------------------------------------------------- schema helpers (as CHEM-165 / CHEM-166) def number(unit='1', lo=None, hi=None): s = {'type': 'number', 'x-unit': unit} if lo is not None: s['minimum'] = lo if hi is not None: s['maximum'] = hi return s def obj(properties, optional=()): return dict(type='object', properties=properties, required=[k for k in properties if k not in optional], additionalProperties=False) def nullable(s): return {'anyOf': [s, {'type': 'null'}]} def array(s, minimum=0, maximum=4096): return dict(type='array', items=s, minItems=minimum, maxItems=maximum) def enum(items): return {'type': 'string', 'enum': list(items)} def integer(lo, hi): return {'type': 'integer', 'x-unit': '1', 'minimum': lo, 'maximum': hi} BOOL = {'type': 'boolean'} TEXT = {'type': 'string'} INT = {'type': 'integer', 'x-unit': '1'} def validate(s, v): if 'anyOf' in s: for o in s['anyOf']: try: validate(o, v) return except ActionRejected: pass raise ActionRejected('INVALID_ARGUMENT') k = s.get('type') if k in ('number', 'integer'): if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or (k == 'integer' and not float(v).is_integer()): raise ActionRejected('INVALID_ARGUMENT') if not s.get('minimum', -math.inf) <= v <= s.get('maximum', math.inf): raise ActionRejected('INVALID_ARGUMENT') elif k == 'object': if not isinstance(v, dict): raise ActionRejected('INVALID_ARGUMENT') if 'properties' in s: req = set(s.get('required', s['properties'])) if not req <= set(v) or not set(v) <= set(s['properties']): raise ActionRejected('INVALID_ARGUMENT') for key, value in v.items(): validate(s['properties'][key], value) elif 'additionalProperties' in s and isinstance(s['additionalProperties'], dict): if len(v) > s.get('maxProperties', math.inf): raise ActionRejected('INVALID_ARGUMENT') for key, value in v.items(): if 'propertyNames' in s: validate(s['propertyNames'], key) validate(s['additionalProperties'], value) elif k == 'array': if not isinstance(v, list) or not s.get('minItems', 0) <= len(v) <= s.get('maxItems', math.inf): raise ActionRejected('INVALID_ARGUMENT') for x in v: validate(s['items'], x) elif k == 'boolean' and type(v) is not bool: raise ActionRejected('INVALID_ARGUMENT') elif k == 'string': if not isinstance(v, str) or len(v) > s.get('maxLength', 10 ** 6) or len(v) < s.get('minLength', 0): raise ActionRejected('INVALID_ARGUMENT') if 'pattern' in s: import re if not re.fullmatch(s['pattern'], v): raise ActionRejected('INVALID_ARGUMENT') elif k == 'null' and v is not None: raise ActionRejected('INVALID_ARGUMENT') if 'enum' in s and v not in s['enum']: raise ActionRejected('INVALID_ARGUMENT') # ---------------------------------------------------------------- capabilities CAPS = {} def cap(k, s, o, e, c, meaning, visibility='agent', kind='device_command'): CAPS[k] = dict(input_schema=s, output_schema=o, example_arguments=e, component_ids=c, function_zh=meaning, visibility=visibility, kind=kind) SID = dict(type='string', minLength=1, maxLength=40, pattern='^[A-Za-z0-9_.-]+$') LIBID = dict(type='string', minLength=1, maxLength=80) WELL = enum(WELLS) PLANT_EXAMPLE = dict(room_k=295.15, mains_voltage_v=230.0, noise_seed=1) PLANT = obj(dict(room_k=number('K', 288.15, 308.15), mains_voltage_v=number('V', 0.0, 264.0), noise_seed=integer(0, 2 ** 31 - 1))) STEP = obj(dict(kind=enum(['temperature', 'gradient', 'goto', 'melt']), temperature_k=nullable(number('K', 277.15, 373.15)), hold_s=nullable(number('s', 1.0, 64799.0)), plate_read=BOOL, ramp_rate_k_s=nullable(number('K/s', 0.1, 5.0)), increment_k=number('K', -10.0, 10.0), extend_s=number('s', -60.0, 60.0), beep=BOOL, lower_k=nullable(number('K', 303.15, 372.15)), upper_k=nullable(number('K', 304.15, 373.15)), goto_step=nullable(integer(1, MAX_STEPS)), cycles=nullable(integer(1, MAX_GOTO_CYCLES)), start_k=nullable(number('K', 277.15, 373.15)), end_k=nullable(number('K', 277.15, 373.15)), melt_increment_k=nullable(number('K', 0.1, 5.0))), optional=('temperature_k', 'hold_s', 'plate_read', 'ramp_rate_k_s', 'increment_k', 'extend_s', 'beep', 'lower_k', 'upper_k', 'goto_step', 'cycles', 'start_k', 'end_k', 'melt_increment_k')) PROTOCOL_EXAMPLE = dict(name='SYBR_2step_melt', sample_volume_m3=2.0e-8, lid_temperature_k=378.15, steps=[ dict(kind='temperature', temperature_k=368.15, hold_s=30.0), dict(kind='temperature', temperature_k=368.15, hold_s=10.0), dict(kind='temperature', temperature_k=333.15, hold_s=30.0, plate_read=True), dict(kind='goto', goto_step=2, cycles=39), dict(kind='melt', start_k=338.15, end_k=368.15, melt_increment_k=0.5, hold_s=5.0)]) WELL_SPEC = obj(dict(well=WELL, sample_type=enum(SAMPLE_TYPES), sample_id=nullable(SID), dilution=number('1', 1e-12, 1.0), template_volume_m3=number('m3', 0.0, 5e-8), reaction_volume_m3=number('m3', 1e-9, 5e-8), assays=array(LIBID, 0, MAX_ASSAYS), chemistry=enum(CHEMISTRIES), reporters=array(LIBID, 0, MAX_ASSAYS), quantity_copies=nullable(number('1', 0.0, 1e13)), biological_group=nullable(SID)), optional=('sample_id', 'dilution', 'template_volume_m3', 'reporters', 'quantity_copies', 'biological_group')) PLATE_EXAMPLE = dict(plate_id='plate_1', plate_type='white_lowprofile_96', seal='optical_film', wells=[ dict(well='A1', sample_type='standard', sample_id='gapdh_std', dilution=1.0, template_volume_m3=2e-9, reaction_volume_m3=2e-8, assays=['hs_gapdh'], chemistry='sybr', quantity_copies=1.0e6)]) OPERATION = obj(dict(operation_id=TEXT, warnings=array(enum(['no_plate_on_the_block']), 0, 4)), optional=('warnings',)) RUN_WARNINGS = ['POWER_FAILURE'] EVENT = obj(dict(time_s=number('s'), kind=enum(['power', 'lid', 'plate', 'protocol', 'run', 'read', 'error', 'fault', 'data']), code=TEXT, message_zh=TEXT)) CURVE = obj(dict(well=TEXT, fluorophore=TEXT, channel=TEXT, cycles=array(INT, 0, 200), rfu=array(number('1'), 0, 200), baseline_subtracted=array(number('1'), 0, 200))) MELT = obj(dict(well=TEXT, fluorophore=TEXT, temperature_k=array(number('K'), 0, 2000), rfu=array(number('1'), 0, 2000), neg_derivative=array(number('1/K'), 0, 2000))) CQ_ROW = obj(dict(well=TEXT, fluorophore=TEXT, target=nullable(TEXT), sample_type=TEXT, cq=nullable(number('1')), end_rfu=number('1'))) PEAK = obj(dict(well=TEXT, fluorophore=TEXT, peaks_k=array(number('K'), 0, 8), heights=array(number('1/K'), 0, 8))) STD = obj(dict(target=TEXT, fluorophore=TEXT, slope=nullable(number('1')), intercept=nullable(number('1')), r2=nullable(number('1')), efficiency=nullable(number('1')), points=INT, unknowns=array(obj(dict(well=TEXT, cq=nullable(number('1')), quantity_copies=nullable(number('1')))), 0, NW))) GEX = obj(dict(sample=TEXT, target=TEXT, delta_cq=nullable(number('1')), delta_delta_cq=nullable(number('1')), relative_quantity=nullable(number('1')))) RUN_REC = obj(dict(run_id=TEXT, protocol=TEXT, plate_id=nullable(TEXT), status=TEXT, started_s=number('s'), finished_s=nullable(number('s')), reads=INT, cycles=INT, scan_mode=TEXT, warnings=array(enum(RUN_WARNINGS), 0, 50))) LEDGER_KEYS = ['electrical_energy_j', 'peltier_heat_pumped_j', 'lid_heater_energy_j', 'amplicon_copies_made', 'primer_consumed_mol', 'dntp_consumed_mol', 'probe_cleaved_mol', 'primer_dimer_copies_made', 'water_evaporated_m3', 'plate_reads', 'well_reads'] LEDGER = obj({k: number('J' if k.endswith('_j') else 'mol' if k.endswith('_mol') else 'm3' if k.endswith('_m3') else '1') for k in LEDGER_KEYS}) TRUTH_WELL = obj(dict(well=TEXT, occupied=BOOL, sample_temperature_k=number('K'), volume_m3=number('m3'), polymerase_active=number('1'), cycles_completed=INT, assays=array(obj(dict(assay=TEXT, copies=number('1'), primer_remaining=number('1'), probe_cleaved=number('1'), last_efficiency=nullable(number('1')), melt_tm_k=number('K'))), 0, MAX_ASSAYS), primer_dimer_copies=number('1'))) cap('plant.configure', PLANT, obj(dict(plant=obj(dict(room_k=number('K'), mains_voltage_v=number('V'), noise_seed=INT)))), PLANT_EXAMPLE, ['chassis'], '宿主声明实验室条件:室温(288–308 K)、供电电压与噪声种子(只在首次声明时生效)', 'evaluator', 'simulation') cap('power.set', obj(dict(enabled=BOOL)), obj(dict(enabled=BOOL)), dict(enabled=True), ['switch_power'], '开机/关机(等同按后面板电源开关到指定位置)') cap('power.press_switch', obj({}), obj(dict(enabled=BOOL)), {}, ['switch_power'], '按一下后面板电源开关(切换开/关)') cap('lid.open', obj({}), obj(dict(target_m=number('m'))), {}, ['lid', 'touch_screen'], '在触摸屏点Open Lid:电动盖退回后罩(约6 s);运行中不能开盖') cap('lid.close', obj({}), obj(dict(target_m=number('m'))), {}, ['lid', 'touch_screen'], '在触摸屏点Close Lid:电动盖关上并压住板(约6 s);遇阻时停止') cap('screen.tilt', obj(dict(angle_rad=number('rad', 12.0 * math.pi / 180, 55.0 * math.pi / 180))), obj(dict(angle_rad=number('rad'), tilt_from_reference_rad=number('rad'))), dict(angle_rad=30.0 * math.pi / 180), ['touch_screen'], '用手把触摸屏倾角调到12–55°(相对竖直)', 'agent', 'robot_skill') COPIES_MAP = dict(type='object', propertyNames=LIBID, additionalProperties=number('1/m3', 0.0, 1e21), maxProperties=MAX_ASSAYS) cap('sample.provide', obj(dict(sample_id=SID, kind=enum(['template', 'standard']), copies_per_m3=COPIES_MAP, inhibitor=number('1', 0.0, 1.0), declared_copies_per_m3=nullable(COPIES_MAP)), optional=('inhibitor', 'declared_copies_per_m3')), obj(dict(sample_id=TEXT)), dict(sample_id='gapdh_std', kind='standard', copies_per_m3={'hs_gapdh': 5.0e14}, declared_copies_per_m3={'hs_gapdh': 5.0e14}), ['sample_block'], '评测者准备一个核酸样品:每个检测的真实拷贝浓度(copies/m3,键为assay库ID)、抑制物强度;标准品可声明标称浓度', 'evaluator', 'simulation') cap('plate.prepare', obj(dict(plate_id=SID, plate_type=enum(list(PLATE_TYPES)), seal=enum(SEALS), wells=array(WELL_SPEC, 1, NW))), obj(dict(plate_id=TEXT, wells=INT, warnings=array(enum(['unsealed_plate_evaporation']), 0, 1)), optional=('warnings',)), PLATE_EXAMPLE, ['sample_block'], '在实验台上配一块96孔板:每孔的样品类型、样品与稀释倍数、模板体积、反应体积、检测(引物对,≤5个)、化学(SYBR/EvaGreen/探针)、' '探针报告染料、标准品拷贝数与生物学分组;封膜方式', 'agent', 'robot_skill') cap('plate.load', obj(dict(plate_id=SID)), obj(dict(plate_id=TEXT)), dict(plate_id='plate_1'), ['sample_block'], '把配好的板压入样品块(盖子须已退回)', 'agent', 'robot_skill') cap('plate.remove', obj({}), obj(dict(plate_id=TEXT)), {}, ['sample_block'], '从样品块取出板(盖子须已退回、不在运行中)', 'agent', 'robot_skill') cap('protocol.set', obj(dict(name=dict(type='string', minLength=1, maxLength=32), sample_volume_m3=number('m3', 0.0, 5e-8), lid_temperature_k=number('K', 303.15, 383.15), steps=array(STEP, 1, MAX_STEPS)), optional=('lid_temperature_k',)), obj(dict(name=TEXT, steps=INT, estimated_duration_s=number('s'), control_mode=enum(['calculated', 'block']))), PROTOCOL_EXAMPLE, ['touch_screen'], '新建/编辑协议:样品体积(0为块模式)、热盖温度(默认105 °C)、温度/梯度/GOTO(默认39次)/熔解步骤(保持时间、读板、升降温速率、每循环增量与延时、蜂鸣);返回的预计时长按全通道扫描计算') cap('run.start', obj(dict(scan_mode=enum(list(SCAN_S)))), OPERATION, dict(scan_mode='all_channels'), ['touch_screen', 'sample_block', 'lid'], '开始运行(盖子须关闭、已载入协议):热盖先升温,然后按协议控温、读板;异步操作') cap('run.pause', obj({}), obj(dict(state=TEXT)), {}, ['touch_screen'], '暂停运行(保持当前温度,计时暂停)') cap('run.resume', obj({}), obj(dict(state=TEXT)), {}, ['touch_screen'], '继续已暂停的运行') cap('run.skip_step', obj({}), obj(dict(step=INT)), {}, ['touch_screen'], '跳过当前步骤(GOTO循环内跳到下一步)') cap('data.amplification', obj(dict(run_id=nullable(TEXT), wells=nullable(array(WELL, 1, NW)), fluorophore=nullable(LIBID)), optional=('run_id', 'wells', 'fluorophore')), obj(dict(run_id=TEXT, curves=array(CURVE, 0, NW * MAX_ASSAYS), baseline_cycles=array(INT, 2, 2))), dict(wells=['A1']), ['touch_screen'], '读扩增曲线:每孔每染料每循环的RFU与基线扣除后的RFU(出厂染料校准做颜色补偿)', 'agent', 'query') cap('data.melt', obj(dict(run_id=nullable(TEXT), wells=nullable(array(WELL, 1, NW))), optional=('run_id', 'wells')), obj(dict(run_id=TEXT, curves=array(MELT, 0, NW * MAX_ASSAYS))), dict(wells=['A1']), ['touch_screen'], '读熔解曲线:温度、RFU与−dRFU/dT', 'agent', 'query') cap('analysis.cq', obj(dict(run_id=nullable(TEXT), threshold_rfu=nullable(number('1', 0.0, 1e6)), baseline=nullable(array(integer(1, 199), 2, 2))), optional=('run_id', 'threshold_rfu', 'baseline')), obj(dict(run_id=TEXT, thresholds=array(obj(dict(fluorophore=TEXT, threshold_rfu=number('1'), auto=BOOL)), 0, 128), results=array(CQ_ROW, 0, NW * MAX_ASSAYS))), {}, ['touch_screen'], '计算Cq:基线扣除(自动或给定基线循环)、阈值(自动=基线标准差的10倍,或给定)、分数Cq', 'agent', 'query') cap('analysis.standard_curve', obj(dict(run_id=nullable(TEXT), threshold_rfu=nullable(number('1', 0.0, 1e6))), optional=('run_id', 'threshold_rfu')), obj(dict(run_id=TEXT, curves=array(STD, 0, NW * MAX_ASSAYS))), {}, ['touch_screen'], '标准曲线:Cq对log10拷贝数回归(斜率、截距、R2、效率),给出未知样品拷贝数', 'agent', 'query') cap('analysis.melt_peaks', obj(dict(run_id=nullable(TEXT), min_height_fraction=nullable(number('1', 0.0, 1.0))), optional=('run_id', 'min_height_fraction')), obj(dict(run_id=TEXT, peaks=array(PEAK, 0, NW * MAX_ASSAYS))), {}, ['touch_screen'], '熔解峰:−dRFU/dT峰的温度与高度(峰高下限为最高峰的比例)', 'agent', 'query') cap('analysis.gene_expression', obj(dict(run_id=nullable(TEXT), reference_targets=array(LIBID, 1, 4), control_group=SID, use_efficiency=BOOL), optional=('run_id', 'use_efficiency')), obj(dict(run_id=TEXT, results=array(GEX, 0, 400))), dict(reference_targets=['hs_gapdh'], control_group='ctrl'), ['touch_screen'], '基因表达:按生物学分组平均Cq,ΔCq(对参照基因)与ΔΔCq(对对照组),相对表达量(效率校正可选)', 'agent', 'query') cap('data.export', obj(dict(run_id=nullable(TEXT), kind=enum(['amplification_csv', 'cq_csv', 'melt_csv', 'rdml'])), optional=('run_id',)), obj(dict(file=TEXT, bytes=INT, rows=INT)), dict(kind='cq_csv'), ['usb_front_port', 'touch_screen'], '把扩增、Cq、熔解数据或RDML导出到U盘(写文件并记事件,不改状态槽)', 'agent', 'device_command') cap('runs.list', obj({}), obj(dict(runs=array(RUN_REC, 0, MAX_RUNS))), {}, ['touch_screen'], '列出运行记录', 'agent', 'query') cap('events.read', obj(dict(since_s=number('s', 0.0))), obj(dict(events=array(EVENT, 0, MAX_EVENTS), dropped=INT)), dict(since_s=0.0), ['touch_screen'], '读事件日志', 'agent', 'query') cap('provenance.read', obj({}), obj(dict(libraries=array(obj(dict(name=TEXT, file=TEXT, entries=INT)), 0, 8), channels=array(obj(dict(channel=TEXT, excitation_m=array(number('m'), 2, 2), detection_m=array(number('m'), 2, 2), dye=TEXT, evidence=TEXT)), 0, 8))), {}, ['touch_screen'], '读模板库与通道波段来源', 'agent', 'query') cap('well.inspect', obj(dict(well=WELL)), obj(dict(truth=TRUTH_WELL)), dict(well='A1'), ['sample_block'], '评测者读某孔真值:样品温度、体积、酶活化、每个检测的拷贝数、' '剩余引物、切割探针、上一循环效率、引物二聚体', 'evaluator', 'query') cap('ledger.read', obj({}), obj(dict(ledger=LEDGER)), {}, ['chassis'], '读守恒账目(电能、Peltier搬运热、热盖能量、扩增子、引物/dNTP/探针消耗、蒸发、读板次数)', 'evaluator', 'query') cap('fault.inject', obj(dict(fault=enum(FAULTS), active=BOOL)), obj(dict(faults=array(TEXT, 0, 16))), dict(fault='lid_obstructed', active=True), ['chassis', 'lid'], '评测者故障注入:断电、盖子遇阻、某通道LED失效、风扇故障(降温变慢)、块温传感器漂移', 'evaluator', 'simulation') cap('sim.step', obj(dict(dt_s=number('s', 0.0, 7 * 86400.0))), obj(dict(time_s=number('s'))), dict(dt_s=60.0), ['chassis'], '推进宿主时钟(0.1 s物理网格)', 'evaluator', 'simulation') UNSUPPORTED = { 'user.login': '用户账户与权限(Admin/Guest、密码)未建模', 'brio.connect': 'BR.io云平台、邮件与网络文件夹未建模', 'precision_melt.analyze': 'Precision Melt Analysis(另售软件的高分辨熔解分型)未建模', 'allelic_discrimination.analyze': '等位基因分型(终点荧光聚类)未建模', 'dye.calibrate': '新染料校准(用户校准板)未建模,只用出厂校准的染料', 'firmware.update': '固件/软件升级未建模', } for k, v in UNSUPPORTED.items(): cap(k, obj({}), obj({}), {}, ['touch_screen'], v) FREEOBJ = {'type': 'object'} # ---------------------------------------------------------------- touch-screen software: users, files, run setup, settings, logs, diagnostics # (Instrument Guide 10000119983 chapters 2-6 and appendix C; the terminal layer under the front-panel spec panel_ui.json) SOFTWARE_VERSION = '1.0.710.726' # Home screen figure (guide p.52) SERIAL_NUMBER = 'OPUS00001' # figure example (guide p.52); the instrument name starts as the serial number (p.59) TIME_ZONES = {'(UTC-11:00) Coordinated Universal Time-11': -11, '(UTC-08:00) Pacific Time (US & Canada)': -8, '(UTC-05:00) Eastern Time (US & Canada)': -5, '(UTC) Coordinated Universal Time': 0, '(UTC+01:00) Amsterdam, Berlin, Rome, Stockholm': 1, '(UTC+08:00) Beijing, Chongqing, Hong Kong': 8, '(UTC+09:00) Osaka, Sapporo, Tokyo': 9} DEFAULT_TIME_ZONE = '(UTC-11:00) Coordinated Universal Time-11' # factory time zone (guide p.60); the list is a subset of the Windows zones (assumption) CLOCK_START = '2026-01-01T00:00:00' # local device time at simulation time 0 (assumption) SAVER_IDLE_S = [60, 300, 600, 900, 1800, 3600] # screen-saver idle times offered (assumption: the guide names the setting only) BUILTIN_USERS = ('Admin', 'Guest', 'Service') # Login list of a new system (guide p.42 figure); Admin has no password at first (p.45) NAME_MAX, RUN_NAME_MAX = 32, 64 # protocol / file / folder names 32 characters, run file names 64 (guide p.88, p.113, p.128) PASSWORD_LEN = (4, 50) # passwords 4-50 characters, case-sensitive (guide p.44) MY_FILES_MAX = 900 # CFX Opus 96: 900 files in My Files, 100 in Run Reports (guide p.135) DISK_BYTES, FILE_BYTES = 32.0e9, 60.0e3 # internal storage and the size of one file shown by About (assumption) USB_ROOT, PUBLIC, SAMPLES = 'USB', 'Public', 'Public/Bio-Rad qPCR' LOG_FILES = ['SystemMessageLog.txt', 'SystemUsageLog.txt', 'DebugLog.txt', 'OSLog.txt', 'FirmwareUpdateLog.txt', 'GUILog.txt', 'WCFLog.txt'] # guide p.158 _K = 273.15 SAMPLE_PROTOCOLS = { # read-only sample qPCR protocols in Public > Bio-Rad qPCR (guide p.106; names and steps: assumption, 'CFX_2stepAmp+Melt': dict(name='CFX_2stepAmp+Melt', sample_volume_m3=2e-8, lid_temperature_k=LID_DEFAULT_K, steps=[ # the usual Bio-Rad defaults) dict(kind='temperature', temperature_k=95 + _K, hold_s=180.0), dict(kind='temperature', temperature_k=95 + _K, hold_s=10.0), dict(kind='temperature', temperature_k=60 + _K, hold_s=30.0, plate_read=True), dict(kind='goto', goto_step=2, cycles=39), dict(kind='melt', start_k=65 + _K, end_k=95 + _K, melt_increment_k=0.5, hold_s=5.0)]), 'CFX_3stepAmp+Melt': dict(name='CFX_3stepAmp+Melt', sample_volume_m3=2e-8, lid_temperature_k=LID_DEFAULT_K, steps=[ dict(kind='temperature', temperature_k=95 + _K, hold_s=180.0), dict(kind='temperature', temperature_k=95 + _K, hold_s=10.0), dict(kind='temperature', temperature_k=55 + _K, hold_s=30.0), dict(kind='temperature', temperature_k=72 + _K, hold_s=30.0, plate_read=True), dict(kind='goto', goto_step=2, cycles=39), dict(kind='melt', start_k=65 + _K, end_k=95 + _K, melt_increment_k=0.5, hold_s=5.0)]), 'CFX_2stepAmp': dict(name='CFX_2stepAmp', sample_volume_m3=2e-8, lid_temperature_k=LID_DEFAULT_K, steps=[ dict(kind='temperature', temperature_k=95 + _K, hold_s=180.0), dict(kind='temperature', temperature_k=95 + _K, hold_s=10.0), dict(kind='temperature', temperature_k=60 + _K, hold_s=30.0, plate_read=True), dict(kind='goto', goto_step=2, cycles=39)])} DIAGNOSTIC_TESTS = [('block_thermal', 'Block heating / cooling', 'fan_failure'), ('block_sensor', 'Block temperature sensor', 'block_sensor_drift'), ('lid_motor', 'Lid motor', 'lid_obstructed'), ('heated_lid', 'Heated lid', None)] + \ [(f'optics_ch{c}', f'Optics channel {c} LED', f'led_failure_channel_{c}') for c in range(1, 6)] + [('touch_screen', 'Touch screen', None)] USER = dict(type='string', minLength=1, maxLength=NAME_MAX) PWD = dict(type='string', minLength=0, maxLength=64) PATH = dict(type='string', minLength=1, maxLength=400) FNAME = dict(type='string', minLength=1, maxLength=NAME_MAX) DIAG = obj(dict(test=TEXT, name=TEXT, result=enum(['Pass', 'Fail']))) del UNSUPPORTED['user.login'], CAPS['user.login'] # user accounts are implemented in the terminal layer (1.1.0) cap('user.login', obj(dict(user=USER, password=nullable(PWD), new_password=nullable(PWD)), optional=('password', 'new_password')), obj(dict(user=TEXT)), dict(user='Guest'), ['touch_screen'], '在登录列表点用户并输入密码登录(Guest无密码;未设密码的用户不弹键盘;管理员开启密码要求后无密码的用户须在登录时设新密码new_password;Service为维修账户,' '其密码只给维修人员);登录后Home显示用户名') cap('user.logout', obj({}), obj(dict(user=nullable(TEXT))), {}, ['touch_screen'], 'Home屏点Logout:注销当前用户,回到登录列表') cap('user.create', obj(dict(name=USER, password=nullable(PWD)), optional=('password',)), obj(dict(user=TEXT)), dict(name='Analyst', password='pcr1234'), ['touch_screen'], '登录列表点Create User:输入用户名,再输入并确认密码(4–50字符,区分大小写)或Skip Password(开启密码要求时不能跳过);建立个人文件夹My Files并登录') cap('user.set_password', obj(dict(new_password=PWD, current_password=nullable(PWD)), optional=('current_password',)), obj(dict(user=TEXT)), dict(new_password='pcr5678', current_password='pcr1234'), ['touch_screen'], 'Tools > User Profile > Change Password:已有密码时先输入当前密码;Guest不能设密码') cap('user.set_email', obj(dict(email=dict(type='string', maxLength=120))), obj(dict(user=TEXT, email=nullable(TEXT))), dict(email='lab@example.org'), ['touch_screen'], 'Tools > User Profile > Email Notification:设置或清除(空字符串)运行结束通知的邮箱地址') cap('user.reset_password', obj(dict(user=USER, new_password=PWD)), obj(dict(user=TEXT)), dict(user='Analyst', new_password='pcr0000'), ['touch_screen'], 'Admin:Tools > User Management选中用户 > Reset Password(输入并确认新密码;内置账户不能在此重置)') cap('user.remove', obj(dict(user=USER)), obj(dict(user=TEXT, files_deleted=INT)), dict(user='Analyst'), ['touch_screen'], 'Admin:Tools > User Management选中用户 > Remove User(永久删除该用户及其协议与运行文件;Admin、Guest、Service不能删除)') cap('system.configure', obj(dict(name=dict(type='string', minLength=1, maxLength=NAME_MAX), time_zone=enum(list(TIME_ZONES)), date=dict(type='string', pattern='^[0-9]{4}-[0-9]{2}-[0-9]{2}$'), time=dict(type='string', pattern='^[0-9]{2}:[0-9]{2}(:[0-9]{2})?$'), password_required=BOOL, screen_saver=BOOL, screen_saver_idle_s={'type': 'integer', 'x-unit': 's', 'enum': list(SAVER_IDLE_S)}), optional=('name', 'time_zone', 'date', 'time', 'password_required', 'screen_saver', 'screen_saver_idle_s')), obj(dict(settings=FREEOBJ)), dict(name='qPCR-1', password_required=True), ['touch_screen'], 'Admin:Tools > System Settings > Apply:仪器名、时区(立即换算日期时间)、日期与时间(24 h)、密码要求、屏保与空闲时间') cap('system.shutdown', obj({}), obj(dict(shutdown=BOOL)), {}, ['touch_screen', 'switch_power'], '登录界面点Shut Down:软关机(须已注销且没有运行);之后屏幕与样品块、热盖关闭,再按后面板电源开关断电') cap('email.configure', obj(dict(server=dict(type='string', minLength=1, maxLength=120), port=integer(1, 65535), use_ssl=BOOL, authentication=BOOL, account=dict(type='string', maxLength=120), account_password=PWD), optional=('account', 'account_password')), obj(dict(email=FREEOBJ)), dict(server='smtp.example.org', port=587, use_ssl=True, authentication=False), ['touch_screen'], 'Admin:Tools > Email Settings > Save:发信服务器、端口、SSL、是否认证及认证账户与密码(出厂为Gmail设置)') cap('files.save_protocol', obj(dict(folder=PATH, name=FNAME, protocol=CAPS['protocol.set']['input_schema'], from_path=nullable(PATH)), optional=('from_path',)), obj(dict(path=TEXT, overwritten=BOOL)), dict(folder='Public', name='SYBR_2step_melt', protocol=PROTOCOL_EXAMPLE), ['touch_screen', 'usb_front_port'], '协议编辑器Save > Save As:把协议以给定名称存到文件夹(My Files仅本人可见、Public共享、USB;同名同位置覆盖;Bio-Rad qPCR只读,示例协议须改名才能保存)') cap('files.create_folder', obj(dict(parent=PATH, name=FNAME)), obj(dict(path=TEXT)), dict(parent='Public', name='Assays'), ['touch_screen'], 'File Browser或Select Location点Create Folder:在当前位置新建文件夹(同一位置不能重名)') cap('files.copy', obj(dict(path=PATH, folder=PATH, overwrite=BOOL), optional=('overwrite',)), obj(dict(path=TEXT, overwritten=BOOL)), dict(path='Public/Bio-Rad qPCR/CFX_2stepAmp+Melt', folder='USB'), ['touch_screen', 'usb_front_port'], 'File Browser > Options > Copy:把文件或文件夹(含内容)复制到所选位置(同名文件经确认可覆盖;同名文件夹不能覆盖)') cap('files.delete', obj(dict(path=PATH)), obj(dict(deleted=INT)), dict(path='Public/Assays'), ['touch_screen'], 'File Browser > Options > Delete:删除文件或文件夹及其内容(只读的示例文件夹不能删除)') cap('files.rename', obj(dict(path=PATH, name=FNAME)), obj(dict(path=TEXT)), dict(path='Public/SYBR_2step_melt', name='SYBR_melt_v2'), ['touch_screen'], 'File Browser > Options > Rename:重命名协议文件(运行文件与只读示例协议不能重命名)') cap('files.open', obj(dict(path=PATH)), obj(dict(name=TEXT, steps=INT, estimated_duration_s=number('s'), control_mode=enum(['calculated', 'block']), path=TEXT)), dict(path='Public/Bio-Rad qPCR/CFX_2stepAmp+Melt'), ['touch_screen'], 'File Browser选中协议或运行文件后点Next/Edit:载入其协议作为当前协议(同protocol.set;运行文件取其中的协议)') cap('run.configure', obj(dict(folder=nullable(PATH), run_file_name=dict(type='string', maxLength=RUN_NAME_MAX), plate_id=dict(type='string', maxLength=64), notify_beep=BOOL, notify_email=BOOL), optional=('folder', 'run_file_name', 'plate_id', 'notify_beep', 'notify_email')), obj(dict(setup=FREEOBJ)), dict(folder='Public', run_file_name='', plate_id='PL-0001', notify_beep=True, notify_email=False), ['touch_screen'], 'Run Setup:下一次运行的板ID(键盘或条码枪)、运行文件名(默认<协议>_<日期>_<时间>_<序列号>_<用户>,≤64字符)、保存位置(默认协议所在文件夹或My Files)、' '结束提示音与邮件通知;运行结束时按此保存运行文件') cap('run.stop', obj({}), obj(dict(state=TEXT)), {}, ['touch_screen'], 'Run Status > Stop Run:立即停止运行(样品块停止变温;已采集的读板数据保留并保存运行文件)') cap('runs.export', obj(dict(run_id=nullable(TEXT)), optional=('run_id',)), obj(dict(files=array(TEXT, 0, MAX_RUNS))), dict(run_id=None), ['touch_screen', 'usb_front_port'], 'Tools > Run Reports > Export / Export All:把一个或全部运行报告导出到前面板U盘') cap('runs.recover', obj(dict(run_id=TEXT)), obj(dict(file=TEXT)), dict(run_id='R001'), ['touch_screen', 'usb_front_port'], 'Admin:Run Reports选中运行 > Recover Data:把该运行的.zpcr文件存到U盘(一次一个)') cap('runs.delete', obj(dict(run_ids=array(TEXT, 1, MAX_RUNS))), obj(dict(deleted=INT)), dict(run_ids=['R001']), ['touch_screen'], 'Admin:Run Reports删除较旧或无效的运行报告(进行中的运行不能删除)') cap('logs.export', obj({}), obj(dict(files=array(TEXT, 0, 16))), {}, ['touch_screen', 'usb_front_port'], 'Tools > System Logs > Export Logs:在U盘Exports文件夹写入消息、使用、调试、OS、固件更新、GUI与WCF日志') cap('logs.clear', obj({}), obj(dict(cleared_s=number('s'))), {}, ['touch_screen'], 'Admin:Tools > System Logs清除全部消息与使用日志(事件接口events.read不受影响)') cap('diagnostics.run', obj({}), obj(dict(results=array(DIAG, 0, 16))), {}, ['touch_screen', 'sample_block', 'lid'], 'Admin:Tools > Diagnostic Test:自检样品块加热/冷却、块温传感器、盖子电机、热盖、5个光学通道LED与触摸屏(不在运行中),给出Pass/Fail') TERMINAL_CAPS = ['user.login', 'user.logout', 'user.create', 'user.set_password', 'user.set_email', 'user.reset_password', 'user.remove', 'system.configure', 'system.shutdown', 'email.configure', 'files.save_protocol', 'files.create_folder', 'files.copy', 'files.delete', 'files.rename', 'files.open', 'run.configure', 'run.stop', 'runs.export', 'runs.recover', 'runs.delete', 'logs.export', 'logs.clear', 'diagnostics.run'] def _panel_engine(): try: from . import _panel_ui as engine # imported as asset_runtime.biorad_cfxopus (tests, Matterix bridge) return engine except ImportError: # loaded from its file path import importlib.util import sys if '_chemsim_panel_ui' not in sys.modules: spec = importlib.util.spec_from_file_location('_chemsim_panel_ui', Path(__file__).with_name('_panel_ui.py')) sys.modules['_chemsim_panel_ui'] = importlib.util.module_from_spec(spec) spec.loader.exec_module(sys.modules['_chemsim_panel_ui']) return sys.modules['_chemsim_panel_ui'] _panel_ui = _panel_engine() if os.environ.get('CFX_PANEL_BUILD'): # the spec builder imports this module before the spec exists PANEL_SPEC = dict(spec_version=_panel_ui.SPEC_VERSION, inputs={}, displays={'screen': dict(kind='touch_tft', size=[1024, 600])}, screens={'off': dict(style='static')}) else: PANEL_SPEC = _panel_ui.load_spec(ASSET_DIR / 'panel_ui.json', capabilities=set(CAPS)) PANEL_CAPS = _panel_ui.capability_definitions(PANEL_SPEC) # panel.touch / switch / capture / frame (kept out of CAPS: ALL_CAPS = dict(CAPS, **PANEL_CAPS) # CAPS stays the instrument's own command set) PANEL_GESTURES = [k for k in PANEL_CAPS if k not in ('panel.capture', 'panel.frame')] # ---------------------------------------------------------------- front panel hooks: the protocol editor's working copy and the run / file views # (small instrument hooks of the panel engine; the editor keeps the protocol being edited in panel variables and hands it to protocol.set / # files.save_protocol, the same commands a direct call uses) EDITOR_COLUMNS = 4 # steps side by side on the protocol editor (guide p.88 figure) NEW_PROTOCOL = dict(name='New Protocol', sample_volume_m3=30e-9, lid_temperature_k=LID_DEFAULT_K, steps=[ # a new protocol (guide p.88 figure) dict(kind='temperature', temperature_k=95 + _K, hold_s=180.0), dict(kind='temperature', temperature_k=95 + _K, hold_s=10.0), dict(kind='temperature', temperature_k=55 + _K, hold_s=30.0, plate_read=True), dict(kind='goto', goto_step=2, cycles=GOTO_DEFAULT_CYCLES)]) NEW_STEP = {'temperature': dict(kind='temperature', temp_c=50.0, hold=30.0), 'gradient': dict(kind='gradient', lower_c=55.0, upper_c=65.0, hold=30.0), 'melt': dict(kind='melt', start_c=65.0, end_c=95.0, minc=0.5, hold=5.0), 'goto': dict(kind='goto', goto=1, cycles=GOTO_DEFAULT_CYCLES)} # a new step: 50 C for 0:30 (guide p.90, p.108); gradient 55-65 C, melt 65-95 C by 0.5 C / 5 s and GOTO step 1 x 39 are assumptions def _hms(s): if s is None: return 'inf' s = int(round(s)) return f'{s // 3600}:{s % 3600 // 60:02d}:{s % 60:02d}' if s >= 3600 else f'{s // 60}:{s % 60:02d}' def _hms_long(s): s = int(round(s)) return f'{s // 3600:02d}:{s % 3600 // 60:02d}:{s % 60:02d}' def _parse_hms(text): """A hold time typed as HH:MM:SS, MM:SS or seconds, or the infinite-hold key (None); 1 s to 17:59:59 (guide p.89).""" t = str(text).strip().lower() if t == 'inf': return None parts = t.split(':') if not 1 <= len(parts) <= 3 or not all(p.isdigit() for p in parts): raise ValueError(text) v = 0 for p in parts: v = v * 60 + int(p) if not 1 <= v <= 64799: raise ValueError(text) return float(v) def _step_line(s): """One step as text (Run Status list, file details).""" k = s['kind'] if k == 'temperature': return f'{s["temperature_k"] - _K:.1f} °C {_hms(s["hold_s"])}' + (' Read' if s.get('plate_read') else '') if k == 'gradient': return f'Gradient {s["lower_k"] - _K:.1f}-{s["upper_k"] - _K:.1f} °C {_hms(s["hold_s"])}' + (' Read' if s.get('plate_read') else '') if k == 'melt': return f'Melt {s["start_k"] - _K:.1f}-{s["end_k"] - _K:.1f} °C +{s["melt_increment_k"]:.1f} °C {_hms(s["hold_s"])}' return f'GOTO step {s["goto_step"]}, {s["cycles"]} more times' def _ui_step(s): k = s['kind'] c = lambda T: round(T - _K, 1) # noqa: E731 if k == 'temperature': return dict(kind=k, temp_c=c(s['temperature_k']), hold=s.get('hold_s'), read=bool(s.get('plate_read')), ramp=s.get('ramp_rate_k_s'), inc=float(s.get('increment_k') or 0.0), ext=float(s.get('extend_s') or 0.0), beep=bool(s.get('beep'))) if k == 'gradient': return dict(kind=k, lower_c=c(s['lower_k']), upper_c=c(s['upper_k']), hold=s.get('hold_s'), read=bool(s.get('plate_read')), ext=float(s.get('extend_s') or 0.0)) if k == 'melt': return dict(kind=k, start_c=c(s['start_k']), end_c=c(s['end_k']), minc=float(s['melt_increment_k']), hold=s.get('hold_s')) return dict(kind=k, goto=int(s['goto_step']), cycles=int(s['cycles'])) def _si_step(u): k = u['kind'] K = lambda c: round(c + _K, 2) # noqa: E731 if k == 'temperature': return dict(kind=k, temperature_k=K(u['temp_c']), hold_s=u['hold'], plate_read=u.get('read', False), ramp_rate_k_s=u.get('ramp'), increment_k=u.get('inc', 0.0), extend_s=u.get('ext', 0.0), beep=u.get('beep', False)) if k == 'gradient': return dict(kind=k, lower_k=K(u['lower_c']), upper_k=K(u['upper_c']), hold_s=u['hold'], plate_read=u.get('read', False), extend_s=u.get('ext', 0.0)) if k == 'melt': return dict(kind=k, start_k=K(u['start_c']), end_k=K(u['end_c']), melt_increment_k=u['minc'], hold_s=u['hold']) return dict(kind=k, goto_step=u['goto'], cycles=u['cycles']) def _texts(steps): """Number the editor steps and write the texts of their buttons (temperature / time, GOTO step / cycles) and option marks.""" for i, u in enumerate(steps): k = u['kind'] u['n'], u['label'] = i, str(i + 1) if k == 'temperature': top, bottom = f'{u["temp_c"]:.1f} °C', _hms(u['hold']) elif k == 'gradient': top, bottom = f'{u["lower_c"]:.1f}-{u["upper_c"]:.1f} °C', _hms(u['hold']) elif k == 'melt': top, bottom = f'{u["start_c"]:.1f}-{u["end_c"]:.1f} °C', f'+{u["minc"]:.1f} °C {_hms(u["hold"])}' else: top, bottom = f'Step {u["goto"]}', f'{u["cycles"]} X' marks = [m for m, on in (('Read', u.get('read') or k == 'melt'), ('Beep', u.get('beep')), ('Ramp', u.get('ramp') is not None), ('Inc', bool(u.get('inc'))), ('Ext', bool(u.get('ext')))) if on] u.update(top=top, bottom=bottom, marks=' '.join(marks), kind_text={'temperature': 'Temperature', 'gradient': 'Gradient', 'melt': 'Melt Curve', 'goto': 'GOTO'}[k]) return steps def _say(panel, text): """The device's message box (dialog 'msg' of the spec).""" panel.ui['vars']['msg'] = text panel._dialog_open(dict(dialog='msg'), {}) def _hk_editor_new(panel, ctx, a): v, st = panel.ui['vars'], panel._state() v['head'] = dict(title='New Protocol', name=NEW_PROTOCOL['name'], volume_ul=30.0, lid_c=round(LID_DEFAULT_K - _K, 1), src=None, folder=st.get('host.my_files') or PUBLIC) v['steps'] = _texts([_ui_step(s) for s in NEW_PROTOCOL['steps']]) v['sel'], v['scroll'] = 0, 0 return True def _hk_editor_load(panel, ctx, a): """Edit Protocol: the selected file of the File Browser (a run file gives its protocol, guide p.117) or the protocol loaded for the run.""" v, st = panel.ui['vars'], panel._state() if a.get('from') == 'file': e = next((x for x in st['files.entries'] if x['path'] == v.get('fb_sel')), None) if e is None or e['protocol'] is None: return False p, src = e['protocol'], e['path'] parent = next((x for x in st['files.entries'] if x['path'] == e['parent']), None) folder = e['parent'] if (parent is not None and not parent['readonly'] and e['kind'] == 'protocol') else (st.get('host.my_files') or PUBLIC) else: p, src = st['protocol.definition'], st['protocol.path'] if p is None: return False folder = st.get('host.my_files') or PUBLIC v['head'] = dict(title='Edit Protocol', name=p['name'], volume_ul=round(p['sample_volume_m3'] * 1e9, 1), lid_c=round(p['lid_temperature_k'] - _K, 1), src=src, folder=folder) v['steps'] = _texts([_ui_step(s) for s in p['steps']]) v['sel'], v['scroll'] = 0, 0 return True def _hk_select(panel, ctx, a): v = panel.ui['vars'] i = v['scroll'] + int(a['col']) if i >= len(v['steps']): return False v['sel'] = i return True def _hk_scroll(panel, ctx, a): v = panel.ui['vars'] v['scroll'] = min(max(v['scroll'] + int(a['n']), 0), max(0, len(v['steps']) - EDITOR_COLUMNS)) return True def _show_sel(v): if v['sel'] < v['scroll']: v['scroll'] = v['sel'] elif v['sel'] >= v['scroll'] + EDITOR_COLUMNS: v['scroll'] = v['sel'] - EDITOR_COLUMNS + 1 def _hk_insert(panel, ctx, a): """Insert Step (guide p.89, p.107): a new step to the right of the selected one; Plate Read adds a read to the selected step instead. GOTO targets behind the insertion point move with their steps (assumption).""" v = panel.ui['vars'] steps, kind = v['steps'], a['kind'] if kind == 'plate_read': s = steps[v['sel']] if s['kind'] not in ('temperature', 'gradient'): _say(panel, 'A plate read can be added to temperature\nand gradient steps only.') return False s['read'] = True _texts(steps) return True if len(steps) >= MAX_STEPS: _say(panel, f'A protocol has at most {MAX_STEPS} steps.') return False i = v['sel'] + 1 for s in steps: if s['kind'] == 'goto' and s['goto'] > i: s['goto'] += 1 steps.insert(i, copy.deepcopy(NEW_STEP[kind]) if kind != 'temperature' else dict(NEW_STEP[kind], read=False, ramp=None, inc=0.0, ext=0.0, beep=False)) if steps[i]['kind'] == 'gradient': steps[i].update(read=False, ext=0.0) _texts(steps) v['sel'] = i _show_sel(v) return True def _hk_remove(panel, ctx, a): v = panel.ui['vars'] steps = v['steps'] if len(steps) <= 1: _say(panel, 'A protocol needs at least one step.') return False i = v['sel'] del steps[i] for s in steps: if s['kind'] == 'goto' and s['goto'] > i + 1: s['goto'] -= 1 _texts(steps) v['sel'] = min(i, len(steps) - 1) v['scroll'] = min(v['scroll'], max(0, len(steps) - EDITOR_COLUMNS)) _show_sel(v) return True STEP_FIELDS = ('kind', 'temp_c', 'hold', 'gradient', 'lower_c', 'upper_c', 'ramp', 'inc', 'ext', 'beep', 'read', 'goto', 'cycles', 'start_c', 'end_c', 'minc') def step_form_values(u): """The Step Options form of an editor step (the time as typed text).""" return dict(kind=u['kind'], temp_c=u.get('temp_c', round((u.get('lower_c', 50.0) + u.get('upper_c', 50.0)) / 2, 1)), hold=_hms(u.get('hold')) if 'hold' in u else '', gradient=u['kind'] == 'gradient', lower_c=u.get('lower_c', max(30.0, u.get('temp_c', 55.0) - 5.0)), upper_c=u.get('upper_c', min(100.0, max(30.0, u.get('temp_c', 55.0) - 5.0) + 10.0)), ramp=u.get('ramp'), inc=u.get('inc', 0.0), ext=u.get('ext', 0.0), beep=bool(u.get('beep')), read=bool(u.get('read')), goto=u.get('goto', 1), cycles=u.get('cycles', GOTO_DEFAULT_CYCLES), start_c=u.get('start_c', 65.0), end_c=u.get('end_c', 95.0), minc=u.get('minc', 0.5)) def _hk_step_open(panel, ctx, a): v = panel.ui['vars'] panel._form_open(dict(form='f_step', set={k: {'const': x} for k, x in step_form_values(v['steps'][v['sel']]).items()}), {}) return True def _refuse(panel, b, text): """A refused Step Options value: the message, and the form shows the step unchanged.""" v = panel.ui['vars'] b.update(step_form_values(v['steps'][v['sel']])) _say(panel, text) return False def _hk_step_apply(panel, ctx, a): """A Step Options value (or a value tapped on the step) goes into the selected step: Gradient ticked turns a temperature step into a gradient step (lower / upper around it, assumption) and back (the middle temperature); the gradient span must stay 1-24 C (guide p.86).""" v = panel.ui['vars'] f = panel.ui['forms'].get('f_step') if f is None: return False b = f['buffer'] u = dict(v['steps'][v['sel']]) try: hold = _parse_hms(b['hold']) if u['kind'] != 'goto' else None except ValueError: return _refuse(panel, b, 'Enter a time between 0:01 and 17:59:59 (or Inf).') k = u['kind'] newk = ('gradient' if b['gradient'] else 'temperature') if k in ('temperature', 'gradient') else k if newk == 'temperature': temp = float(b['temp_c']) if k == 'temperature' else round((u['lower_c'] + u['upper_c']) / 2, 1) if hold is None and v['sel'] != len(v['steps']) - 1: return _refuse(panel, b, 'An infinite hold is allowed in the last step only.') u = dict(kind=newk, temp_c=temp, hold=hold, read=bool(b['read']), ramp=b['ramp'], inc=float(b['inc']), ext=float(b['ext']), beep=bool(b['beep'])) elif newk == 'gradient': if k == 'temperature': # the box was just ticked: a 10 C range around the step temperature lo = round(max(30.0, min(90.0, float(b['temp_c']) - 5.0)), 1) hi = round(lo + 10.0, 1) else: lo, hi = float(b['lower_c']), float(b['upper_c']) if not (30.0 <= lo <= 99.0 and hi <= 100.0 and 1.0 <= hi - lo <= 24.0) or hold is None: return _refuse(panel, b, 'Gradient: lower 30.0-99.0 °C, upper up to\n100.0 °C, within 24 °C of the lower value.') u = dict(kind=newk, lower_c=lo, upper_c=hi, hold=hold, read=bool(b['read']), ext=float(b['ext'])) elif newk == 'melt': if hold is None or float(b['end_c']) - float(b['start_c']) < max(0.5, float(b['minc'])): return _refuse(panel, b, 'Melt curve: the end must be above the start\nby at least one increment.') u = dict(kind=newk, start_c=float(b['start_c']), end_c=float(b['end_c']), minc=float(b['minc']), hold=hold) else: u = dict(kind=newk, goto=int(b['goto']), cycles=int(b['cycles'])) v['steps'][v['sel']] = u _texts(v['steps']) for key, x in step_form_values(u).items(): # the form shows the step as it is now (e.g. the gradient range) b[key] = x return True def _hk_head_apply(panel, ctx, a): f = panel.ui['forms'].get('f_head') if f is None: return False h = panel.ui['vars']['head'] h.update(name=f['buffer']['name'], volume_ul=float(f['buffer']['volume_ul']), lid_c=float(f['buffer']['lid_c'])) return True def _hk_saved(panel, ctx, a): """After Save As: the editor shows the saved name; Save and the run file default to that folder.""" v = panel.ui['vars'] b = (panel.ui['forms'].get('f_save') or {}).get('buffer') or ctx.get('buffer') or {} v['head'].update(name=b.get('name', v['head']['name']), folder=b.get('folder', v['head']['folder']), src=f'{b.get("folder")}/{b.get("name")}') return True def _src_protocol(panel, ctx, s): v = panel.ui['vars'] h = v.get('head') or {} return dict(name=h.get('name') or NEW_PROTOCOL['name'], sample_volume_m3=round(round(float(h.get('volume_ul', 0.0)), 1) * 1e-9, 15), lid_temperature_k=round(float(h.get('lid_c', 105.0)) + _K, 2), steps=[_si_step(u) for u in v.get('steps') or []]) def _src_exists(panel, ctx, s): b = (panel.ui['forms'].get(s.get('form', 'f_save')) or {}).get('buffer') or {} return f'{b.get("folder")}/{b.get("name")}' in {e['path'] for e in panel._state()['files.entries']} def _src_run_name(panel, ctx, s): """Default run file name __