|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +from collections.abc import Mapping, Sequence |
| 4 | +from typing import Any, Final |
| 5 | +import ctypes |
| 6 | +import ctypes.util |
| 7 | +import os |
| 8 | +import tempfile |
| 9 | +import time |
| 10 | + |
| 11 | +import numpy |
| 12 | + |
| 13 | +from pvapy.hpc.adImageProcessor import AdImageProcessor |
| 14 | +from pvapy.utility.floatWithUnits import FloatWithUnits |
| 15 | +import pvaccess as pva |
| 16 | + |
| 17 | + |
| 18 | +def find_epics_db() -> None: |
| 19 | + if not os.environ.get('EPICS_DB_INCLUDE_PATH'): |
| 20 | + pvDataLib = ctypes.util.find_library('pvData') |
| 21 | + |
| 22 | + if pvDataLib: |
| 23 | + pvDataLib = os.path.realpath(pvDataLib) |
| 24 | + epicsLibDir = os.path.dirname(pvDataLib) |
| 25 | + dbdDir = os.path.realpath(f'{epicsLibDir}/../../dbd') |
| 26 | + os.environ['EPICS_DB_INCLUDE_PATH'] = dbdDir |
| 27 | + else: |
| 28 | + raise Exception('Cannot find dbd directory, please set EPICS_DB_INCLUDE_PATH' |
| 29 | + 'environment variable') |
| 30 | + |
| 31 | + |
| 32 | +def create_ca_ioc(pvseq: Sequence[str]) -> pva.CaIoc: |
| 33 | + # create database and start IOC |
| 34 | + dbFile = tempfile.NamedTemporaryFile(delete=False) |
| 35 | + dbFile.write(b'record(ao, "$(NAME)") {}\n') |
| 36 | + dbFile.close() |
| 37 | + |
| 38 | + ca_ioc = pva.CaIoc() |
| 39 | + ca_ioc.loadDatabase('base.dbd', '', '') |
| 40 | + ca_ioc.registerRecordDeviceDriver() |
| 41 | + |
| 42 | + for pv in pvseq: |
| 43 | + print(f'Creating CA ca record: {pv}') |
| 44 | + ca_ioc.loadRecords(dbFile.name, f'NAME={pv}') |
| 45 | + |
| 46 | + ca_ioc.start() |
| 47 | + os.unlink(dbFile.name) |
| 48 | + return ca_ioc |
| 49 | + |
| 50 | + |
| 51 | +class PixelStatisticsProcessor(AdImageProcessor): |
| 52 | + DESAT_PV: Final[str] = 'pvapy:desat' |
| 53 | + DESAT_KW: Final[str] = 'desat_threshold' |
| 54 | + SAT_PV: Final[str] = 'pvapy:sat' |
| 55 | + SAT_KW: Final[str] = 'sat_threshold' |
| 56 | + SUM_PV: Final[str] = 'pvapy:sum' |
| 57 | + |
| 58 | + def __init__(self, config_dict: Mapping[str, Any] = {}) -> None: |
| 59 | + super().__init__(config_dict) |
| 60 | + find_epics_db() |
| 61 | + |
| 62 | + self._desat_threshold = config_dict.get(self.DESAT_KW, 1) |
| 63 | + self._sat_threshold = config_dict.get(self.SAT_KW, 254) |
| 64 | + self._ca_ioc = pva.CaIoc() |
| 65 | + |
| 66 | + # statistics |
| 67 | + self.num_frames_processed = 0 |
| 68 | + self.processing_time_s = 0 |
| 69 | + |
| 70 | + def start(self) -> None: |
| 71 | + self._ca_ioc = create_ca_ioc([self.DESAT_PV, self.SAT_PV, self.SUM_PV]) |
| 72 | + self.logger.debug(self._ca_ioc.getRecordNames()) |
| 73 | + |
| 74 | + def configure(self, config_dict: Mapping[str, Any]) -> None: |
| 75 | + try: |
| 76 | + self._desat_threshold = int(config_dict[self.DESAT_KW]) |
| 77 | + except KeyError: |
| 78 | + pass |
| 79 | + except ValueError: |
| 80 | + self.logger.warning('Failed to parse desaturation threshold!') |
| 81 | + else: |
| 82 | + self.logger.debug(f'Desaturation threshold: {self._desat_threshold}') |
| 83 | + |
| 84 | + try: |
| 85 | + self._sat_threshold = int(config_dict[self.SAT_KW]) |
| 86 | + except KeyError: |
| 87 | + pass |
| 88 | + except ValueError: |
| 89 | + self.logger.warning('Failed to parse saturation threshold!') |
| 90 | + else: |
| 91 | + self.logger.debug(f'Saturation threshold: {self._sat_threshold}') |
| 92 | + |
| 93 | + def process(self, pvObject: pva.PvObject) -> pva.PvObject: |
| 94 | + t0 = time.time() |
| 95 | + |
| 96 | + (frameId, image, nx, ny, nz, colorMode, fieldKey) = self.reshapeNtNdArray(pvObject) |
| 97 | + |
| 98 | + if nx is None: |
| 99 | + self.logger.debug(f'Frame id {frameId} contains an empty image.') |
| 100 | + return pvObject |
| 101 | + |
| 102 | + desat_pixels = numpy.count_nonzero(image < self._desat_threshold) |
| 103 | + self._ca_ioc.putField(self.DESAT_PV, desat_pixels) |
| 104 | + |
| 105 | + sat_pixels = numpy.count_nonzero(image > self._sat_threshold) |
| 106 | + self._ca_ioc.putField(self.SAT_PV, sat_pixels) |
| 107 | + |
| 108 | + sum_pixels = image.sum() |
| 109 | + self._ca_ioc.putField(self.SUM_PV, sum_pixels) |
| 110 | + |
| 111 | + t1 = time.time() |
| 112 | + self.processing_time_s += (t1 - t0) |
| 113 | + |
| 114 | + return pvObject |
| 115 | + |
| 116 | + def stop(self) -> None: |
| 117 | + pass |
| 118 | + |
| 119 | + def resetStats(self) -> None: |
| 120 | + self.num_frames_processed = 0 |
| 121 | + self.processing_time_s = 0 |
| 122 | + |
| 123 | + def getStats(self) -> Mapping[str, Any]: |
| 124 | + processed_frame_rate_Hz = 0 |
| 125 | + |
| 126 | + if self.processing_time_s > 0: |
| 127 | + processed_frame_rate_Hz = self.num_frames_processed / self.processing_time_s |
| 128 | + |
| 129 | + return { |
| 130 | + 'num_frames_processed': self.num_frames_processed, |
| 131 | + 'processing_time_s': FloatWithUnits(self.processing_time_s, 's'), |
| 132 | + 'processed_frame_rate_Hz': FloatWithUnits(processed_frame_rate_Hz, 'fps'), |
| 133 | + } |
| 134 | + |
| 135 | + def getStatsPvaTypes(self) -> Mapping[str, Any]: |
| 136 | + return { |
| 137 | + 'num_frames_processed': pva.UINT, |
| 138 | + 'processing_time_s': pva.DOUBLE, |
| 139 | + 'processed_frame_rate_Hz': pva.DOUBLE, |
| 140 | + } |
0 commit comments