|
| 1 | +"""Subprocess worker that runs the ptychozoon (GPU VSPI) fluorescence enhancement. |
| 2 | +
|
| 3 | +This module is executed in a freshly ``spawn``ed process so that the CuPy GPU |
| 4 | +context is created cleanly and fully released when the process exits. It must not |
| 5 | +import ``ptychozoon`` (or CuPy) at module load time; the import happens inside the |
| 6 | +worker function so that the parent process never pulls GPU libraries into its own |
| 7 | +interpreter. |
| 8 | +
|
| 9 | +All data crosses the process boundary as plain numpy arrays and scalars (see |
| 10 | +:class:`PtychozoonPayload`). Messages are streamed back over a single queue as |
| 11 | +tagged tuples: |
| 12 | +
|
| 13 | +- ``('result', iteration, [(element_name, counts_per_second_array), ...])`` per checkpoint |
| 14 | +- ``('log', levelno, message)`` for each captured log record from the ptychozoon logger |
| 15 | +- ``('error', traceback_str)`` on failure |
| 16 | +
|
| 17 | +followed by a ``None`` sentinel. Because a single child thread produces every |
| 18 | +message, ordering is preserved (a log line arrives before the result it precedes). |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import logging |
| 24 | +from dataclasses import dataclass |
| 25 | +from multiprocessing.queues import Queue |
| 26 | +from typing import Any |
| 27 | + |
| 28 | +import numpy |
| 29 | + |
| 30 | +__all__ = [ |
| 31 | + 'PtychozoonPayload', |
| 32 | + 'run_vspi_enhancement', |
| 33 | +] |
| 34 | + |
| 35 | + |
| 36 | +class _QueueLogHandler(logging.Handler): |
| 37 | + """Logging handler that forwards formatted records to the parent over the result queue.""" |
| 38 | + |
| 39 | + def __init__(self, result_queue: 'Queue[Any]') -> None: |
| 40 | + super().__init__() |
| 41 | + self._result_queue = result_queue |
| 42 | + |
| 43 | + def emit(self, record: logging.LogRecord) -> None: |
| 44 | + try: |
| 45 | + self._result_queue.put(('log', record.levelno, self.format(record))) |
| 46 | + except Exception: |
| 47 | + # Never let logging failures break the enhancement worker. |
| 48 | + pass |
| 49 | + |
| 50 | + |
| 51 | +@dataclass(frozen=True) |
| 52 | +class PtychozoonPayload: |
| 53 | + """Picklable inputs for one ptychozoon enhancement run.""" |
| 54 | + |
| 55 | + # Ptychography product (plain arrays / scalars) |
| 56 | + probe_positions_m: numpy.ndarray # (N, 2) float [y, x] meters |
| 57 | + probe: numpy.ndarray # (n_opr, modes, height, width) complex |
| 58 | + object_array: numpy.ndarray # (height, width) complex |
| 59 | + pixel_size_m: tuple[float, float] # (pixel_height_m, pixel_width_m) |
| 60 | + object_center_m: tuple[float, float] # (center_y_m, center_x_m) |
| 61 | + opr_mode_weights: numpy.ndarray | None # (n_opr, N) float or None |
| 62 | + |
| 63 | + # Fluorescence element maps |
| 64 | + element_maps: list[tuple[str, numpy.ndarray]] # [(name, counts_per_second), ...] |
| 65 | + |
| 66 | + # Solver settings |
| 67 | + damping_factor: float |
| 68 | + gradient_smoothness: float |
| 69 | + max_iterations: int |
| 70 | + atol: float |
| 71 | + btol: float |
| 72 | + checkpoint_interval: int |
| 73 | + use_gpu: bool |
| 74 | + gpu_device_index: int |
| 75 | + |
| 76 | + # Effective log level of the parent's ptychozoon logger, so the child only |
| 77 | + # forwards records that the parent would actually surface. |
| 78 | + log_level: int |
| 79 | + |
| 80 | + |
| 81 | +def run_vspi_enhancement(payload: PtychozoonPayload, result_queue: 'Queue[Any]') -> None: |
| 82 | + """Run ptychozoon VSPI enhancement and stream checkpoint results over a queue. |
| 83 | +
|
| 84 | + Intended as the target of a ``spawn``ed ``multiprocessing.Process``. Puts |
| 85 | + ``('result', iteration, [(name, cps), ...])`` tuples per checkpoint and |
| 86 | + ``('log', levelno, message)`` tuples for ptychozoon log records, then ``None`` |
| 87 | + when complete, or ``('error', traceback_str)`` on failure. |
| 88 | + """ |
| 89 | + # Forward ptychozoon's own log output to the parent so it appears in the |
| 90 | + # Enhance Fluorescence status view (this process has no ptychodus handlers). |
| 91 | + log_handler = _QueueLogHandler(result_queue) |
| 92 | + log_handler.setFormatter(logging.Formatter('%(message)s')) |
| 93 | + ptychozoon_logger = logging.getLogger('ptychozoon') |
| 94 | + ptychozoon_logger.addHandler(log_handler) |
| 95 | + ptychozoon_logger.setLevel(payload.log_level) |
| 96 | + |
| 97 | + try: |
| 98 | + from ptychozoon.data_structures import ( |
| 99 | + ElementMap, |
| 100 | + FluorescenceDataset, |
| 101 | + PtychographyProduct, |
| 102 | + ) |
| 103 | + from ptychozoon.settings import ( |
| 104 | + DeconvolutionEnhancementSettings, |
| 105 | + InterpolationTypes, |
| 106 | + ) |
| 107 | + from ptychozoon.vspi_enhance import VSPIFluorescenceEnhancingAlgorithm |
| 108 | + |
| 109 | + product = PtychographyProduct( |
| 110 | + probe_positions=payload.probe_positions_m, |
| 111 | + probe=payload.probe, |
| 112 | + object_array=payload.object_array, |
| 113 | + pixel_size_m=payload.pixel_size_m, |
| 114 | + object_center_m=payload.object_center_m, |
| 115 | + opr_mode_weights=payload.opr_mode_weights, |
| 116 | + ) |
| 117 | + dataset = FluorescenceDataset( |
| 118 | + element_maps=[ |
| 119 | + ElementMap(name=name, counts_per_second=cps) for name, cps in payload.element_maps |
| 120 | + ] |
| 121 | + ) |
| 122 | + |
| 123 | + settings = DeconvolutionEnhancementSettings() |
| 124 | + settings.lsmr.damping_factor = payload.damping_factor |
| 125 | + settings.lsmr.gradient_smoothness = payload.gradient_smoothness |
| 126 | + settings.lsmr.max_iter = payload.max_iterations |
| 127 | + settings.lsmr.atol = payload.atol |
| 128 | + settings.lsmr.btol = payload.btol |
| 129 | + settings.lsmr.checkpoint_interval = payload.checkpoint_interval |
| 130 | + settings.gpu.enabled = payload.use_gpu |
| 131 | + settings.gpu.index = payload.gpu_device_index |
| 132 | + # Fourier interpolation requires the GPU; fall back to Barycentric on CPU. |
| 133 | + settings._interpolation = ( |
| 134 | + InterpolationTypes.FOURIER if payload.use_gpu else InterpolationTypes.BARYCENTRIC |
| 135 | + ) |
| 136 | + |
| 137 | + algorithm = VSPIFluorescenceEnhancingAlgorithm() |
| 138 | + |
| 139 | + for enhanced_dataset, iteration in algorithm.enhance(dataset, product, settings=settings): |
| 140 | + result_queue.put( |
| 141 | + ( |
| 142 | + 'result', |
| 143 | + int(iteration), |
| 144 | + [ |
| 145 | + (emap.name, numpy.asarray(emap.counts_per_second)) |
| 146 | + for emap in enhanced_dataset.element_maps |
| 147 | + ], |
| 148 | + ) |
| 149 | + ) |
| 150 | + except Exception: |
| 151 | + import traceback |
| 152 | + |
| 153 | + result_queue.put(('error', traceback.format_exc())) |
| 154 | + finally: |
| 155 | + ptychozoon_logger.removeHandler(log_handler) |
| 156 | + result_queue.put(None) |
0 commit comments