import os import sys import glob from pathlib import Path from configparser import ConfigParser from typing import List, Optional, Union import json import csv import squid.logging from enum import Enum, IntEnum, auto log = squid.logging.get_logger(__name__) def conf_attribute_reader(string_value): """ :brief: standardized way for reading config entries that are strings, in priority order JSON (with comments stripped if needed) -> None -> bool -> int -> float -> string Inline comments (# ...) are stripped, but # inside valid JSON is preserved. REMEMBER TO ENCLOSE PROPERTY NAMES IN LISTS/DICTS IN DOUBLE QUOTES """ actualvalue = str(string_value).strip() # Try JSON first - handles valid JSON with # inside (like {"color": "#FF0000"}) try: return json.loads(actualvalue) except (json.JSONDecodeError, ValueError): pass # JSON failed - strip inline comments if present # Only treat # as comment if preceded by whitespace (e.g., "value # comment") if "#" in actualvalue: # For JSON-like values, try stripping from rightmost # positions # This handles cases like {"color": "#FF0000"} # comment if actualvalue.startswith("[") or actualvalue.startswith("{"): hash_positions = [i for i, c in enumerate(actualvalue) if c == "#"] for pos in reversed(hash_positions): candidate = actualvalue[:pos].strip() try: return json.loads(candidate) except (json.JSONDecodeError, ValueError): continue # For non-JSON or if all JSON attempts failed, strip comments with whitespace before # # This preserves values like "my#tag" while stripping "value # comment" # Find the earliest comment separator to handle "value\t# c1 # c2" correctly comment_positions = [actualvalue.find(sep) for sep in (" #", "\t#") if sep in actualvalue] if comment_positions: cut_pos = min(comment_positions) actualvalue = actualvalue[:cut_pos].rstrip() # Parse the (possibly stripped) value if actualvalue == "None": return None if actualvalue in ("True", "true"): return True if actualvalue in ("False", "false"): return False # Try JSON again (for cases like [1,2,3] # comment -> [1,2,3]) try: return json.loads(actualvalue) except (json.JSONDecodeError, ValueError): pass # Try int try: return int(actualvalue) except ValueError: pass # Try float try: return float(actualvalue) except ValueError: pass return actualvalue def populate_class_from_dict(myclass, options): """ :brief: helper function to establish a compatibility layer between new way of storing config and current way of accessing it. assumes all class attributes are all-uppercase, and pattern-matches attributes in priority order dict/list (json) -> -> int -> float-> string REMEMBER TO ENCLOSE PROPERTY NAMES IN LISTS IN DOUBLE QUOTES """ for key, value in options: if key.startswith("_") and key.endswith("options"): continue actualkey = key.upper() actualvalue = conf_attribute_reader(value) setattr(myclass, actualkey, actualvalue) class TriggerMode: SOFTWARE = "Software Trigger" HARDWARE = "Hardware Trigger" CONTINUOUS = "Continuous Acquisition" @staticmethod def convert_to_var(option: Union[str, "TriggerMode"]) -> "TriggerMode": """ Attempts to convert the given string to a TriggerMode. """ if isinstance(option, TriggerMode): return option for name, value in vars(TriggerMode).items(): if value == option or name == option.upper(): return getattr(TriggerMode, name) raise ValueError(f"Invalid trigger mode: {option}") class Acquisition: NUMBER_OF_FOVS_PER_AF = 3 IMAGE_FORMAT = "tiff" IMAGE_DISPLAY_SCALING_FACTOR = 0.3 DX = 0.9 DY = 0.9 DZ = 1.5 NX = 1 NY = 1 USE_MULTIPROCESSING = True class PosUpdate: INTERVAL_MS = 25 class MicrocontrollerDef: MSG_LENGTH = 24 CMD_LENGTH = 8 N_BYTES_POS = 4 USE_SEPARATE_MCU_FOR_DAC = False class MCU_PINS: PWM1 = 5 PWM2 = 4 PWM3 = 22 PWM4 = 3 PWM5 = 23 PWM6 = 2 PWM7 = 1 PWM9 = 6 PWM10 = 7 PWM11 = 8 PWM12 = 9 PWM13 = 10 PWM14 = 15 PWM15 = 24 PWM16 = 25 AF_LASER = 15 class CMD_SET: MOVE_X = 0 MOVE_Y = 1 MOVE_Z = 2 MOVE_THETA = 3 MOVE_W = 4 HOME_OR_ZERO = 5 TURN_ON_ILLUMINATION = 10 TURN_OFF_ILLUMINATION = 11 SET_ILLUMINATION = 12 SET_ILLUMINATION_LED_MATRIX = 13 ACK_JOYSTICK_BUTTON_PRESSED = 14 ANALOG_WRITE_ONBOARD_DAC = 15 SET_DAC80508_REFDIV_GAIN = 16 SET_ILLUMINATION_INTENSITY_FACTOR = 17 MOVETO_W = 18 MOVE_W2 = 19 MOVETO_X = 6 MOVETO_Y = 7 MOVETO_Z = 8 SET_LIM = 9 CONFIGURE_STEPPER_DRIVER = 21 SET_MAX_VELOCITY_ACCELERATION = 22 SET_LEAD_SCREW_PITCH = 23 SET_OFFSET_VELOCITY = 24 CONFIGURE_STAGE_PID = 25 ENABLE_STAGE_PID = 26 DISABLE_STAGE_PID = 27 SET_HOME_SAFETY_MERGIN = 28 SET_PID_ARGUMENTS = 29 SEND_HARDWARE_TRIGGER = 30 SET_STROBE_DELAY = 31 SET_AXIS_DISABLE_ENABLE = 32 SET_TRIGGER_MODE = 33 # Multi-port illumination commands (firmware v1.0+) SET_PORT_INTENSITY = 34 # Set DAC intensity for specific port only TURN_ON_PORT = 35 # Turn on GPIO for specific port TURN_OFF_PORT = 36 # Turn off GPIO for specific port SET_PORT_ILLUMINATION = 37 # Set intensity + on/off in one command SET_MULTI_PORT_MASK = 38 # Set on/off for multiple ports (partial update) TURN_OFF_ALL_PORTS = 39 # Turn off all illumination ports SET_WATCHDOG_TIMEOUT = 40 # Set serial watchdog timeout and enable SET_PIN_LEVEL = 41 HEARTBEAT = 42 # No-op keepalive for watchdog MOVETO_W2 = 43 # Absolute move on the W2 filter wheel # Firmware >= 1.6 only; the host never sends these to older firmware (callers gate on the version). SET_ENCODER_REPORTING = 44 # One axis's encoder in the status packet (see ENCODER_REPORTING) SET_RAMP_PROFILE = 47 # S-shaped or trapezoidal ramp per axis (see RAMP_PROFILE) SET_COMPLETION_WINDOW = 49 # Report a move complete once within a distance of the target # Hardware sequencer (opcodes 60-63; 64-66 are taken above). Wire contract: control/sequencer_program.py, mirroring # firmware/controller/src/sequencer/seq_wire.h. SEQ_WRITE = 60 # [2]=word index, [3..6]=4 bytes of the staged program (absolute, idempotent) SEQ_COMMIT = 61 # [2..3]=byte length BE, [4..5]=CRC-16/CCITT-FALSE BE; parse + validate SEQ_RUN = 62 # [2..5]=int32 stack start BE; stays IN_PROGRESS until the sequence is terminal SEQ_CANCEL = 63 # finish the current exposure, then wind down INITFILTERWHEEL_W2 = 252 INITFILTERWHEEL = 253 INITIALIZE = 254 RESET = 255 SET_LIMIT_SWITCH_CONFIG = 64 SET_FOCUS_WHEEL_MODE = 65 # Firmware >= FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE (see FOCUS_WHEEL_MODE) SET_PANEL_LOCK = 66 # Firmware >= FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE: [2] 1 = the control panel moves nothing # Firmware >= STARTUP_STATE_MIN_FIRMWARE. [2..5] = the configuration signature (big-endian), [6] = (format << 4) | # required axes mask. Neither moves anything. STORE_CONFIG_SIGNATURE = 67 # mask 0; a different signature or format clears every homed flag QUERY_STARTUP_STATE = 68 # mask bit a = protocol axis a must be homed; answered in the status byte (StartupVerdict) class CMD_SET2: ANALOG_WRITE_DAC8050X = 0 SET_CAMERA_TRIGGER_FREQUENCY = 1 START_CAMERA_TRIGGERING = 2 STOP_CAMERA_TRIGGERING = 3 BIT_POS_JOYSTICK_BUTTON = 0 BIT_POS_SWITCH = 1 BIT_POS_Z_LIMIT_LEFT = 2 BIT_POS_Z_LIMIT_RIGHT = 3 class ENCODER_REPORTING: """Modes for CMD_SET.SET_ENCODER_REPORTING (firmware >= 1.6). OFF: shipping packet. ENC_IN_THETA: the status packet's theta field (bytes 14-17) carries the selected axis's ENC_POS in microsteps, byte 19 carries ENC_FLAG bits and bytes 20-21 the clipped int16 ENC_POS - XACTUAL (positive = encoder ahead of the step counter). ENC_AS_POSITION: as ENC_IN_THETA, and the axis's own position field carries ENC_POS instead of XACTUAL (X/Y/Z only). The filter wheels have no position field in the packet, so this is the only way to see one. """ OFF = 0 ENC_IN_THETA = 1 ENC_AS_POSITION = 2 class ENC_FLAG: """Bit positions in status byte 19, valid only while encoder reporting is on.""" REPORTING = 0 PID_ENABLED = 1 AXIS_SHIFT = 4 # bits 4-6: protocol axis id being reported class FOCUS_WHEEL_MODE: """Modes for CMD_SET.SET_FOCUS_WHEEL_MODE (firmware >= FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE). DRIVES_Z: the control panel's focus wheel moves the Z stepper (the firmware default, and after RESET and INITIALIZE). TO_HOST: the wheel moves nothing; the status packet's theta field (bytes 14-17) carries the wheel's tick count since the mode was set, flagged by FOCUS_WHEEL_FLAG_REPORTING in byte 19, so the host can drive another focus axis with it. Refused while encoder reporting is on (they share those bytes), and vice versa. """ DRIVES_Z = 0 TO_HOST = 1 FOCUS_WHEEL_FLAG_REPORTING = 7 # status byte 19 bit: bytes 14-17 carry the focus wheel count # Status byte 19 bit: bytes 14-17 carry the hardware sequencer's status (control.sequencer_program.SequencerStatus) # instead of the encoder position / focus wheel count. Set while a sequence runs and for about a second after any # sequencer command or terminal state, so a refusal or a final status is readable; the other owners resume afterwards. SEQ_FLAG_STATUS = 2 # SET_FOCUS_WHEEL_MODE [3] flag: also store the mode as the controller's power-up mode (EEPROM; RESET and INITIALIZE # use it too). Squid saves TO_HOST on a lift system, so the wheel moves nothing while Squid is not running. FOCUS_WHEEL_SAVE_AS_POWER_UP = 1 FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE = (1, 8) class RAMP_PROFILE: """Values for CMD_SET.SET_RAMP_PROFILE (firmware >= 1.6). S-shape is the firmware default.""" TRAPEZOID = 1 SSHAPE = 2 class HOME_OR_ZERO: HOME_NEGATIVE = 1 # motor moves along the negative direction (MCU coordinates) HOME_POSITIVE = 0 # motor moves along the negative direction (MCU coordinates) ZERO = 2 class AXIS: X = 0 Y = 1 Z = 2 THETA = 3 XY = 4 W = 5 W2 = 6 class LIMIT_CODE: X_POSITIVE = 0 X_NEGATIVE = 1 Y_POSITIVE = 2 Y_NEGATIVE = 3 Z_POSITIVE = 4 Z_NEGATIVE = 5 class LIMIT_SWITCH_BITS: """Bits of the per-axis limit switch config nibble sent with SET_LIMIT_SWITCH_CONFIG.""" LEFT_ENABLED = 1 RIGHT_ENABLED = 2 LEFT_ACTIVE_HIGH = 4 RIGHT_ACTIVE_HIGH = 8 LIMIT_SWITCH_DEFAULT_CONFIG = 0x03 # both inputs enabled, both active low # First firmware with SET_LIMIT_SWITCH_CONFIG. The single source for the Microcontroller's gate, FirmwareSimSerial's # cutoff and the tests' versions. LIMIT_SWITCH_CONFIG_MIN_FIRMWARE = (1, 7) class StartupVerdict(IntEnum): """QUERY_STARTUP_STATE's answer (firmware >= STARTUP_STATE_MIN_FIRMWARE): may a relaunched host skip startup homing? The first failing check wins, in this order; WARM only if none fails.""" WARM = 0 # same configuration, healthy, at rest, every required axis homed NO_SIGNATURE = 1 # none stored since power-up or INITIALIZE, or a covered setting changed after the store SIGNATURE_MISMATCH = 2 # the stored signature or format differs from the query's UNHEALTHY = 3 # power not good, a stage TMC4361A lost its configuration, or a stage driver disabled MOVING = 4 # an X/Y/Z ramp has not stopped NOT_HOMED = 5 # a required axis is not homed # First firmware with STORE_CONFIG_SIGNATURE / QUERY_STARTUP_STATE. The single source for the Microcontroller's gate, # FirmwareSimSerial's cutoff and the tests' versions. STARTUP_STATE_MIN_FIRMWARE = (1, 9) class LIMIT_SWITCHES: # Left blocks negative firmware motion, right blocks positive (before the X/Y flip). # active_high = False is the stock hall sensor. enabled = False only when no switch is fitted; # the input an axis homes on must stay enabled. X_LEFT_ACTIVE_HIGH = False X_LEFT_ENABLED = True X_RIGHT_ACTIVE_HIGH = False X_RIGHT_ENABLED = True Y_LEFT_ACTIVE_HIGH = False Y_LEFT_ENABLED = True Y_RIGHT_ACTIVE_HIGH = False Y_RIGHT_ENABLED = True Z_LEFT_ACTIVE_HIGH = False Z_LEFT_ENABLED = True Z_RIGHT_ACTIVE_HIGH = False Z_RIGHT_ENABLED = True _LIMIT_SWITCH_KEYS = tuple( f"{axis}_{side}_{setting}" for axis in "XYZ" for side in ("LEFT", "RIGHT") for setting in ("ACTIVE_HIGH", "ENABLED") ) def limit_switch_config_problems() -> List[str]: """What is wrong with LIMIT_SWITCHES as loaded from [LIMIT_SWITCHES]; empty when nothing is. The loader puts any key of the section on the class and its value through conf_attribute_reader, so a misspelled key would be a stray attribute nobody reads and "no", "off" or 0 would be used by truthiness. Each unknown key and each value that is not True or False is listed here. Importing _def never fails on it: the Microcontroller raises LimitSwitchConfigError with this list before it sends anything beyond its firmware-version probe. """ problems = [] for name, value in vars(LIMIT_SWITCHES).items(): if name.startswith("__") and name.endswith("__"): continue if name not in _LIMIT_SWITCH_KEYS: problems.append(f"unknown key {name.lower()}") elif type(value) is not bool: problems.append(f"{name.lower()} = {value!r} is not True or False") return problems def limit_switch_config_byte(axis: str) -> int: """Config nibble for axis ("x", "y" or "z") built from LIMIT_SWITCHES.""" a = axis.upper() byte = 0 for side in ("LEFT", "RIGHT"): if getattr(LIMIT_SWITCHES, f"{a}_{side}_ENABLED"): byte |= getattr(LIMIT_SWITCH_BITS, f"{side}_ENABLED") if getattr(LIMIT_SWITCHES, f"{a}_{side}_ACTIVE_HIGH"): byte |= getattr(LIMIT_SWITCH_BITS, f"{side}_ACTIVE_HIGH") return byte class LIMIT_SWITCH_POLARITY: # Retired (replaced by LIMIT_SWITCHES). Kept only so that field .txt configurations that still assign # X/Y/Z_HOME_SWITCH_POLARITY = LIMIT_SWITCH_POLARITY.<...> exec without a NameError; nothing reads these. ACTIVE_LOW = 0 ACTIVE_HIGH = 1 DISABLED = 2 def legacy_limit_switch_warning(cfp: ConfigParser) -> Optional[str]: """Warning text if cfp still has the retired [LIMIT_SWITCH_POLARITY] section, else None.""" if cfp.has_section("LIMIT_SWITCH_POLARITY"): return ( "The [LIMIT_SWITCH_POLARITY] section in the configuration file is no longer used and is ignored; " "limit switches are now configured in [LIMIT_SWITCHES] (x/y/z_left/right_active_high and _enabled)." ) return None class ILLUMINATION_CODE: """Illumination source codes for MCU communication. LED Matrix Patterns (USB ports): USB1-USB8 map to pattern codes 0-8+. Illumination Control TTL Ports (D1-D5): Port-based names (ILLUMINATION_D1-D5) are preferred for new code. Wavelength-based names (ILLUMINATION_SOURCE_405NM, etc.) are kept as aliases for backward compatibility. The actual wavelength is configured in the illumination_channel_config.yaml file, not hardcoded here. """ # LED matrix patterns (USB ports) ILLUMINATION_SOURCE_LED_ARRAY_FULL = 0 ILLUMINATION_SOURCE_LED_ARRAY_LEFT_HALF = 1 ILLUMINATION_SOURCE_LED_ARRAY_RIGHT_HALF = 2 ILLUMINATION_SOURCE_LED_ARRAY_LEFTB_RIGHTR = 3 ILLUMINATION_SOURCE_LED_ARRAY_LOW_NA = 4 ILLUMINATION_SOURCE_LED_ARRAY_LEFT_DOT = 5 ILLUMINATION_SOURCE_LED_ARRAY_RIGHT_DOT = 6 ILLUMINATION_SOURCE_LED_ARRAY_TOP_HALF = 7 ILLUMINATION_SOURCE_LED_ARRAY_BOTTOM_HALF = 8 ILLUMINATION_SOURCE_LED_EXTERNAL_FET = 20 # Illumination Control TTL Ports - port-based names (preferred) # These correspond to controller_port D1-D5 in illumination_channel_config.yaml # Note: D3/D4 source codes are non-sequential (14, 13) for historical API compatibility ILLUMINATION_D1 = 11 ILLUMINATION_D2 = 12 ILLUMINATION_D3 = 14 ILLUMINATION_D4 = 13 ILLUMINATION_D5 = 15 # Illumination Control TTL Ports - legacy wavelength-based names (deprecated, kept for compatibility) # Use ILLUMINATION_D1-D5 for new code; wavelength is configured in YAML ILLUMINATION_SOURCE_405NM = ILLUMINATION_D1 ILLUMINATION_SOURCE_488NM = ILLUMINATION_D2 ILLUMINATION_SOURCE_561NM = ILLUMINATION_D3 ILLUMINATION_SOURCE_638NM = ILLUMINATION_D4 ILLUMINATION_SOURCE_730NM = ILLUMINATION_D5 class ILLUMINATION_PORT: """Port indices for multi-port illumination control (firmware v1.0+). Port indices (0-15) for up to 16 illumination ports. These are used with the new multi-port illumination commands (SET_PORT_INTENSITY, TURN_ON_PORT, etc.). Note: These are port indices, NOT the legacy source codes (11-15). For legacy source codes, use ILLUMINATION_CODE.ILLUMINATION_D1, etc. """ D1 = 0 D2 = 1 D3 = 2 D4 = 3 D5 = 4 # D6-D16 can be added as hardware expands def source_code_to_port_index(source_code: int) -> int: """Map legacy illumination source code to port index. Legacy source codes are non-sequential for historical API compatibility: D1 = 11, D2 = 12, D3 = 14, D4 = 13, D5 = 15 Note: D3 and D4 are swapped! Args: source_code: Legacy source code (11-15 for D1-D5) Returns: Port index (0-4), or -1 for unknown source codes """ mapping = { ILLUMINATION_CODE.ILLUMINATION_D1: 0, # 11 -> 0 ILLUMINATION_CODE.ILLUMINATION_D2: 1, # 12 -> 1 ILLUMINATION_CODE.ILLUMINATION_D3: 2, # 14 -> 2 (non-sequential!) ILLUMINATION_CODE.ILLUMINATION_D4: 3, # 13 -> 3 (non-sequential!) ILLUMINATION_CODE.ILLUMINATION_D5: 4, # 15 -> 4 } return mapping.get(source_code, -1) def port_index_to_source_code(port_index: int) -> int: """Map port index to legacy illumination source code. Args: port_index: Port index (0-4 for D1-D5) Returns: Legacy source code (11-15), or -1 for invalid port index """ mapping = { 0: ILLUMINATION_CODE.ILLUMINATION_D1, # 0 -> 11 1: ILLUMINATION_CODE.ILLUMINATION_D2, # 1 -> 12 2: ILLUMINATION_CODE.ILLUMINATION_D3, # 2 -> 14 3: ILLUMINATION_CODE.ILLUMINATION_D4, # 3 -> 13 4: ILLUMINATION_CODE.ILLUMINATION_D5, # 4 -> 15 } return mapping.get(port_index, -1) # Response byte positions for MCU protocol (24-byte response) RESPONSE_BYTE_FIRMWARE_VERSION = 22 # Nibble-encoded: high=major, low=minor # Serial watchdog (illumination auto-shutoff safety) # Must match firmware constants in constants.h DEFAULT_WATCHDOG_TIMEOUT_MS = 5000 # 5 seconds (matches firmware) MAX_WATCHDOG_TIMEOUT_MS = 3600000 # 1 hour (matches firmware) WATCHDOG_TIMEOUT_S = DEFAULT_WATCHDOG_TIMEOUT_MS / 1000.0 class VOLUMETRIC_IMAGING: NUM_PLANES_PER_VOLUME = 20 class CMD_EXECUTION_STATUS: COMPLETED_WITHOUT_ERRORS = 0 IN_PROGRESS = 1 CMD_CHECKSUM_ERROR = 2 CMD_INVALID = 3 CMD_EXECUTION_ERROR = 4 ERROR_CODE_EMPTYING_THE_FLUDIIC_LINE_FAILED = 100 # Firmware >= STARTUP_STATE_MIN_FIRMWARE: status byte values STARTUP_VERDICT_STATUS_BASE + StartupVerdict (64-69) are # QUERY_STARTUP_STATE's reply, sent until the next command arrives, in place of IN_PROGRESS or the last command's # status. Not an execution status: never completion, error or idle evidence. STARTUP_VERDICT_STATUS_BASE = 64 # In those packets bytes 14-21 are the startup reply, not the theta, encoder or focus wheel fields: byte 19 bit # STARTUP_REPLY_FLAG_PIEZO_DAC_WRITTEN set means bytes 20-21 (big-endian) are the last code written to the objective # piezo's DAC channel since the controller powered up. OBJECTIVE_PIEZO_DAC_CHANNEL = 7 STARTUP_REPLY_FLAG_PIEZO_DAC_WRITTEN = 0 class SpotDetectionMode(Enum): """Specifies which spot to detect when multiple spots are present. SINGLE: Expect and detect single spot DUAL_RIGHT: In dual-spot case, use rightmost spot DUAL_LEFT: In dual-spot case, use leftmost spot MULTI_RIGHT: In multi-spot case, use rightmost spot MULTI_SECOND_RIGHT: In multi-spot case, use spot immediately left of rightmost spot """ SINGLE = "single" DUAL_RIGHT = "dual_right" DUAL_LEFT = "dual_left" MULTI_RIGHT = "multi_right" MULTI_SECOND_RIGHT = "multi_second_right" class FileSavingOption(Enum): """File saving options. INDIVIDUAL_IMAGES: Save each image as a separate file. Format is defined in Acquisition.IMAGE_FORMAT. MULTI_PAGE_TIFF: Save all images from a single FOV as a single multi-page TIFF file. OME_TIFF: Save data to OME-TIFF stacks with full metadata. ZARR_V3: Save data to Zarr v3 format with sharding. """ INDIVIDUAL_IMAGES = "INDIVIDUAL_IMAGES" MULTI_PAGE_TIFF = "MULTI_PAGE_TIFF" OME_TIFF = "OME_TIFF" ZARR_V3 = "ZARR_V3" @staticmethod def convert_to_enum(option: Union[str, "FileSavingOption"]) -> "FileSavingOption": """ Attempts to convert the given string to a FileSavingOption. This ignores all letter cases. """ if isinstance(option, FileSavingOption): return option try: return FileSavingOption[option.upper()] except KeyError: raise ValueError(f"Invalid file saving option: {option}") class ZarrChunkMode(Enum): """Zarr chunk size configuration. FULL_FRAME: Each chunk is a full image plane (simplest, default). TILED_512: 512x512 pixel chunks for tiled visualization. TILED_256: 256x256 pixel chunks for fine-grained streaming. """ FULL_FRAME = "full_frame" TILED_512 = "tiled_512" TILED_256 = "tiled_256" @staticmethod def convert_to_enum(option: Union[str, "ZarrChunkMode"]) -> "ZarrChunkMode": """Convert string or enum to ZarrChunkMode enum.""" if isinstance(option, ZarrChunkMode): return option try: return ZarrChunkMode(option.lower()) except ValueError: raise ValueError( f"Invalid zarr chunk mode: '{option}'. Expected 'full_frame', 'tiled_512', or 'tiled_256'." ) class ZarrCompression(Enum): """Zarr compression presets optimized for different use cases. NONE: No compression, maximum write speed (~2x faster than TIFF). FAST: blosc-lz4, ~1000 MB/s encode, ~2x compression ratio. Safe for 10-20 fps. BALANCED: blosc-zstd level 3, ~500 MB/s encode, ~3-4x ratio. BEST: blosc-zstd level 9, slowest but best compression ratio. """ NONE = "none" FAST = "fast" BALANCED = "balanced" BEST = "best" @staticmethod def convert_to_enum(option: Union[str, "ZarrCompression"]) -> "ZarrCompression": """Convert string or enum to ZarrCompression enum.""" if isinstance(option, ZarrCompression): return option try: return ZarrCompression(option.lower()) except ValueError: raise ValueError(f"Invalid zarr compression: '{option}'. Expected 'none', 'fast', 'balanced', or 'best'.") class FocusMeasureOperator(Enum): LAPE = "LAPE" # LAPE has worked well for bright field images GLVA = "GLVA" # GLVA works well for darkfield/fluorescence TENENGRAD = "TENENGRAD" @staticmethod def convert_to_enum(option: Union[str, "FocusMeasureOperator"]) -> "FocusMeasureOperator": """ Attempts to convert the given string to a FocusMeasureOperator. This ignores all letter cases. """ if isinstance(option, FocusMeasureOperator): return option try: return FocusMeasureOperator[option.upper()] except KeyError: raise ValueError(f"Invalid focus measure operator: {option}") class ZProjectionMode(Enum): """Z-projection mode for downsampled view generation. MIP: Max intensity projection - uses running maximum across all z-levels LAST_PLANE: Last plane - each z-plane overwrites the previous one """ MIP = "mip" LAST_PLANE = "last_plane" @staticmethod def convert_to_enum(option: Union[str, "ZProjectionMode"]) -> "ZProjectionMode": """Convert string or enum to ZProjectionMode enum.""" if isinstance(option, ZProjectionMode): return option try: return ZProjectionMode(option.lower()) except ValueError: raise ValueError(f"Invalid z-projection mode: '{option}'. Expected 'mip' or 'last_plane'.") class DownsamplingMethod(Enum): """Interpolation method for downsampled view generation. INTER_LINEAR: Fast bilinear interpolation (~0.05ms). Each resolution is computed directly from the original image (parallel). Best for real-time previews. INTER_AREA_FAST: Gaussian pyramid downsampling (~1ms). Uses cv2.pyrDown chain (optimized 2x reductions) then INTER_AREA for final size. Good balance of speed and quality. Resolutions computed in parallel. INTER_AREA: High-quality area averaging (~18ms). Resolutions are computed in cascade (original→5um→10um→20um) for speed. Best for final output quality. """ INTER_LINEAR = "inter_linear" INTER_AREA_FAST = "inter_area_fast" INTER_AREA = "inter_area" @staticmethod def convert_to_enum(option: Union[str, "DownsamplingMethod"]) -> "DownsamplingMethod": """Convert string or enum to DownsamplingMethod enum.""" if isinstance(option, DownsamplingMethod): return option try: return DownsamplingMethod(option.lower()) except ValueError: raise ValueError( f"Invalid downsampling method: '{option}'. " "Expected 'inter_linear', 'inter_area_fast', or 'inter_area'." ) class ZMotorConfig(Enum): """Z motor configuration options. STEPPER: Stepper motor only STEPPER_PIEZO: Stepper motor with piezo for fine Z control PIEZO: Piezo only """ STEPPER = "STEPPER" STEPPER_PIEZO = "STEPPER + PIEZO" PIEZO = "PIEZO" @staticmethod def convert_to_enum(option: Union[str, "ZMotorConfig"]) -> "ZMotorConfig": """Convert string or enum to ZMotorConfig enum.""" if isinstance(option, ZMotorConfig): return option for member in ZMotorConfig: if member.value == option: return member raise ValueError(f"Invalid Z motor config: '{option}'. Expected one of: {[m.value for m in ZMotorConfig]}") def has_piezo(self) -> bool: """Check if this configuration includes a piezo.""" return "PIEZO" in self.value def is_piezo_only(self) -> bool: """Check if this configuration is piezo-only (no stepper).""" return self == ZMotorConfig.PIEZO PRINT_CAMERA_FPS = True ########################################################### #### machine specific configurations - to be overridden ### ########################################################### DEFAULT_TRIGGER_MODE = TriggerMode.SOFTWARE BUFFER_SIZE_LIMIT = 4095 # note: XY are the in-plane axes, Z is the focus axis # change the following so that "backward" is "backward" - towards the single sided hall effect sensor STAGE_MOVEMENT_SIGN_X = -1 STAGE_MOVEMENT_SIGN_Y = 1 STAGE_MOVEMENT_SIGN_Z = -1 STAGE_MOVEMENT_SIGN_THETA = 1 STAGE_MOVEMENT_SIGN_W = 1 STAGE_POS_SIGN_X = STAGE_MOVEMENT_SIGN_X STAGE_POS_SIGN_Y = STAGE_MOVEMENT_SIGN_Y STAGE_POS_SIGN_Z = STAGE_MOVEMENT_SIGN_Z STAGE_POS_SIGN_THETA = STAGE_MOVEMENT_SIGN_THETA TRACKING_MOVEMENT_SIGN_X = 1 TRACKING_MOVEMENT_SIGN_Y = 1 TRACKING_MOVEMENT_SIGN_Z = 1 TRACKING_MOVEMENT_SIGN_THETA = 1 USE_ENCODER_X = False USE_ENCODER_Y = False USE_ENCODER_Z = False USE_ENCODER_THETA = False ENCODER_POS_SIGN_X = 1 ENCODER_POS_SIGN_Y = 1 ENCODER_POS_SIGN_Z = 1 ENCODER_POS_SIGN_THETA = 1 ENCODER_STEP_SIZE_X_MM = 100e-6 ENCODER_STEP_SIZE_Y_MM = 100e-6 ENCODER_STEP_SIZE_Z_MM = 100e-6 ENCODER_STEP_SIZE_THETA = 1 FULLSTEPS_PER_REV_X = 200 FULLSTEPS_PER_REV_Y = 200 FULLSTEPS_PER_REV_Z = 200 FULLSTEPS_PER_REV_W = 200 FULLSTEPS_PER_REV_THETA = 200 # beginning of actuator specific configurations SCREW_PITCH_X_MM = 1 SCREW_PITCH_Y_MM = 1 SCREW_PITCH_Z_MM = 0.012 * 25.4 SCREW_PITCH_W_MM = 1 MICROSTEPPING_DEFAULT_X = 8 MICROSTEPPING_DEFAULT_Y = 8 MICROSTEPPING_DEFAULT_Z = 8 MICROSTEPPING_DEFAULT_W = 64 MICROSTEPPING_DEFAULT_THETA = 8 # not used, to be removed X_MOTOR_RMS_CURRENT_mA = 490 Y_MOTOR_RMS_CURRENT_mA = 490 Z_MOTOR_RMS_CURRENT_mA = 490 W_MOTOR_RMS_CURRENT_mA = 1900 X_MOTOR_I_HOLD = 0.5 Y_MOTOR_I_HOLD = 0.5 Z_MOTOR_I_HOLD = 0.5 W_MOTOR_I_HOLD = 0.5 MAX_VELOCITY_X_mm = 25 MAX_VELOCITY_Y_mm = 25 MAX_VELOCITY_Z_mm = 2 MAX_VELOCITY_W_mm = 3.19 MAX_ACCELERATION_X_mm = 500 MAX_ACCELERATION_Y_mm = 500 MAX_ACCELERATION_Z_mm = 20 MAX_ACCELERATION_W_mm = 300 # config encoder arguments HAS_ENCODER_X = False HAS_ENCODER_Y = False HAS_ENCODER_Z = False HAS_ENCODER_W = False # the wheel's encoder is for reporting and the tuner; closed loop on the wheel is not supported # enable PID control ENABLE_PID_X = False ENABLE_PID_Y = False ENABLE_PID_Z = False # PID arguments PID_P_X = int(1 << 12) PID_I_X = int(0) PID_D_X = int(0) PID_P_Y = int(1 << 12) PID_I_Y = int(0) PID_D_Y = int(0) PID_P_Z = int(1 << 12) PID_I_Z = int(0) PID_D_Z = int(1) # flip direction True or False ENCODER_FLIP_DIR_X = True ENCODER_FLIP_DIR_Y = True ENCODER_FLIP_DIR_Z = True ENCODER_FLIP_DIR_W = False # distance for each count (um) ENCODER_RESOLUTION_UM_X = 0.05 ENCODER_RESOLUTION_UM_Y = 0.05 ENCODER_RESOLUTION_UM_Z = 0.1 # end of actuator specific configurations SCAN_STABILIZATION_TIME_MS_X = 160 SCAN_STABILIZATION_TIME_MS_Y = 160 SCAN_STABILIZATION_TIME_MS_Z = 20 HOMING_ENABLED_X = True HOMING_ENABLED_Y = True HOMING_ENABLED_Z = False SLEEP_TIME_S = 0.005 LED_MATRIX_R_FACTOR = 0 LED_MATRIX_G_FACTOR = 0 LED_MATRIX_B_FACTOR = 1 DEFAULT_SAVING_PATH = str(Path.home() / "Downloads") ACQUISITION_CONFIGURATIONS_PATH = Path("user_profiles") FILE_ID_PADDING = 0 CAMERA_PIXEL_SIZE_UM = { "IMX290": 2.9, "IMX178": 2.4, "IMX226": 1.85, "IMX250": 3.45, "IMX252": 3.45, "IMX273": 3.45, "IMX264": 3.45, "IMX265": 3.45, "IMX571": 3.76, "PYTHON300": 4.8, } TUBE_LENS_MM = 50 CAMERA_SENSOR = "IMX226" TRACKERS = ["csrt", "kcf", "mil", "tld", "medianflow", "mosse", "daSiamRPN"] DEFAULT_TRACKER = "csrt" ENABLE_TRACKING = False TRACKING_SHOW_MICROSCOPE_CONFIGURATIONS = False # set to true when doing multimodal acquisition class CAMERA_CONFIG: ROI_OFFSET_X_DEFAULT = None ROI_OFFSET_Y_DEFAULT = None ROI_WIDTH_DEFAULT = None ROI_HEIGHT_DEFAULT = None ROTATE_IMAGE_ANGLE = None FLIP_IMAGE = None # 'Horizontal', 'Vertical', 'Both' CROP_WIDTH_UNBINNED = 4168 CROP_HEIGHT_UNBINNED = 4168 BINNING_FACTOR_DEFAULT = 2 PIXEL_FORMAT_DEFAULT = "MONO12" SENSOR_MODE_DEFAULT = None TEMPERATURE_DEFAULT = 20 FAN_SPEED_DEFAULT = 1 BLACKLEVEL_VALUE_DEFAULT = 3 AWB_RATIOS_R = 1.375 AWB_RATIOS_G = 1 AWB_RATIOS_B = 1.4141 class AF: STOP_THRESHOLD = 0.85 CROP_WIDTH = 800 CROP_HEIGHT = 800 class Tracking: SEARCH_AREA_RATIO = 10 # @@@ check CROPPED_IMG_RATIO = 10 # @@@ check BBOX_SCALE_FACTOR = 1.2 DEFAULT_TRACKER = "csrt" INIT_METHODS = ["roi"] DEFAULT_INIT_METHOD = "roi" SHOW_DAC_CONTROL = False class SLIDE_POSITION: LOADING_X_MM = 30 LOADING_Y_MM = 55 SCANNING_X_MM = 3 SCANNING_Y_MM = 3 class OUTPUT_GAINS: REFDIV = False CHANNEL0_GAIN = False CHANNEL1_GAIN = False CHANNEL2_GAIN = False CHANNEL3_GAIN = False CHANNEL4_GAIN = False CHANNEL5_GAIN = False CHANNEL6_GAIN = False CHANNEL7_GAIN = True SLIDE_POTISION_SWITCHING_TIMEOUT_LIMIT_S = 10 SLIDE_POTISION_SWITCHING_HOME_EVERYTIME = False class SOFTWARE_POS_LIMIT: X_POSITIVE = 56 X_NEGATIVE = -0.5 Y_POSITIVE = 56 Y_NEGATIVE = -0.5 Z_POSITIVE = 7 Z_NEGATIVE = 0.05 SHOW_AUTOLEVEL_BTN = False AUTOLEVEL_DEFAULT_SETTING = False MULTIPOINT_AUTOFOCUS_CHANNEL = "BF LED matrix full" # MULTIPOINT_AUTOFOCUS_CHANNEL = 'BF LED matrix left half' MULTIPOINT_AUTOFOCUS_ENABLE_BY_DEFAULT = False MULTIPOINT_BF_SAVING_OPTION = "Raw" # MULTIPOINT_BF_SAVING_OPTION = 'RGB2GRAY' # MULTIPOINT_BF_SAVING_OPTION = 'Green Channel Only' DEFAULT_MULTIPOINT_NX = 1 DEFAULT_MULTIPOINT_NY = 1 ENABLE_FLEXIBLE_MULTIPOINT = True USE_OVERLAP_FOR_FLEXIBLE = True ENABLE_WELLPLATE_MULTIPOINT = True ENABLE_RECORDING = False # Live is off after an acquisition, whatever it was before. Set resume_live_after_acquisition = True # in the [GENERAL] section of the machine INI to turn live back on when it was on before the run. RESUME_LIVE_AFTER_ACQUISITION = False # When enabled, each multipoint acquisition will write a second log file scoped to that acquisition at: # //acquisition.log ENABLE_PER_ACQUISITION_LOG = True # Memory profiling - when enabled, shows real-time RAM usage in status bar during acquisition # and logs periodic memory snapshots to help diagnose memory issues ENABLE_MEMORY_PROFILING = True # Simulated disk I/O for development (RAM/speed optimization) # When enabled, images are encoded to memory buffers but NOT saved to disk SIMULATED_DISK_IO_ENABLED = False SIMULATED_DISK_IO_SPEED_MB_S = 200.0 # Target write speed in MB/s (HDD: 50-100, SATA SSD: 200-500, NVMe: 1000-3000) SIMULATED_DISK_IO_COMPRESSION = True # Exercise compression CPU/RAM for realistic simulation # Per-component hardware simulation controls # These settings only apply when running WITHOUT the --simulation flag. # When --simulation is used, ALL components are simulated regardless of these settings. # Values: False = use real hardware (default), True = simulate this component SIMULATE_CAMERA = False SIMULATE_MICROCONTROLLER = False # Also controls stage (stage uses MCU) SIMULATE_SPINNING_DISK = False # XLight/Dragonfly SIMULATE_FILTER_WHEEL = False SIMULATE_OBJECTIVE_CHANGER = False SIMULATE_LASER_AF_CAMERA = False # Laser autofocus camera SIMULATE_FLUIDICS = False # Fluidics system (syringe pump, valves, TEC, flow sensors); built on Initialize # Acquisition Backpressure Settings # Prevents RAM exhaustion when acquisition speed exceeds disk write speed ACQUISITION_THROTTLING_ENABLED = True ACQUISITION_MAX_PENDING_JOBS = 10 # Max jobs in flight before throttling ACQUISITION_MAX_PENDING_MB = 2000.0 # Max pending MB before throttling ACQUISITION_THROTTLE_TIMEOUT_S = 30.0 # Max wait time when throttled CAMERA_SN = {"ch 1": "SN1", "ch 2": "SN2"} # for multiple cameras, to be overwritten in the configuration file ENABLE_STROBE_OUTPUT = False ACQUISITION_PATTERN = "S-Pattern" # 'S-Pattern', 'Unidirectional' FOV_PATTERN = "Unidirectional" # 'S-Pattern', 'Unidirectional' Z_STACKING_CONFIG = "FROM BOTTOM" # 'FROM BOTTOM', 'FROM CENTER', 'FROM TOP' Z_STACKING_CONFIG_MAP = {0: "FROM BOTTOM", 1: "FROM CENTER", 2: "FROM TOP"} # Order of the z and channel loops at each FOV: # 'CHANNEL FIRST' - at each z level, acquire every channel, then step z # 'Z FIRST' - acquire the whole z stack in one channel, then switch channel Z_STACK_ORDER = "CHANNEL FIRST" Z_STACK_ORDERS = ("CHANNEL FIRST", "Z FIRST") # Opt-in: show the Channel First / Z First choice next to Nz in the acquisition tabs. Off, the GUI always acquires # Channel First (whatever a loaded acquisition YAML says); the TCP server, fluidics protocols and # Microscope.acquire_single_fov still use an order they are given explicitly. ENABLE_Z_STACK_ORDER_SELECTION = False DEFAULT_Z_POS_MM = 2 WELLPLATE_OFFSET_X_mm = 0 # x offset adjustment for using different plates WELLPLATE_OFFSET_Y_mm = 0 # y offset adjustment for using different plates # focus measure operator FOCUS_MEASURE_OPERATOR = FocusMeasureOperator.LAPE # controller version CONTROLLER_VERSION = "Arduino Due" # 'Teensy' # How to read Spinnaker nodemaps, options are INDIVIDUAL or VALUE CHOSEN_READ = "INDIVIDUAL" # laser autofocus SUPPORT_LASER_AUTOFOCUS = False MAIN_CAMERA_MODEL = "MER2-1220-32U3M" FOCUS_CAMERA_MODEL = "MER2-630-60U3M" FOCUS_CAMERA_EXPOSURE_TIME_MS = 2 FOCUS_CAMERA_ANALOG_GAIN = 0 LASER_AF_AVERAGING_N = 3 LASER_AF_DISPLAY_SPOT_IMAGE = True LASER_AF_CROP_WIDTH = 1536 LASER_AF_CROP_HEIGHT = 256 LASER_AF_SPOT_DETECTION_MODE = SpotDetectionMode.DUAL_LEFT.value LASER_AF_RANGE = 100 DISPLACEMENT_SUCCESS_WINDOW_UM = 1.0 SPOT_CROP_SIZE = 100 CORRELATION_THRESHOLD = 0.7 PIXEL_TO_UM_CALIBRATION_DISTANCE = 6.0 LASER_AF_Y_WINDOW = 96 LASER_AF_X_WINDOW = 20 LASER_AF_MIN_PEAK_WIDTH = 10 LASER_AF_MIN_PEAK_DISTANCE = 10 LASER_AF_MIN_PEAK_PROMINENCE = 0.20 LASER_AF_SPOT_SPACING = 100 SHOW_LEGACY_DISPLACEMENT_MEASUREMENT_WINDOWS = False LASER_AF_FILTER_SIGMA = None LASER_AF_INITIALIZE_CROP_WIDTH = 1200 LASER_AF_INITIALIZE_CROP_HEIGHT = 800 MULTIPOINT_REFLECTION_AUTOFOCUS_ENABLE_BY_DEFAULT = False MULTIPOINT_CONTRAST_AUTOFOCUS_ENABLE_BY_DEFAULT = False RETRACT_OBJECTIVE_BEFORE_MOVING_TO_LOADING_POSITION = True OBJECTIVE_RETRACTED_POS_MM = 0.1 TWO_CLASSIFICATION_MODELS = False CLASSIFICATION_MODEL_PATH = "models/resnet18_en/version1/best.pt" CLASSIFICATION_MODEL_PATH2 = "models/resnet18_en/version2/best.pt" CLASSIFICATION_TEST_MODE = False CLASSIFICATION_TH = 0.3 SEGMENTATION_MODEL_PATH = "models/m2unet_model_flat_erode1_wdecay5_smallbatch/model_4000_11.pth" ENABLE_SEGMENTATION = True USE_TRT_SEGMENTATION = False SEGMENTATION_CROP = 1500 DISP_TH_DURING_MULTIPOINT = 0.95 SORT_DURING_MULTIPOINT = False INVERTED_OBJECTIVE = False # Illumination intensity scaling factor - scales DAC output for different hardware: # 0.6 = Squid LEDs (0-1.5V output range) # 0.8 = Squid laser engine (0-2V output range) # 1.0 = Full range (0-2.5V output, when DAC gain is 1 instead of 2) # This factor is applied to ALL illumination commands (legacy and multi-port). ILLUMINATION_INTENSITY_FACTOR = 0.6 CAMERA_TYPE = "Default" FOCUS_CAMERA_TYPE = "Default" # Spinning disk confocal integration ENABLE_SPINNING_DISK_CONFOCAL = False USE_LDI_SERIAL_CONTROL = False LDI_INTENSITY_MODE = "PC" LDI_SHUTTER_MODE = "PC" USE_CELESTA_ETHERNET_CONTROL = False USE_ANDOR_LASER_CONTROL = False ANDOR_LASER_VID = 0x1BDB ANDOR_LASER_PID = 0x0300 # Active blanking with an Andor SDK3 camera and Andor laser engine; one switch for both halves. # Laser: when a channel is selected, only its line's shutter is open (every other line on every unit is # closed), so the camera's exposure signal gates the one active line. Camera: the AUX OUT pin follows the # "all rows exposing" window (SDK3 AuxiliaryOutSource "FireAll"); this half is what a Dragonfly with TWO # Andor cameras needs, and does no harm with one. Off by default; needs AUX OUT wired to the engine. USE_ANDOR_ACTIVE_BLANKING = False # Vortran Stradus VersaLase over USB HID. VORTRAN_SHUTTER_CONTROL_MODE is "TTL" (TTL lines gate # the light) or "Software" (emission toggled over USB - slow, heads with the 5 s emission delay # take 5 s to turn on). With TTL, VORTRAN_TTL_INPUT is the VersaLase input the TTL lines are wired # to: "LASER_ENABLE" (DE-25 Laser Enable pins, standard; heads run CW at the laser power) or # "DIGITAL_MODULATION" (rear SMB inputs, optional; heads run in pulse mode at the peak power). USE_VORTRAN_LASER_CONTROL = False VORTRAN_SHUTTER_CONTROL_MODE = "TTL" VORTRAN_TTL_INPUT = "LASER_ENABLE" # Squid laser engine integration (Cephla Teensy-based laser controller) # When True, software opens a USB-serial connection to the laser engine, polls # per-channel status (state/temperature/ΔT/TTL), and gates acquisition on # channels reaching ACTIVE state. # Legacy keys of this (v1) engine, still read: set laser_engine = v1 and laser_engine_sn (below) instead. USE_SQUID_LASER_ENGINE = False SQUID_LASER_ENGINE_SN = None # USB serial number; required when USE_SQUID_LASER_ENGINE is True # Cephla laser engine (docs/laser-engine.md): laser_engine = v1 (the engine above) or v2 (control/laser_engine_v2.py: # intensity over USB, exposure timing on the Squid controller TTL lines D1-D5); blank or None = no laser engine. # Resolved at startup together with the legacy keys above (_resolve_laser_engine); the code reads only these two. LASER_ENGINE = None LASER_ENGINE_SN = None # the engine's USB serial number, every version (all digits is fine: matched as text) XLIGHT_SERIAL_NUMBER = "B00031BE" XLIGHT_SLEEP_TIME_FOR_WHEEL = 0.25 XLIGHT_VALIDATE_WHEEL_POS = False XLIGHT_EMISSION_FILTER_POSITIONS = 8 # 5 for Cicero, 8 for XLight V3 XLIGHT_ILLUMINATION_IRIS_DEFAULT = 100 XLIGHT_EMISSION_IRIS_DEFAULT = 100 # Dragonfly integration USE_DRAGONFLY = False DRAGONFLY_SERIAL_NUMBER = "00000000" # Confocal.nl NL5 integration ENABLE_NL5 = False ENABLE_CELLX = False CELLX_SN = None CELLX_MODULATION = "EXT Digital" NL5_USE_AOUT = False NL5_USE_DOUT = True # With NL5_USE_DOUT, a hardware trigger is one blocking RCM scan that waits for the camera's ready # signal. A scan that has not finished after this long (plus 3 frame times) is aborted and the # trigger dropped, instead of holding the camera's trigger lock forever. NL5_TRIGGER_TIMEOUT_S = 2.0 NL5_TRIGGER_PIN = 2 NL5_WAVENLENGTH_MAP = {405: 1, 470: 2, 488: 2, 545: 3, 555: 3, 561: 3, 637: 4, 638: 4, 640: 4} # Laser AF characterization mode LASER_AF_CHARACTERIZATION_MODE = False # Napari integration USE_NAPARI_FOR_MOSAIC_DISPLAY = True # Live view only (no acquisition tabs) LIVE_ONLY_MODE = False # NDViewer integration ENABLE_NDVIEWER = False # Location of a standalone ndviewer_light (file, folder holding ndviewer_light/, or command line); empty = auto-detect NDVIEWER_LIGHT_COMMAND = "" # Also record Snap images in the acquisition history RECORD_SNAPS_IN_HISTORY = False MOSAIC_VIEW_TARGET_PIXEL_SIZE_UM = 2 # How z-planes combine in the mosaic view (and its saved overview): running max, or last plane wins. MOSAIC_Z_PROJECTION = ZProjectionMode.MIP # Downsampled-view auto-save settings. Each flag independently controls one # output of the unified mosaic widget's save path: # SAVE_DOWNSAMPLED_OVERVIEW → mosaic_view/mosaic__um.ome.tiff # SAVE_DOWNSAMPLED_WELL_IMAGES → mosaic_view/wells/_um.tiff (plate mode only) # Both gate auto-save on acquisition end AND the manual Save View button, so # the checkboxes are the single source of truth for what gets written. # The save resolution is coupled with the on-screen target (MOSAIC_VIEW_TARGET_PIXEL_SIZE_UM). SAVE_DOWNSAMPLED_OVERVIEW = True SAVE_DOWNSAMPLED_WELL_IMAGES = True # Plate view zoom limits # MIN_VISIBLE_PIXELS: At maximum zoom, ensure at least this many pixels are visible # in the smallest dimension. 500 pixels allows inspecting cellular-level details. PLATE_VIEW_MIN_VISIBLE_PIXELS = 500.0 # MAX_ZOOM_FACTOR: Cap zoom to prevent performance issues with large texture rendering. # 10x is sufficient for most inspection tasks while maintaining smooth interaction. PLATE_VIEW_MAX_ZOOM_FACTOR = 10.0 # Controller SN (needed when using multiple teensy-based connections) CONTROLLER_SN = None # Sci microscopy SUPPORT_SCIMICROSCOPY_LED_ARRAY = False SCIMICROSCOPY_LED_ARRAY_SN = None SCIMICROSCOPY_LED_ARRAY_DISTANCE = 50 SCIMICROSCOPY_LED_ARRAY_DEFAULT_NA = 0.8 SCIMICROSCOPY_LED_ARRAY_DEFAULT_COLOR = [1, 1, 1] SCIMICROSCOPY_LED_ARRAY_TURN_ON_DELAY = 0.03 # time to wait before trigger the camera (in seconds) # Navigation Settings ENABLE_CLICK_TO_MOVE = True LIVE_VIEW_Z_STEP_UM = 5.0 LIVE_VIEW_Z_STEP_FAST_UM = 40.0 # Stitcher IS_HCS = False DYNAMIC_REGISTRATION = False STITCH_COMPLETE_ACQUISITION = False # Pseudo color settings CHANNEL_COLORS_MAP = { "405": {"hex": 0x20ADF8, "name": "bop blue"}, "488": {"hex": 0x1FFF00, "name": "green"}, "561": {"hex": 0xFFCF00, "name": "yellow"}, "638": {"hex": 0xFF0000, "name": "red"}, "730": {"hex": 0x770000, "name": "dark red"}, "R": {"hex": 0xFF0000, "name": "red"}, "G": {"hex": 0x1FFF00, "name": "green"}, "B": {"hex": 0x3300FF, "name": "blue"}, } SAVE_IN_PSEUDO_COLOR = False MERGE_CHANNELS = False # Emission filter wheel USE_EMISSION_FILTER_WHEEL = False EMISSION_FILTER_WHEEL_TYPE = "SQUID" # "SQUID", "ZABER", "OPTOSPIN" EMISSION_FILTER_WHEEL_INDICES = [1] # ZABER specific settings ZABER_EMISSION_FILTER_WHEEL_DELAY_MS = 70 ZABER_EMISSION_FILTER_WHEEL_BLOCKING_CALL = False # OPTOSPIN specific settings FILTER_CONTROLLER_SERIAL_NUMBER = "A10NG007" # used for both Zaber and Optospin for now OPTOSPIN_EMISSION_FILTER_WHEEL_SPEED_HZ = 50 OPTOSPIN_EMISSION_FILTER_WHEEL_DELAY_MS = 70 OPTOSPIN_EMISSION_FILTER_WHEEL_TTL_TRIGGER = False # SQUID specific settings SQUID_FILTERWHEEL_MAX_INDEX = 8 SQUID_FILTERWHEEL_MIN_INDEX = 1 SQUID_FILTERWHEEL_OFFSET = 0.008 SQUID_FILTERWHEEL_MOTORSLOTINDEX = 3 SQUID_FILTERWHEEL_TRANSITIONS_PER_REVOLUTION = 4000 # Shortest path between slots may cross the index flag (8 -> 1 is one slot, not seven); firmware >= 1.6 only. # False forces the flag-free arc on every firmware. SQUID_FILTERWHEEL_WRAP = True # > 0: the wheel reports a slot change complete once it is within this many degrees of the slot, while the last # degrees are still travelled, so the exposure can start earlier (firmware >= 1.6, SET_COMPLETION_WINDOW; ignored # with a warning on older firmware). 0 = complete at the exact slot with the wheel stopped. Size it from the optics: # (filter clear aperture - image field diameter) / 2 / filter pitch radius, in degrees, minus margin. 32 mm filters # on a 22 mm field and a ~46 mm pitch radius allow about 6 deg (5 was used on the bench: 58 instead of 78 ms per # slot, wheel 2.7 deg from the slot when COMPLETED arrived); 25 mm filters allow about 1.9 deg. SQUID_FILTERWHEEL_COMPLETION_WINDOW_DEG = 0.0 # Multi-wheel SQUID filter wheel configuration # Motor slot 3 = W axis (first filter wheel), motor slot 4 = W2 axis (second filter wheel) SQUID_FILTERWHEEL_CONFIGS = { 1: { "motor_slot_index": 3, # W axis "max_index": 8, "min_index": 1, "offset": 0.008, "transitions_per_revolution": 4000, }, 2: { "motor_slot_index": 4, # W2 axis "max_index": 8, "min_index": 1, "offset": 0.008, "transitions_per_revolution": 4000, }, } # Stage USE_PRIOR_STAGE = False PRIOR_STAGE_SN = "" # Encoders on a Prior stage: False switches them off at start-up (open loop), True on (closed loop), None sends # nothing. A ProScan turns on the encoders it detects at power-up and keeps a switched state until it is power-cycled, # so going back to None does not restore closed loop by itself. On an H117 closed loop made short moves ~3x slower and # did not recover a stall. Switched off, they still count ("P,e"), e.g. to check for lost steps. PRIOR_STAGE_USE_ENCODERS = None # ProScan SMS / SAS values, 1-1000. On an H117(1MM) stage 100 = 6 mm/s and 28.6 mm/s^2; 1000 = 60 mm/s, 285.5 mm/s^2. # Editable in Preferences > Advanced > Prior Stage, which also sends them to the connected stage. PRIOR_STAGE_MAX_SPEED = 100 PRIOR_STAGE_ACCELERATION = 100 # This rig's ceilings: the most the stage takes without losing steps (it runs open loop). Preferences and the driver # refuse more. 1000 is the controller's own maximum; set lower where faster moves lose steps. Speed and acceleration # act together: an H117(1MM) on a Squid stalled at 200/250 (its Y axis, on 10 mm moves) but not at 200/100, 175/250 # or 150 with any acceleration up to 1000. PRIOR_STAGE_MAX_SPEED_LIMIT = 1000 PRIOR_STAGE_ACCELERATION_LIMIT = 1000 # PI V-308 / C-414 focus drive used as the main Z (wraps the configured XY stage) USE_PI_FOCUS_STAGE = False SIMULATE_PI_FOCUS_STAGE = False PI_FOCUS_STAGE_SN = "" # FTDI/USB EEPROM serial (e.g. "1UETR6I!") -> resolved to a port PI_FOCUS_SERIAL_PORT = "" # explicit port fallback (e.g. /dev/ttyUSB0, COM5) PI_FOCUS_BAUDRATE = 115200 PI_FOCUS_AXIS = "1" PI_FOCUS_REFERENCE_ON_STARTUP = True # FRF on bring-up -- MOVES the stage PI_FOCUS_VELOCITY_MM_S = 0.0 # >0 sets the closed-loop velocity; 0 keeps the controller default # Upright system: the V-308's native 0 is DOWN (objective toward the sample). Invert Z so Squid Z # increases toward the sample (Z+ = focus down) and Squid Z 0 = fully retracted; the mapping is # squid_z = (native positive travel limit) - native. PI_FOCUS_INVERT_Z = False # home()/retract drives Z to the stage's positive travel limit (furthest from the sample) instead # of OBJECTIVE_RETRACTED_POS_MM. Use this on an upright system where retract = objective UP. PI_FOCUS_HOME_TO_POSITIVE_LIMIT = False # Full physical Z travel (mm). On the C-414 qTMN/qTMX ARE the Position Range Limit, so fencing # shrinks them permanently (until power cycle); >0 restores [0, this] at connect so the inversion # offset / soft-limit fencing don't drift across software restarts. Set to the V-308's travel (7). PI_FOCUS_Z_TRAVEL_MM = 0.0 # On-target window (half-width) per Z move, written to the C-414's RAM: STEP_FRACTION x the move # distance, clamped to [MIN, MAX] um. A move counts as finished once Z stays inside the window for the # controller's dwell time, so small steps need a window well below the step (the controller's own # +/-1 um calls a 0.5-1 um step done before it moves) while long moves can be more forgiving. # Defaults: 0.5-1 um steps +/-0.1 um, 3 um +/-0.3 um, >=5 um +/-0.5 um. MIN = 0 keeps the controller's window. PI_FOCUS_ON_TARGET_TOL_MIN_UM = 0.1 PI_FOCUS_ON_TARGET_TOL_MAX_UM = 0.5 PI_FOCUS_ON_TARGET_TOL_STEP_FRACTION = 0.1 # Pause after a Z move before imaging, replacing SCAN_STABILIZATION_TIME_MS_Z for the V-308: its moves already # wait for on-target inside the window above. Ignored (SCAN_STABILIZATION_TIME_MS_Z applies) when the window is # disabled (PI_FOCUS_ON_TARGET_TOL_MIN_UM = 0). PI_FOCUS_SCAN_STABILIZATION_TIME_MS_Z = 0 # Settle after a V-308 move no larger than its on-target window (e.g. a 0.05 um step with the 0.1 um minimum): # such a move is "on target" before Z moves, so the on-target wait cannot cover it and this fixed pause does. # 20 ms matches what these steps got before (+-1 um on-target, then SCAN_STABILIZATION_TIME_MS_Z). Measured on a # V-308 with the 2026-10-20 gains, a 0.05 um step is ~14% done after 20 ms, ~70% after 100 ms and done after # 200 ms (slow integrator creep): raise this for sub-0.1 um stacks, or tune the creep. PI_FOCUS_SUB_WINDOW_SETTLE_MS = 20 # The C-414's profile generator is switched off across a manual objective swap, holding its setpoint at the # pre-swap focus (squid.stage.pi.C414FocusStage.freeze_profile). The setpoint is kept here while it is off, so a # restart after Squid stopped mid-swap still knows where to switch it back on. PI_FOCUS_PROFILE_STATE_PATH = "cache/pi_focus_profile.json" # When neither of the above applies, Z retracts to OBJECTIVE_RETRACTED_POS_MM (the existing Squid # retract constant) on home() and before XY homing -- set that for the objective-clear position. # Z lift: on an upright system with a PI V-308 as the focus Z, the Cephla Z stepper lifts the XY stage and the sample. # It lowers (homes, to its bottom sensor) before XY homing and before the loading position, by Z_LIFT_SWAP_LOWER_MM for # a manual objective swap (fully, for a changer switch to a higher magnification), and the control panel's focus wheel then drives the V-308 instead (firmware >= 1.8). # Needs USE_PI_FOCUS_STAGE. The stepper's pitch / microstepping / current / sign come from the Z axis settings; its # travel is Z_LIFT_MIN_MM..Z_LIFT_MAX_MM (Z_AXIS MIN/MAX_POSITION describe the V-308 on such a system). USE_Z_LIFT_STAGE = False Z_LIFT_MIN_MM = 0.0 Z_LIFT_MAX_MM = 10.0 # Where "lowered" is. Homing ends at 0 (the bottom sensor); a lowered position above it skips re-homing. Z_LIFT_LOWERED_MM = 0.0 # A manual objective swap (V-308 servo released) lowers the lift by this much, whatever the magnification (not below # Z_LIFT_MIN_MM), and raises it back to where it was once the servo holds Z again. Z_LIFT_SWAP_LOWER_MM = 5.0 # The lift's working height per sample format, edited in the Z Lift window (Utils). Z_LIFT_HEIGHTS_PATH = "cache/z_lift_heights.json" # Written while the stage is at the loading position (Z lift systems), with the Z and lift height to return to: # Squid closed there starts again at the loading position, locked, instead of raising the lift. Z_LIFT_LOADING_STATE_PATH = "cache/z_lift_loading_state.json" # Route the control panel's focus wheel to the V-308 (the lift is then moved only from the software). Z_LIFT_FOCUS_WHEEL_DRIVES_PI = True # V-308 travel per focus wheel count, in um. The control panel sends 2^(Z sensitivity knob, 0-8) / 4 counts per encoder # click, in multiples of 16 (made for the 16-microstep Z stepper), so 0.00625 makes its smallest step 0.1 um: about # 0.4 um per click at knob 8, 0.1 um per 4 clicks at knob 4. 0 = one Z stepper microstep per count (far too coarse # for the V-308: 20 um per click at knob 8 on the 1 mm-pitch lift). PI_FOCUS_WHEEL_UM_PER_TICK = 0.00625 PI_FOCUS_WHEEL_INVERT = False # Fastest the focus wheel moves the V-308, in um/s; turning faster drops the extra ticks (Z stops with the wheel). # 0 = no cap. Autofocus, z-stacks and other moves keep the V-308's own speed. PI_FOCUS_WHEEL_MAX_SPEED_UM_S = 2000.0 # camera blacklevel settings DISPLAY_TOUPCAMER_BLACKLEVEL_SETTINGS = False # Toupcam global reset mode: every row starts exposing at once, so hardware-triggered frames need no # rolling-shutter strobe delay. Used in hardware trigger mode only, the one mode where the illumination is pulsed # for just the exposure (see ToupcamCamera._set_global_reset for why). Needs a camera that supports the option # (eg: the ITR10CMOS26000KMA); on other cameras it is ignored. ENABLE_TOUPCAM_GLOBAL_RESET = False class HardwareTriggerMode: EDGE = 0 # Fixed pulse width (TRIGGER_PULSE_LENGTH_us) LEVEL = 1 # Variable pulse width (illumination_on_time) HARDWARE_TRIGGER_MODE = HardwareTriggerMode.EDGE # Opt-in: put the sensor into GLOBAL RESET mode while hardware triggering in LEVEL mode. # # In the default rolling-shutter model, rows start exposing one after another, so the host # waits a strobe delay (~rows x line interval) until the LAST row has started before firing # the illumination. In global reset every row starts exposing at the trigger, so that # per-frame wait collapses to the camera's fixed trigger latency. Readout is still rolling, # so the illumination must be strobed and OFF before readout begins. # # Only has an effect together with HARDWARE_TRIGGER_MODE = LEVEL and a camera in the # HARDWARE trigger acquisition mode. Drivers read the mode back from the camera and raise # rather than fall back to rolling timing, which would fire the strobe before the last rows # are exposing, and put the previous trigger mode back. A camera that does not support global # reset does not open while this is on. HARDWARE_TRIGGER_GLOBAL_RESET = False # Opt-in: have the camera drive a "trigger ready" output the controller can gate the next # trigger on (Hamamatsu: output trigger connector 1; ToupCam: GPIO1, "Frame Trigger Wait"). # Only configured while the camera is in the HARDWARE trigger acquisition mode; a camera # without such an output does not open while this is on. # ACTIVE LOW on both: the controller's ready input is pulled up, so an unplugged cable reads # HIGH, and HIGH has to mean NOT ready. With the setting off nothing changes -- the ToupCam # driver keeps driving GPIO1 (active high) in EDGE mode only, as it always has. CAMERA_TRIGGER_READY_OUTPUT = False def use_level_trigger_global_reset() -> bool: """True when the opt-in LEVEL trigger + global reset exposure model is in effect. Reads the live module globals, so it sees values loaded from the .ini (and any runtime override) rather than a stale `from control._def import *` binding. """ return bool(HARDWARE_TRIGGER_GLOBAL_RESET) and HARDWARE_TRIGGER_MODE == HardwareTriggerMode.LEVEL def read_objectives_csv(file_path): objectives = {} with open(file_path, "r") as csvfile: reader = csv.DictReader(csvfile) for row in reader: objectives[row["name"]] = { "magnification": float(row["magnification"]), "NA": float(row["NA"]), "tube_lens_f_mm": float(row["tube_lens_f_mm"]), } return objectives # On-disk column order for sample_formats.csv. Single source of truth for both the # reader and the writer below, so the two cannot drift apart. This schema is # FROZEN at these 10 columns: per-axis geometry and well shape are derived # in-memory (below) and, when a format genuinely differs from the defaults, # persisted in the user-formats YAML - never here. SAMPLE_FORMAT_CSV_FIELDNAMES = ( "format", "a1_x_mm", "a1_y_mm", "a1_x_pixel", "a1_y_pixel", "well_size_mm", "well_spacing_mm", "number_of_skip", "rows", "cols", ) # In-memory keys derived from the 10 CSV columns; never written back to the CSV # (the writer skips them without warning). well_spacing_x_mm multiplies the # COLUMN index and well_spacing_y_mm the ROW index; ANSI/SLAS pitch is identical # in both axes for every shipped format, so the scalar broadcasts. DERIVED_SAMPLE_FORMAT_KEYS = ( "well_spacing_x_mm", "well_spacing_y_mm", "well_size_x_mm", "well_size_y_mm", "well_shape", ) # Well shape was previously inferred from the format NAME at scattered call # sites (384/1536 -> Square, everything else -> Circle) - which silently # misclassified any custom rectangular format as a circle. This is the one # code-side default; formats defined in the user YAML can override it. _RECTANGULAR_SHIPPED_FORMATS = ("384 well plate", "1536 well plate") def _with_derived_geometry(format_key, settings): """Fill the derived per-axis/shape keys, idempotently. Applied on CSV load AND in get_wellplate_settings, so runtime-added custom formats and format "0" (plain dicts) get defaults too. """ settings.setdefault("well_spacing_x_mm", settings["well_spacing_mm"]) settings.setdefault("well_spacing_y_mm", settings["well_spacing_mm"]) settings.setdefault("well_size_x_mm", settings["well_size_mm"]) settings.setdefault("well_size_y_mm", settings["well_size_mm"]) settings.setdefault("well_shape", "rectangle" if format_key in _RECTANGULAR_SHIPPED_FORMATS else "circle") return settings def _overlay_legacy_cache(cached, shipped, cached_formats_path): """The legacy cache was a whole-table shadow of the shipped catalog, but a row can be missing: a write interrupted after some complete rows parses as a shorter, plausible table, and every cache was written by an OLDER build - the catalog has grown since (the glass slide row, 2024), so a cache can legitimately predate a shipped format. Either way a missing row is the shipped example, exactly what a never-calibrated format is; the rows that survived keep their calibrations instead of all being thrown away.""" missing = [key for key in shipped if key not in cached] if not cached: log.error(f"{cached_formats_path} parsed to zero formats (truncated); the shipped geometry is used.") elif missing: log.warning( f"{cached_formats_path} lacks {missing} - truncated, or written before these formats shipped; " f"the shipped geometry is used for them." ) return {**shipped, **cached} def read_sample_formats_csv(file_path): sample_formats = {} with open(file_path, "r") as csvfile: reader = csv.DictReader(csvfile) for row in reader: format_ = str(row["format"]) format_key = f"{format_} well plate" if format_.isdigit() else format_ sample_formats[format_key] = _with_derived_geometry( format_key, { "a1_x_mm": float(row["a1_x_mm"]), "a1_y_mm": float(row["a1_y_mm"]), "a1_x_pixel": int(row["a1_x_pixel"]), "a1_y_pixel": int(row["a1_y_pixel"]), "well_size_mm": float(row["well_size_mm"]), "well_spacing_mm": float(row["well_spacing_mm"]), "number_of_skip": int(row["number_of_skip"]), "rows": int(row["rows"]), "cols": int(row["cols"]), }, ) return sample_formats def write_sample_formats_csv(file_path, sample_formats): """Write sample formats to file_path atomically. The caller's previous file survives any failure intact: we write a sibling temp file, fsync it, then os.replace() onto the target. That matters because load_formats() parses this file at import time, so a half-written file would prevent the application from starting. """ directory = os.path.dirname(file_path) if directory: os.makedirs(directory, exist_ok=True) # Same directory as the target so os.replace() stays within one filesystem. tmp_path = file_path + ".tmp" try: with open(tmp_path, "w", newline="") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=SAMPLE_FORMAT_CSV_FIELDNAMES) writer.writeheader() for format_, settings in sample_formats.items(): # Project explicitly onto the known columns. A missing column raises # (a blank cell is what breaks load_formats() at import time); an # extra key is dropped, but never silently - if you add a setting you # must add it to SAMPLE_FORMAT_CSV_FIELDNAMES or it will not persist. dropped = set(settings) - set(SAMPLE_FORMAT_CSV_FIELDNAMES) - set(DERIVED_SAMPLE_FORMAT_KEYS) if dropped: log.warning( f"Sample format {format_!r} has setting(s) {sorted(dropped)} with no column in " f"SAMPLE_FORMAT_CSV_FIELDNAMES; they will NOT be saved to {file_path}." ) row = {"format": format_} for field in SAMPLE_FORMAT_CSV_FIELDNAMES[1:]: row[field] = settings[field] writer.writerow(row) csvfile.flush() os.fsync(csvfile.fileno()) os.replace(tmp_path, file_path) except BaseException: try: os.unlink(tmp_path) except OSError: pass raise def _migrate_legacy_format_cache(cached, shipped, cached_formats_path): """Convert a legacy cache/sample_formats.csv (already parsed and overlaid on the shipped table) into user format definitions. The legacy cache was a WHOLE-TABLE shadow: one calibration froze all seven formats forever. Each row that differs from the shipped example becomes a COMPLETE definition in sample_formats_user.yaml (a1 included, absolutely); rows the shipped catalog does not know become definitions too. Rows identical to the shipped example are dropped - they carry no user intent and keeping them would needlessly stop tracking future shipped examples. The cache is then renamed .migrated. Existing entries in the user file are never clobbered (they are newer than the cache). """ import datetime from control.models.sample_format_config import ( FormatMeasurement, load_user_sample_formats_for_edit, MeasuredPoint, SampleFormat, save_user_sample_formats, ) mtime = datetime.datetime.fromtimestamp(os.path.getmtime(cached_formats_path)).isoformat(timespec="seconds") user_formats = load_user_sample_formats_for_edit() # raises on a damaged file: the cache keeps working migrated = [] for format_key, cached_settings in cached.items(): if format_key in user_formats.formats: continue # the user file is newer than the cache shipped_settings = shipped.get(format_key) if shipped_settings is not None and all( cached_settings[field] == shipped_settings[field] for field in SAMPLE_FORMAT_CSV_FIELDNAMES if field != "format" ): continue # untouched example: nothing of the user's to carry over a1_measured = shipped_settings is None or ( cached_settings["a1_x_mm"] != shipped_settings["a1_x_mm"] or cached_settings["a1_y_mm"] != shipped_settings["a1_y_mm"] ) # from_settings is the ONE dict -> model converter: cached_settings has # already been through _with_derived_geometry, so per-axis pitch and # well_shape come across too. Hand-listing the CSV's 10 columns here # silently dropped well_shape, migrating 384/1536 to "circle". user_formats.formats[format_key] = SampleFormat.from_settings( cached_settings, measured=( FormatMeasurement( points=[MeasuredPoint(well="A1", x_mm=cached_settings["a1_x_mm"], y_mm=cached_settings["a1_y_mm"])], method="migrated", timestamp=mtime, note=f"migrated_from_cache_csv (cache mtime {mtime})", ) if a1_measured else None ), ) migrated.append(format_key) save_user_sample_formats(user_formats) os.replace(cached_formats_path, cached_formats_path + ".migrated") log.info( f"Legacy format cache migrated ({len(migrated)} format(s): {sorted(migrated)}) and renamed to " f"{cached_formats_path}.migrated; definitions now load from sample_formats_user.yaml." ) def load_formats(): """Load formats, prioritizing cache for sample formats.""" cache_path = "cache" default_path = "objective_and_sample_formats" # Load objectives (from default location) objectives = read_objectives_csv(os.path.join(default_path, "objectives.csv")) # Try cache first for sample formats, fall back to default if not found cached_formats_path = os.path.join(cache_path, "sample_formats.csv") default_formats_path = os.path.join(default_path, "sample_formats.csv") shipped = read_sample_formats_csv(default_formats_path) # the base on every path sample_formats = None if os.path.exists(cached_formats_path): # Never propagate: this runs at import time, so raising here means the # application cannot start at all. try: cached = _overlay_legacy_cache(read_sample_formats_csv(cached_formats_path), shipped, cached_formats_path) except Exception: log.exception( f"Cached sample formats at {cached_formats_path} are unreadable. Falling back to the shipped " f"geometry in {default_formats_path} - ANY PLATE CALIBRATION STORED IN THE CACHE IS NOT BEING " f"APPLIED, so stage positions will differ from your last session. Move the file aside and " f"recalibrate to clear this." ) else: # One-time, idempotent migration of the legacy whole-table cache into # complete per-format definitions in the user YAML. Renames the cache # to .migrated on success so it never runs twice; on any failure the # cache is left in place and keeps working as before. try: _migrate_legacy_format_cache(cached, shipped, cached_formats_path) except Exception: log.exception( f"Migration of {cached_formats_path} failed; keeping the legacy cache as-is. " f"Calibrations continue to load from it." ) sample_formats = cached log.info(f"Using cached sample formats from {cached_formats_path}") if sample_formats is None: sample_formats = shipped # Layer the user's format edits and custom formats on top of the base # (shipped catalog, or the legacy whole-table cache until it is migrated). # Imported here because control.models imports pydantic; keep _def importable # even if that stack is broken - the identity default is "no user file". try: from control.models.sample_format_config import apply_user_sample_formats, load_user_sample_formats apply_user_sample_formats(sample_formats, load_user_sample_formats()) except Exception: log.exception("Failed to load sample_formats_user.yaml; continuing without user format edits.") return objectives, sample_formats OBJECTIVES_CSV_PATH = "objectives.csv" SAMPLE_FORMATS_CSV_PATH = "sample_formats.csv" OBJECTIVES, WELLPLATE_FORMAT_SETTINGS = load_formats() def get_wellplate_settings(wellplate_format): if wellplate_format in WELLPLATE_FORMAT_SETTINGS: settings = _with_derived_geometry(wellplate_format, WELLPLATE_FORMAT_SETTINGS[wellplate_format]) elif wellplate_format == "0": settings = _with_derived_geometry( "0", { "format": "0", "a1_x_mm": 0, "a1_y_mm": 0, "a1_x_pixel": 0, "a1_y_pixel": 0, "well_size_mm": 0, "well_spacing_mm": 0, "number_of_skip": 0, "rows": 1, "cols": 1, }, ) else: raise ValueError( f"Invalid wellplate format: {wellplate_format}. Expected formats are: {list(WELLPLATE_FORMAT_SETTINGS.keys())} or '0'" ) return settings # home safety margin with (um) unit X_HOME_SAFETY_MARGIN_UM = 50 Y_HOME_SAFETY_MARGIN_UM = 50 Z_HOME_SAFETY_MARGIN_UM = 100 # safety homing point (um) unit # after homing process, move axis to the # safety point X_HOME_SAFETY_POINT = 0 Y_HOME_SAFETY_POINT = 0 Z_HOME_SAFETY_POINT = 1200 USE_XERYON = False XERYON_SERIAL_NUMBER = "95130303033351E02050" XERYON_SPEED = 80 XERYON_OBJECTIVE_SWITCHER_POS_1 = ["4x", "10x"] XERYON_OBJECTIVE_SWITCHER_POS_2 = ["20x", "40x", "60x"] XERYON_OBJECTIVE_SWITCHER_POS_2_OFFSET_MM = 2 def xeryon_objective_position(objective_name): """Position index (1 or 2) of an objective on the Xeryon 2-position switcher, or None if the objective is not in either per-machine position list. Single source of the objective->position rule for both the hardware mover and the parfocal Z math (position 2 parks the stage POS_2_OFFSET_MM lower).""" if objective_name in XERYON_OBJECTIVE_SWITCHER_POS_1: return 1 if objective_name in XERYON_OBJECTIVE_SWITCHER_POS_2: return 2 return None # Motorized 4-position objective turret (NiMotion RS-485 stepper, Modbus-RTU) USE_OBJECTIVE_TURRET = False OBJECTIVE_TURRET_SERIAL_NUMBER = "" OBJECTIVE_TURRET_SLAVE_ID = 1 OBJECTIVE_TURRET_BAUDRATE = 115200 # Objective name -> turret slot index (1..4). Override per machine in .ini. OBJECTIVE_TURRET_POSITIONS = {"4x": 1, "10x": 2, "20x": 3, "40x": 4} # Pulse offset of slot 1 from the homing zero (the origin sensor's trigger edge); # the other slots follow at exactly 90-degree spacing. 0 on all normal units; set # per machine (may be negative). Software homing (2026-07) moved the zero slightly # vs the old driver homing — re-measure after upgrading a machine with an old value. OBJECTIVE_TURRET_OFFSET_PULSES = 0 # Gear backlash compensation in turret degrees (0..1, 0 disables). When > 0 every # slot change first overshoots below the target by this angle and then approaches # it from below, so the final approach direction is always the same and gear # backlash cancels out. OBJECTIVE_TURRET_BACKLASH_DEG = 0.0 # Set True for turret motor models wired with the opposite phase order (same # commands spin the other way). The controller then negates move targets, jog # signs and the homing-sweep direction bit, and flips position readbacks, so # slot mapping, offset and backlash logic keep working in the same logical # coordinate system — OBJECTIVE_TURRET_OFFSET_PULSES is always logical-coordinate # pulses. After toggling on an existing machine, re-home and re-measure the # offset: the physical zero moves with the sweep direction. OBJECTIVE_TURRET_DIRECTION_INVERTED = False # Set True for objective changers whose origin-switch sensor triggers on the # opposite logic level (port of SingleMotor's "原点开关极性取反" option, 2026-08-12). # Software homing / distance search then invert the DI1 trigger verdict, so the # homing direction and the sweep-backoff-fine-search state machine stay unchanged. # Toggling on an existing machine requires re-homing: the sensor edge found by # fine search (and thus the physical zero) sits on the other side of the window. OBJECTIVE_TURRET_DI_INVERT = False def _validate_objective_changer_flags(use_xeryon: bool, use_turret: bool) -> None: if use_xeryon and use_turret: raise ValueError( "USE_XERYON and USE_OBJECTIVE_TURRET are mutually exclusive " "(set only one to True in the machine .ini)" ) def _resolve_laser_engine(laser_engine, laser_engine_sn, use_squid_laser_engine, squid_laser_engine_sn) -> tuple: """(LASER_ENGINE, LASER_ENGINE_SN) from the machine .ini: laser_engine = v1 | v2 (blank / none = no engine) and laser_engine_sn, plus the legacy v1 keys use_squid_laser_engine / squid_laser_engine_sn. Raises ValueError for an unknown laser_engine and for use_squid_laser_engine = True together with laser_engine = v2.""" engine = None if laser_engine is None else str(laser_engine).strip().lower() if engine in ("", "none"): engine = None if engine is not None and engine not in ("v1", "v2"): raise ValueError( f"laser_engine = {laser_engine!r} in the machine .ini: use v1, v2, or leave it blank (no laser engine)" ) if use_squid_laser_engine: if engine == "v2": raise ValueError( "use_squid_laser_engine = True (the v1 engine) contradicts laser_engine = v2 in the machine .ini: " "remove use_squid_laser_engine" ) if engine is None: log.warning( "use laser_engine = v1 (and laser_engine_sn) instead of use_squid_laser_engine (and squid_laser_engine_sn)" ) engine = "v1" sn = None if laser_engine_sn in (None, "") else laser_engine_sn if sn is None and engine == "v1": sn = squid_laser_engine_sn return engine, sn # fluidics RUN_FLUIDICS = False FLUIDICS_CONFIG_PATH = "machine_configs/fluidics_config.yaml" # the library's FluidicsConfig YAML USE_TEMPLATE_MULTIPOINT = False FILE_SAVING_OPTION = FileSavingOption.INDIVIDUAL_IMAGES # TIFF saving configuration: 0 writes uncompressed TIFFs, 1-9 pick the zlib compression level # (higher = smaller files, slower writes). Applies to INDIVIDUAL_IMAGES and MULTI_PAGE_TIFF; # OME-TIFF stacks are written through a memory map, which requires an uncompressed file. TIFF_COMPRESSION_LEVEL = 0 def tiff_compression_level_from_config(value) -> int: """The TIFF compression level for a value from the machine config. A bad value must neither keep the software from starting nor fail every image write: out of range is limited to 0-9, and anything that isn't a number means uncompressed. """ try: level = int(value) except (TypeError, ValueError): log.warning(f"tiff_compression_level = {value!r} is not a number, TIFFs will be saved uncompressed") return 0 return min(max(level, 0), 9) # Zarr v3 saving configuration ZARR_CHUNK_MODE = ZarrChunkMode.FULL_FRAME ZARR_COMPRESSION = ZarrCompression.FAST # Safe for 10-20 fps, ~1000 MB/s encode # Use 6D array with FOV dimension for non-HCS acquisitions (non-standard, not OME-NGFF compliant) # When False (default): creates per-FOV 5D zarr files (OME-NGFF compliant) # When True: creates single 6D zarr with shape (FOV, T, C, Z, Y, X) ZARR_USE_6D_FOV_DIMENSION = False ########################################################## #### start of loading machine specific configurations #### ########################################################## CACHED_CONFIG_FILE_PATH = None # Piezo configuration items Z_MOTOR_CONFIG = ZMotorConfig.STEPPER # the value of OBJECTIVE_PIEZO_CONTROL_VOLTAGE_RANGE is 2.5 or 5 OBJECTIVE_PIEZO_CONTROL_VOLTAGE_RANGE = 5 OBJECTIVE_PIEZO_RANGE_UM = 300 OBJECTIVE_PIEZO_HOME_UM = 20 OBJECTIVE_PIEZO_FLIP_DIR = False MULTIPOINT_PIEZO_DELAY_MS = 20 # Opt-in: hardware-sequenced acquisition (controller firmware >= 1.7). The microcontroller runs a # whole multichannel piezo z-stack at each position from one uploaded program instead of the host # commanding every z move, illumination switch and trigger. Decided once per acquisition; when an # acquisition is not eligible it runs software-sequenced exactly as before and the log says why. USE_HARDWARE_SEQUENCED_ACQUISITION = False # Gate each trigger on the camera's trigger-ready output (new controller: Teensy pin 18). Off = # the controller models readiness from SEQUENCER_CAMERA_READOUT_MS after each exposure instead. SEQUENCER_USE_CAMERA_READY_LINE = False SEQUENCER_CAMERA_READOUT_MS = 50.0 # The controller fails a run when a step waits this long (stack settle, camera ready). SEQUENCER_WAIT_TIMEOUT_S = 5.0 # Turn each channel's illumination on this long BEFORE its exposure starts (the light source's rise # time); the controller delays the trigger by it, so the exposure is unchanged and each frame costs # this much extra. Bench 2026-10-28: with 0 the 405 nm channel was 3.5 % dimmer at 1 ms exposure than # software-sequenced. 0 until the bench has measured the value that closes that gap (about 100 us). SEQUENCER_ILLUMINATION_LEAD_US = 0 MULTIPOINT_PIEZO_UPDATE_DISPLAY = True USE_TERMINAL_CONSOLE = False USE_JUPYTER_CONSOLE = False # MCP Control Server - allows external tools (like Claude Code) to control the microscope # When enabled, MCP-related menu items appear in Settings (Launch Claude Code, etc.) # The server itself starts on-demand when user clicks "Launch Claude Code" or enables it manually. # Security note: Server listens only on localhost (127.0.0.1). # The python_exec command is disabled by default and must be explicitly enabled in the GUI. ENABLE_MCP_SERVER_SUPPORT = True # Set to False to hide all MCP-related menu items CONTROL_SERVER_HOST = "127.0.0.1" CONTROL_SERVER_PORT = 5050 ANTHROPIC_API_KEY = None # Set via GUI (Settings > Set Anthropic API Key...) # Slack Notifications - send real-time notifications during acquisition class SlackNotifications: ENABLED = False BOT_TOKEN = None # Slack Bot Token (xoxb-...) for API access CHANNEL_ID = None # Slack Channel ID (C...) to post to NOTIFY_ON_ERROR = True NOTIFY_ON_TIMEPOINT_COMPLETE = True NOTIFY_ON_ACQUISITION_START = False NOTIFY_ON_ACQUISITION_FINISHED = True SEND_MOSAIC_SNAPSHOTS = True WATCHDOG_ENABLED = True # Standalone acquisition watchdog: alert on crash / hang / error / abort try: with open("cache/config_file_path.txt", "r") as file: for line in file: CACHED_CONFIG_FILE_PATH = line break except FileNotFoundError: CACHED_CONFIG_FILE_PATH = None UI_THEME = "classic" # [GENERAL] ui_theme: "classic" or "dark" config_files = glob.glob("." + "/" + "configuration*.ini") if config_files: if len(config_files) > 1: if CACHED_CONFIG_FILE_PATH in config_files: log.info(f"defaulting to last cached config file at '{CACHED_CONFIG_FILE_PATH}'") config_files = [CACHED_CONFIG_FILE_PATH] else: log.error("multiple machine configuration files found, the program will exit") sys.exit(1) log.info("load machine-specific configuration") # exec(open(config_files[0]).read()) cfp = ConfigParser() cfp.read(config_files[0]) _legacy_limit_switch_msg = legacy_limit_switch_warning(cfp) if _legacy_limit_switch_msg: log.warning(_legacy_limit_switch_msg) var_items = list(locals().keys()) for var_name in var_items: if type(locals()[var_name]) is type: continue varnamelower = var_name.lower() if varnamelower not in cfp.options("GENERAL"): continue value = cfp.get("GENERAL", varnamelower) actualvalue = conf_attribute_reader(value) locals()[var_name] = actualvalue for classkey in var_items: myclass = None classkeyupper = classkey.upper() pop_items = None try: pop_items = cfp.items(classkeyupper) except: continue if type(locals()[classkey]) is not type: continue myclass = locals()[classkey] populate_class_from_dict(myclass, pop_items) _validate_objective_changer_flags(USE_XERYON, USE_OBJECTIVE_TURRET) LASER_ENGINE, LASER_ENGINE_SN = _resolve_laser_engine( LASER_ENGINE, LASER_ENGINE_SN, USE_SQUID_LASER_ENGINE, SQUID_LASER_ENGINE_SN ) with open("cache/config_file_path.txt", "w") as file: file.write(config_files[0]) CACHED_CONFIG_FILE_PATH = config_files[0] else: log.warning("configuration*.ini file not found, defaulting to legacy configuration") config_files = glob.glob("." + "/" + "configuration*.txt") if config_files: if len(config_files) > 1: log.error("multiple machine configuration files found, the program will exit") sys.exit(1) log.info("load machine-specific configuration") exec(open(config_files[0]).read()) _validate_objective_changer_flags(USE_XERYON, USE_OBJECTIVE_TURRET) LASER_ENGINE, LASER_ENGINE_SN = _resolve_laser_engine( LASER_ENGINE, LASER_ENGINE_SN, USE_SQUID_LASER_ENGINE, SQUID_LASER_ENGINE_SN ) else: log.error("machine-specific configuration not present, the program will exit") sys.exit(1) import control.objectives_config as _objectives_config # leaf module, see its docstring def _apply_objectives_yaml(): """Rebind OBJECTIVES and the changer slot maps from machine_configs/objectives.yaml. Runs after the machine .ini is applied (its loop rebinds module globals, so anything derived earlier would be overwritten) and before DEFAULT_OBJECTIVE is resolved. Returns the config, or None when the file is absent: objectives.csv and the .ini maps stay in effect, exactly as before. """ global OBJECTIVES, OBJECTIVE_TURRET_POSITIONS, XERYON_OBJECTIVE_SWITCHER_POS_1, XERYON_OBJECTIVE_SWITCHER_POS_2 path = _objectives_config.OBJECTIVES_YAML_PATH config = _objectives_config.load_objectives_config(path) if config is None: return None _objectives_config.validate_objectives_config( config, use_xeryon=USE_XERYON, use_turret=USE_OBJECTIVE_TURRET, path=path ) OBJECTIVES = _objectives_config.to_objectives_dict(config) if config.changer.kind is _objectives_config.ChangerKind.NIMOTION_TURRET: OBJECTIVE_TURRET_POSITIONS = _objectives_config.to_turret_positions(config) elif config.changer.kind is _objectives_config.ChangerKind.XERYON: XERYON_OBJECTIVE_SWITCHER_POS_1, XERYON_OBJECTIVE_SWITCHER_POS_2 = _objectives_config.to_xeryon_lists(config) log.info(f"objectives from {path}: {list(OBJECTIVES)}; the .ini's objective changer maps are ignored") return config try: OBJECTIVES_CONFIG = _apply_objectives_yaml() except _objectives_config.ObjectivesConfigError as e: log.error(f"{e}{_objectives_config.restore_hint(_objectives_config.OBJECTIVES_YAML_PATH)}") sys.exit(1) def _default_objective_fallback(reason="the cached default objective is not mounted"): """Today's literal "20x" without objectives.yaml; with it, the lowest-magnification mounted objective. `reason` must be true for the caller's situation (e.g. there may be no cache file at all, in which case nothing was "not mounted").""" if OBJECTIVES_CONFIG is None: return "20x" fallback = min(OBJECTIVES, key=lambda name: OBJECTIVES[name]["magnification"]) log.warning(f"{reason}; starting on {fallback}") return fallback def get_mounting(objective_name): """(changer kind, slot): ("nimotion_turret", 1..4 or None), ("xeryon", 1, 2 or None) or ("none", None). Raises KeyError for an objective that is not in OBJECTIVES. """ if objective_name not in OBJECTIVES: raise KeyError(objective_name) if USE_OBJECTIVE_TURRET: return ("nimotion_turret", OBJECTIVE_TURRET_POSITIONS.get(objective_name)) if USE_XERYON: return ("xeryon", xeryon_objective_position(objective_name)) return ("none", None) def get_declared(objective_name): """Declared optics, model and serial (model and serial are "" without objectives.yaml). Raises KeyError for an objective that is not in OBJECTIVES. """ info = OBJECTIVES[objective_name] declared = { "magnification": info["magnification"], "na": info["NA"], "tube_lens_f_mm": info["tube_lens_f_mm"], "model": "", "serial": "", } if OBJECTIVES_CONFIG is not None: entry = next(o for o in OBJECTIVES_CONFIG.objectives if o.name == objective_name) declared["model"], declared["serial"] = entry.model, entry.serial return declared try: with open("cache/objective_and_sample_format.txt", "r") as f: cached_settings = json.load(f) DEFAULT_OBJECTIVE = ( cached_settings.get("objective") if cached_settings.get("objective") in OBJECTIVES else _default_objective_fallback() ) WELLPLATE_FORMAT = str(cached_settings.get("wellplate_format")) WELLPLATE_FORMAT = WELLPLATE_FORMAT + " well plate" if WELLPLATE_FORMAT.isdigit() else WELLPLATE_FORMAT if WELLPLATE_FORMAT not in WELLPLATE_FORMAT_SETTINGS: WELLPLATE_FORMAT = "96 well plate" except (FileNotFoundError, json.JSONDecodeError): DEFAULT_OBJECTIVE = _default_objective_fallback("no usable cached default objective") WELLPLATE_FORMAT = "96 well plate" NUMBER_OF_SKIP = WELLPLATE_FORMAT_SETTINGS[WELLPLATE_FORMAT][ "number_of_skip" ] # num rows/cols to skip on wellplate edge WELL_SIZE_MM = WELLPLATE_FORMAT_SETTINGS[WELLPLATE_FORMAT]["well_size_mm"] WELL_SPACING_MM = WELLPLATE_FORMAT_SETTINGS[WELLPLATE_FORMAT]["well_spacing_mm"] A1_X_MM = WELLPLATE_FORMAT_SETTINGS[WELLPLATE_FORMAT]["a1_x_mm"] # measured stage position - to update A1_Y_MM = WELLPLATE_FORMAT_SETTINGS[WELLPLATE_FORMAT]["a1_y_mm"] # measured stage position - to update A1_X_PIXEL = WELLPLATE_FORMAT_SETTINGS[WELLPLATE_FORMAT]["a1_x_pixel"] # coordinate on the png A1_Y_PIXEL = WELLPLATE_FORMAT_SETTINGS[WELLPLATE_FORMAT]["a1_y_pixel"] # coordinate on the png ########################################################## ##### end of loading machine specific configurations ##### ########################################################## # objective piezo Z_MOTOR_CONFIG = ZMotorConfig.convert_to_enum(Z_MOTOR_CONFIG) HAS_OBJECTIVE_PIEZO = Z_MOTOR_CONFIG.has_piezo() IS_PIEZO_ONLY = Z_MOTOR_CONFIG.is_piezo_only() MULTIPOINT_USE_PIEZO_FOR_ZSTACKS = HAS_OBJECTIVE_PIEZO # convert str to enum FILE_SAVING_OPTION = FileSavingOption.convert_to_enum(FILE_SAVING_OPTION) ZARR_CHUNK_MODE = ZarrChunkMode.convert_to_enum(ZARR_CHUNK_MODE) ZARR_COMPRESSION = ZarrCompression.convert_to_enum(ZARR_COMPRESSION) FOCUS_MEASURE_OPERATOR = FocusMeasureOperator.convert_to_enum(FOCUS_MEASURE_OPERATOR) DEFAULT_TRIGGER_MODE = TriggerMode.convert_to_var(DEFAULT_TRIGGER_MODE) TIFF_COMPRESSION_LEVEL = tiff_compression_level_from_config(TIFF_COMPRESSION_LEVEL) # saving path if not (DEFAULT_SAVING_PATH.startswith(str(Path.home()))): DEFAULT_SAVING_PATH = str(Path.home() / DEFAULT_SAVING_PATH.strip("/").strip("\\")) # Load Views settings from config file at startup # These values override the defaults above and are accessed via control._def.XXX if CACHED_CONFIG_FILE_PATH and os.path.exists(CACHED_CONFIG_FILE_PATH): try: _views_config = ConfigParser() _views_config.read(CACHED_CONFIG_FILE_PATH) if _views_config.has_section("VIEWS"): log.info("Loading Views settings from config file") if _views_config.has_option("VIEWS", "display_mosaic_view"): USE_NAPARI_FOR_MOSAIC_DISPLAY = _views_config.get("VIEWS", "display_mosaic_view").lower() in ( "true", "1", "yes", ) if _views_config.has_option("VIEWS", "save_downsampled_overview"): SAVE_DOWNSAMPLED_OVERVIEW = _views_config.get("VIEWS", "save_downsampled_overview").lower() in ( "true", "1", "yes", ) # Support both old and new config key names for backward compatibility if _views_config.has_option("VIEWS", "save_downsampled_well_images"): SAVE_DOWNSAMPLED_WELL_IMAGES = _views_config.get("VIEWS", "save_downsampled_well_images").lower() in ( "true", "1", "yes", ) elif _views_config.has_option("VIEWS", "generate_downsampled_well_images"): # Legacy config key SAVE_DOWNSAMPLED_WELL_IMAGES = _views_config.get( "VIEWS", "generate_downsampled_well_images" ).lower() in ("true", "1", "yes") if _views_config.has_option("VIEWS", "mosaic_view_target_pixel_size_um"): try: MOSAIC_VIEW_TARGET_PIXEL_SIZE_UM = _views_config.getfloat( "VIEWS", "mosaic_view_target_pixel_size_um" ) except ValueError: pass if _views_config.has_option("VIEWS", "mosaic_z_projection"): try: MOSAIC_Z_PROJECTION = ZProjectionMode.convert_to_enum( _views_config.get("VIEWS", "mosaic_z_projection") ) except ValueError: pass if _views_config.has_option("VIEWS", "enable_ndviewer"): ENABLE_NDVIEWER = _views_config.get("VIEWS", "enable_ndviewer").lower() in ("true", "1", "yes") if _views_config.has_option("VIEWS", "ndviewer_light_command"): NDVIEWER_LIGHT_COMMAND = _views_config.get("VIEWS", "ndviewer_light_command").strip() if _views_config.has_option("VIEWS", "record_snaps_in_history"): RECORD_SNAPS_IN_HISTORY = _views_config.get("VIEWS", "record_snaps_in_history").lower() in ( "true", "1", "yes", ) except Exception as e: log.warning(f"Failed to load Views settings from config: {e}") # Load GENERAL settings from config file try: _general_config = ConfigParser() _general_config.read(CACHED_CONFIG_FILE_PATH) if _general_config.has_section("GENERAL"): if _general_config.has_option("GENERAL", "enable_memory_profiling"): ENABLE_MEMORY_PROFILING = _general_config.get("GENERAL", "enable_memory_profiling").lower() in ( "true", "1", "yes", ) log.info(f"Loaded ENABLE_MEMORY_PROFILING={ENABLE_MEMORY_PROFILING} from config") if _general_config.has_option("GENERAL", "enable_click_to_move"): ENABLE_CLICK_TO_MOVE = _general_config.get("GENERAL", "enable_click_to_move").lower() in ( "true", "1", "yes", ) if _general_config.has_option("GENERAL", "live_view_z_step_um"): LIVE_VIEW_Z_STEP_UM = _general_config.getfloat("GENERAL", "live_view_z_step_um") if _general_config.has_option("GENERAL", "live_view_z_step_fast_um"): LIVE_VIEW_Z_STEP_FAST_UM = _general_config.getfloat("GENERAL", "live_view_z_step_fast_um") except Exception as e: log.warning(f"Failed to load GENERAL settings from config: {e}") # Load per-component simulation settings from config file def _parse_sim_setting(value_str): """Parse simulation setting: True (simulate) or False (real hardware).""" val = value_str.strip().lower() if val in ("true", "1", "yes", "simulate"): return True # Everything else (false, none, auto, unrecognized) = real hardware return False try: _sim_config = ConfigParser() _sim_config.read(CACHED_CONFIG_FILE_PATH) if _sim_config.has_section("SIMULATION"): if _sim_config.has_option("SIMULATION", "simulate_camera"): SIMULATE_CAMERA = _parse_sim_setting(_sim_config.get("SIMULATION", "simulate_camera")) log.info(f"Loaded SIMULATE_CAMERA={SIMULATE_CAMERA} from config") if _sim_config.has_option("SIMULATION", "simulate_microcontroller"): SIMULATE_MICROCONTROLLER = _parse_sim_setting(_sim_config.get("SIMULATION", "simulate_microcontroller")) log.info(f"Loaded SIMULATE_MICROCONTROLLER={SIMULATE_MICROCONTROLLER} from config") if _sim_config.has_option("SIMULATION", "simulate_spinning_disk"): SIMULATE_SPINNING_DISK = _parse_sim_setting(_sim_config.get("SIMULATION", "simulate_spinning_disk")) log.info(f"Loaded SIMULATE_SPINNING_DISK={SIMULATE_SPINNING_DISK} from config") if _sim_config.has_option("SIMULATION", "simulate_filter_wheel"): SIMULATE_FILTER_WHEEL = _parse_sim_setting(_sim_config.get("SIMULATION", "simulate_filter_wheel")) log.info(f"Loaded SIMULATE_FILTER_WHEEL={SIMULATE_FILTER_WHEEL} from config") if _sim_config.has_option("SIMULATION", "simulate_objective_changer"): SIMULATE_OBJECTIVE_CHANGER = _parse_sim_setting( _sim_config.get("SIMULATION", "simulate_objective_changer") ) log.info(f"Loaded SIMULATE_OBJECTIVE_CHANGER={SIMULATE_OBJECTIVE_CHANGER} from config") if _sim_config.has_option("SIMULATION", "simulate_laser_af_camera"): SIMULATE_LASER_AF_CAMERA = _parse_sim_setting(_sim_config.get("SIMULATION", "simulate_laser_af_camera")) log.info(f"Loaded SIMULATE_LASER_AF_CAMERA={SIMULATE_LASER_AF_CAMERA} from config") if _sim_config.has_option("SIMULATION", "simulate_fluidics"): SIMULATE_FLUIDICS = _parse_sim_setting(_sim_config.get("SIMULATION", "simulate_fluidics")) log.info(f"Loaded SIMULATE_FLUIDICS={SIMULATE_FLUIDICS} from config") except Exception as e: log.warning(f"Failed to load SIMULATION settings from config: {e}")