Skip to content

Physics & Measurement

These modules handle the core physical calculations.

Image Quality Measurement

flexpose.measure

Measure

Source code in flexpose/measure.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
class Measure:
    def __init__(self, config: dataformats.ConfigData, pixel_results: dict, dose_cls : dose.CalcDose, rng : np.random.Generator | None = None) -> None:
        """
        Initialize the Measure class with configuration, pixel results, dose calculator, and optional RNG

        Args:
            config (dataformats.ConfigData): Configuration data object
            pixel_results (dict): Pixel results data
            dose_cls (dose.CalcDose): Dose calculation class instance
            rng (np.random.Generator | None): Optional random number generator
        """
        self.config : dataformats.ConfigData =  config
        self.rng : np.random.Generator| None = rng
        self.pixel_results = pixel_results
        self.sampled_pixels : dict = {}
        self.dose : dose.CalcDose = dose_cls
        self._make_entrance_kerma_col()
        self.enoise = self.config.detector_data.e_noise
        self.npixels = self._calculate_npixels()

    def set_rng(self, rng : np.random.Generator | None) -> None:
        """
        Set the random number generator for reproducibility

        Args:
            rng (np.random.Generator | None): Random number generator instance
        """
        self.rng = rng

    def sample_pixels(self) -> None:
        """
        Sample pixel values from the provided pixel results
        """
        self.sampled_pixels = self._prepare_pixels(self.pixel_results)

    def _calculate_npixels(self) -> int:
        """
        Calculate the number of pixels in the object area

        Returns:
            int: Number of pixels.
        """
        object_size = self.config.object_data.size_xy
        pixel_size = self.config.detector_data.pixel_size
        sid = self.config.detector_data.sid
        sod = self.config.object_data.sod
        mag = sid/sod
        object_area = object_size[0]*object_size[1]*mag**2
        pixel_area = pixel_size[0]*pixel_size[1]
        npixels = int(object_area/pixel_area)
        return npixels

    def _make_entrance_kerma_col(self) -> np.ndarray:
        """
        Convert DAP to air kerma for optimization

        Returns:
            float: Calculated air kerma value
        """
        df = self.dose.export_df
        sid = self.config.detector_data.sid
        fov = self.config.xray_tube_data.fov
        ref_point = sid - 30
        new_fov = (ref_point/sid)*fov
        field_area = new_fov**2/2
        dap = df['DAP (Gycm2/mAs)'].to_numpy()
        kerma = dap*1E3/field_area
        return kerma

    def _select_region(self, quant: np.ndarray) -> np.ndarray:
        """
        Select the region of interest from the image based on SNR mode

        Args:
            quant (np.ndarray): Input image array

        Returns:
            np.ndarray: Selected region values
        """
        snr_mode = self.config.general_config.snr_mode
        image_size = quant.shape[1:]
        dy = image_size[0]
        dx = image_size[1]
        hy = dy//2
        hx = dx//2

        match snr_mode:
            case 'mean':
                quant = np.mean(quant, axis=(1,2))
            case 'median':
                quant = np.median(quant, axis=(1,2))
            case 'window':
                quant = np.mean(quant[:, hy-1:hy+1, hx-1:hx+1], axis=(1,2))
            case 'center':
                quant = quant[:, hy, hx]
            case _:
                raise NotImplementedError('SNR Mode not implemented yet')
        return quant

    def _convert_region_results(self, pixel_results: dict) -> dict:
        """
        Convert pixel results to target region results for all keys

        Args:
            pixel_results (dict): Pixel results data

        Returns:
            dict: Converted region results
        """
        pixel_results2 ={}
        for key, _ in pixel_results['imgs']['80 (kv)'].items():
            pixel_results2[key] = self._calculate_target_region(pixel_results, key)
        return pixel_results2

    def _sample_quantities(self, pixel_results2: dict) -> dict:
        """
        Sample pixel quantities using the random number generator if available

        Args:
            pixel_results2 (dict): Region results to sample

        Returns:
            dict: Sampled pixel quantities
        """
        if self.rng is None:
            return pixel_results2
        pixels_sampled = {}
        quantities = ['PV BG', 'PV P BG', 'PV OBJ', 'PV P OBJ', 'NOISE BG', 'NOISE OBJ', 'KERMA DET']
        kv_vec = self.config.spectrum_data.kv_vec
        for quantity in quantities:
            dict_quantity = {}
            for _, kv in enumerate(kv_vec):
                quantity_kv = pixel_results2[quantity][kv]
                quantity_unc_kv = pixel_results2[f'{quantity} Unc.'][kv]
                sampled = self.rng.normal(quantity_kv, quantity_unc_kv)
                dict_quantity[kv] = sampled
            pixels_sampled[quantity] = dict_quantity
        return pixels_sampled

    def _prepare_pixels(self, pixel_results: dict) -> dict:
        """
        Prepare sampled pixel data from raw pixel results

        Args:
            pixel_results (dict): Raw pixel results

        Returns:
            dict: Sampled pixel data
        """
        pixel_results2 = self._convert_region_results(pixel_results)
        pixels_sampled = self._sample_quantities(pixel_results2)
        return pixels_sampled

    def _calc_electronic_noise(self) -> float:
        """
        Retrieves from the config the electronic noise for the detector

        Returns:
            float: Electronic noise value for a single pixel
        """
        enoise = self.config.detector_data.e_noise

        return enoise

    def _calculate_target_region(self, pixel_results : dict, key : str) -> dict:
        """
        Calculate the target region for a given key across all kV values

        Args:
            pixel_results (dict): Pixel results data
            key (str): Key to extract region for

        Returns:
            dict: Target region values for each kV
        """
        kv_vec = self.config.spectrum_data.kv_vec
        imgs = pixel_results['imgs']
        img_shape = self.config.iq_data.img_shape
        quant_vec = np.zeros((len(kv_vec), img_shape[0], img_shape[1]))
        for idx, kv in enumerate(kv_vec):
            quant_map_kv = imgs[f'{kv} (kv)'][key]
            quant_vec[idx, :, :] = quant_map_kv
        quant_vec = self._select_region(quant_vec)
        quant_map = dict(zip(kv_vec, quant_vec))
        return quant_map   

    def calc_entrance_kerma(self, res: dict) -> dict:
        """
        Convert DAP to air kerma rate for constraints and add to results

        Args:
            res (dict): Results dictionary containing exposure parameters

        Returns:
            dict: Updated results with entrance kerma rate
        """
        kv = res['Potential (kV)']
        mas = res['ms']*res['mA']/1000
        df = self.dose.export_df
        sid = self.config.detector_data.sid
        fov = self.config.xray_tube_data.fov
        frame_rate = self.config.general_config.frame_rate
        ref_point = sid - 30

        old_side = fov/np.sqrt(2)
        new_side = old_side*(ref_point/sid)
        field_area = new_side**2

        dap = df.loc[df['Potential (kV)'] == kv]['DAP (Gycm2/mAs)'].values[0]
        if self.rng is not None:
            unc_dap = df.loc[df['Potential (kV)'] == kv]['DAP (Gycm2/mAs) Unc.'].values[0]
            dap = self.rng.normal(dap, unc_dap)
        kerma = dap*mas/field_area
        kerma_rate = kerma*frame_rate*1E3*60
        res['Entrance kerma (mGy/min)'] = kerma_rate
        return res

    def measure_contrast(self, kv: int) -> float:
        """
        Measure image contrast for a given kV value

        Args:
            kv (int): Tube potential (kV)

        Returns:
            float: Calculated contrast value
        """
        # we assume scatter is constant so for the numerator 
        # only p is used
        pv_bg = self.sampled_pixels['PV BG'][kv]
        pv_bg_p = self.sampled_pixels['PV P BG'][kv]
        pv_obj_p = self.sampled_pixels['PV P OBJ'][kv]
        contrast = (pv_bg_p - pv_obj_p)/(pv_bg + 1E-15)
        return contrast

    def measure_det_dose_bg(self, kv: int, t: float, ma: float) -> float:
        """
        Measure detector dose in background region

        Args:
            kv (int): Tube potential (kV)
            t (float): Exposure time
            ma (float): Tube current (mA)

        Returns:
            float: Detector dose in background.
        """
        det_dose  = self.sampled_pixels['PV BG'][kv]*t*ma
        return det_dose

    def measure_det_dose_bg_p(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
        """
        Measure detector dose for primary background region.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Detector dose for primary background.
        """
        det_dose  = self.sampled_pixels['PV P BG'][kv]*t*ma
        return det_dose

    def measure_det_dose_obj(self, kv: int, t: float, ma: float) -> float:
        """
        Measure detector dose (primary plus scatter) in object region.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Detector dose (primary plus scatter) in object region.
        """
        det_dose  = self.sampled_pixels['PV OBJ'][kv]*t*ma
        return det_dose

    def measure_det_dose_obj_p(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
        """
        Measure detector dose for primaries in the object region

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Detector dose for primaries in the object region
        """
        det_dose  = self.sampled_pixels['PV P OBJ'][kv]*t*ma
        return det_dose

    def measure_det_kerma(self, kv: int, t: float, ma: float) -> float:
        """
        Measure detector kerma for given exposure parameters.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Detector kerma value.
        """
        det_kerma  = self.sampled_pixels['KERMA DET'][kv]*t*ma
        return det_kerma

    def measure_pixel_noise_bg(self, kv: int, t: float, ma: float) -> float:
        """
        Measure pixel noise in background region.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Pixel noise in background.
        """
        quantum_noise = self.sampled_pixels['NOISE BG'][kv]
        quantum_noise = quantum_noise * np.sqrt(t*ma)
        return quantum_noise

    def measure_pixel_noise_obj(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
        """
        Measure pixel noise in object region.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Pixel noise in object region.
        """
        quantum_noise = self.sampled_pixels['NOISE OBJ'][kv]
        quantum_noise = quantum_noise * np.sqrt(t*ma)
        return quantum_noise

    def measure_noise(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
        """
        Measure total noise (quantum + electronic) for given exposure parameters.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Total noise value.
        """
        npixels = self.npixels
        quantum_noise = self.sampled_pixels['NOISE BG'][kv]
        quantum_noise = quantum_noise * np.sqrt(t*ma)

        electronic_noise = self._calc_electronic_noise()
        # retrieve the total noise
        total_noise = np.sqrt(quantum_noise**2 + electronic_noise**2)*np.sqrt(npixels)
        return total_noise

    def measure_snr(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
        """
        Measure signal-to-noise ratio (SNR) for given exposure parameters.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: SNR value.
        """
        pv_bg = self.measure_det_dose_bg_p(kv, t, ma)
        pv_obj = self.measure_det_dose_obj_p(kv, t, ma)
        npixels = self.npixels

        dif_signal = abs(pv_bg - pv_obj)*npixels

        total_noise = self.measure_noise(kv, t, ma)
        snr = dif_signal/total_noise
        return snr

    def calc_img_quality(self, kv: int, t: float, ma: float) -> dict:
        """
        Calculate image quality metrics for given exposure parameters.

        Args:
            kv (int): Tube potential (kV).
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            dict: Dictionary of image quality metrics.
        """
        snr = self.measure_snr(kv, t , ma)
        contrast = self.measure_contrast(kv)
        pv_bg = self.measure_det_dose_bg(kv, t, ma)
        pv_obj = self.measure_det_dose_obj(kv, t, ma)

        pv_bg_p = self.measure_det_dose_bg_p(kv, t, ma)

        noise_bg = self.measure_pixel_noise_bg(kv, t, ma)
        noise_obj = self.measure_pixel_noise_obj(kv, t, ma)

        det_kerma = self.measure_det_kerma(kv, t, ma)

        filtration = self.config.spectrum_data.filtration

        results = { 'Filtration' : filtration,
                    'Potential (kV)' : kv,
                   'ms' : t*1000,
                   'mA' : ma,
                   'SNR' : snr,
                   'Contrast' : contrast,
                   'PV BG' : pv_bg,
                   'PV OBJ' : pv_obj,
                   'PV BG P' : pv_bg_p,
                   'Noise BG' : noise_bg,
                   'Noise OBJ' : noise_obj,
                   'DET KERMA (nGy)' : det_kerma
                    }
        results = self.calc_entrance_kerma(results)
        return results

calc_entrance_kerma(res)

Convert DAP to air kerma rate for constraints and add to results

Parameters:

Name Type Description Default
res dict

Results dictionary containing exposure parameters

required

Returns:

Name Type Description
dict dict

Updated results with entrance kerma rate

Source code in flexpose/measure.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def calc_entrance_kerma(self, res: dict) -> dict:
    """
    Convert DAP to air kerma rate for constraints and add to results

    Args:
        res (dict): Results dictionary containing exposure parameters

    Returns:
        dict: Updated results with entrance kerma rate
    """
    kv = res['Potential (kV)']
    mas = res['ms']*res['mA']/1000
    df = self.dose.export_df
    sid = self.config.detector_data.sid
    fov = self.config.xray_tube_data.fov
    frame_rate = self.config.general_config.frame_rate
    ref_point = sid - 30

    old_side = fov/np.sqrt(2)
    new_side = old_side*(ref_point/sid)
    field_area = new_side**2

    dap = df.loc[df['Potential (kV)'] == kv]['DAP (Gycm2/mAs)'].values[0]
    if self.rng is not None:
        unc_dap = df.loc[df['Potential (kV)'] == kv]['DAP (Gycm2/mAs) Unc.'].values[0]
        dap = self.rng.normal(dap, unc_dap)
    kerma = dap*mas/field_area
    kerma_rate = kerma*frame_rate*1E3*60
    res['Entrance kerma (mGy/min)'] = kerma_rate
    return res

calc_img_quality(kv, t, ma)

Calculate image quality metrics for given exposure parameters.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
dict dict

Dictionary of image quality metrics.

Source code in flexpose/measure.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def calc_img_quality(self, kv: int, t: float, ma: float) -> dict:
    """
    Calculate image quality metrics for given exposure parameters.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        dict: Dictionary of image quality metrics.
    """
    snr = self.measure_snr(kv, t , ma)
    contrast = self.measure_contrast(kv)
    pv_bg = self.measure_det_dose_bg(kv, t, ma)
    pv_obj = self.measure_det_dose_obj(kv, t, ma)

    pv_bg_p = self.measure_det_dose_bg_p(kv, t, ma)

    noise_bg = self.measure_pixel_noise_bg(kv, t, ma)
    noise_obj = self.measure_pixel_noise_obj(kv, t, ma)

    det_kerma = self.measure_det_kerma(kv, t, ma)

    filtration = self.config.spectrum_data.filtration

    results = { 'Filtration' : filtration,
                'Potential (kV)' : kv,
               'ms' : t*1000,
               'mA' : ma,
               'SNR' : snr,
               'Contrast' : contrast,
               'PV BG' : pv_bg,
               'PV OBJ' : pv_obj,
               'PV BG P' : pv_bg_p,
               'Noise BG' : noise_bg,
               'Noise OBJ' : noise_obj,
               'DET KERMA (nGy)' : det_kerma
                }
    results = self.calc_entrance_kerma(results)
    return results

measure_contrast(kv)

Measure image contrast for a given kV value

Parameters:

Name Type Description Default
kv int

Tube potential (kV)

required

Returns:

Name Type Description
float float

Calculated contrast value

Source code in flexpose/measure.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def measure_contrast(self, kv: int) -> float:
    """
    Measure image contrast for a given kV value

    Args:
        kv (int): Tube potential (kV)

    Returns:
        float: Calculated contrast value
    """
    # we assume scatter is constant so for the numerator 
    # only p is used
    pv_bg = self.sampled_pixels['PV BG'][kv]
    pv_bg_p = self.sampled_pixels['PV P BG'][kv]
    pv_obj_p = self.sampled_pixels['PV P OBJ'][kv]
    contrast = (pv_bg_p - pv_obj_p)/(pv_bg + 1E-15)
    return contrast

measure_det_dose_bg(kv, t, ma)

Measure detector dose in background region

Parameters:

Name Type Description Default
kv int

Tube potential (kV)

required
t float

Exposure time

required
ma float

Tube current (mA)

required

Returns:

Name Type Description
float float

Detector dose in background.

Source code in flexpose/measure.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def measure_det_dose_bg(self, kv: int, t: float, ma: float) -> float:
    """
    Measure detector dose in background region

    Args:
        kv (int): Tube potential (kV)
        t (float): Exposure time
        ma (float): Tube current (mA)

    Returns:
        float: Detector dose in background.
    """
    det_dose  = self.sampled_pixels['PV BG'][kv]*t*ma
    return det_dose

measure_det_dose_bg_p(kv, t, ma)

Measure detector dose for primary background region.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Detector dose for primary background.

Source code in flexpose/measure.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def measure_det_dose_bg_p(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
    """
    Measure detector dose for primary background region.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Detector dose for primary background.
    """
    det_dose  = self.sampled_pixels['PV P BG'][kv]*t*ma
    return det_dose

measure_det_dose_obj(kv, t, ma)

Measure detector dose (primary plus scatter) in object region.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Detector dose (primary plus scatter) in object region.

Source code in flexpose/measure.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def measure_det_dose_obj(self, kv: int, t: float, ma: float) -> float:
    """
    Measure detector dose (primary plus scatter) in object region.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Detector dose (primary plus scatter) in object region.
    """
    det_dose  = self.sampled_pixels['PV OBJ'][kv]*t*ma
    return det_dose

measure_det_dose_obj_p(kv, t, ma)

Measure detector dose for primaries in the object region

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Detector dose for primaries in the object region

Source code in flexpose/measure.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def measure_det_dose_obj_p(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
    """
    Measure detector dose for primaries in the object region

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Detector dose for primaries in the object region
    """
    det_dose  = self.sampled_pixels['PV P OBJ'][kv]*t*ma
    return det_dose

measure_det_kerma(kv, t, ma)

Measure detector kerma for given exposure parameters.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Detector kerma value.

Source code in flexpose/measure.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def measure_det_kerma(self, kv: int, t: float, ma: float) -> float:
    """
    Measure detector kerma for given exposure parameters.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Detector kerma value.
    """
    det_kerma  = self.sampled_pixels['KERMA DET'][kv]*t*ma
    return det_kerma

measure_noise(kv, t, ma)

Measure total noise (quantum + electronic) for given exposure parameters.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Total noise value.

Source code in flexpose/measure.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def measure_noise(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
    """
    Measure total noise (quantum + electronic) for given exposure parameters.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Total noise value.
    """
    npixels = self.npixels
    quantum_noise = self.sampled_pixels['NOISE BG'][kv]
    quantum_noise = quantum_noise * np.sqrt(t*ma)

    electronic_noise = self._calc_electronic_noise()
    # retrieve the total noise
    total_noise = np.sqrt(quantum_noise**2 + electronic_noise**2)*np.sqrt(npixels)
    return total_noise

measure_pixel_noise_bg(kv, t, ma)

Measure pixel noise in background region.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Pixel noise in background.

Source code in flexpose/measure.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def measure_pixel_noise_bg(self, kv: int, t: float, ma: float) -> float:
    """
    Measure pixel noise in background region.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Pixel noise in background.
    """
    quantum_noise = self.sampled_pixels['NOISE BG'][kv]
    quantum_noise = quantum_noise * np.sqrt(t*ma)
    return quantum_noise

measure_pixel_noise_obj(kv, t, ma)

Measure pixel noise in object region.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Pixel noise in object region.

Source code in flexpose/measure.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def measure_pixel_noise_obj(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
    """
    Measure pixel noise in object region.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Pixel noise in object region.
    """
    quantum_noise = self.sampled_pixels['NOISE OBJ'][kv]
    quantum_noise = quantum_noise * np.sqrt(t*ma)
    return quantum_noise

measure_snr(kv, t, ma)

Measure signal-to-noise ratio (SNR) for given exposure parameters.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

SNR value.

Source code in flexpose/measure.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def measure_snr(self, kv: int, t: float | np.ndarray, ma: float | np.ndarray) -> float:
    """
    Measure signal-to-noise ratio (SNR) for given exposure parameters.

    Args:
        kv (int): Tube potential (kV).
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: SNR value.
    """
    pv_bg = self.measure_det_dose_bg_p(kv, t, ma)
    pv_obj = self.measure_det_dose_obj_p(kv, t, ma)
    npixels = self.npixels

    dif_signal = abs(pv_bg - pv_obj)*npixels

    total_noise = self.measure_noise(kv, t, ma)
    snr = dif_signal/total_noise
    return snr

sample_pixels()

Sample pixel values from the provided pixel results

Source code in flexpose/measure.py
37
38
39
40
41
def sample_pixels(self) -> None:
    """
    Sample pixel values from the provided pixel results
    """
    self.sampled_pixels = self._prepare_pixels(self.pixel_results)

set_rng(rng)

Set the random number generator for reproducibility

Parameters:

Name Type Description Default
rng Generator | None

Random number generator instance

required
Source code in flexpose/measure.py
28
29
30
31
32
33
34
35
def set_rng(self, rng : np.random.Generator | None) -> None:
    """
    Set the random number generator for reproducibility

    Args:
        rng (np.random.Generator | None): Random number generator instance
    """
    self.rng = rng

Dose Calculations

flexpose.dose

CalcDose

Source code in flexpose/dose.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class CalcDose:
    def __init__(self, config: dataformats.ConfigData) -> None:
        """
        Initialize the CalcDose class with configuration data.

        Args:
            config (dataformats.ConfigData): Configuration data object.
        """
        self.config : dataformats.ConfigData = config
        self.logger = auxfuncs.Logger(logdir=str(self.config.general_config.output_folder), logname='dose')
        self.dose_table : pd.DataFrame = pd.read_csv(self.config.dose_data.dose_path, sep='\t')
        self.export_df : pd.DataFrame = pd.DataFrame()
        self.quantity_name : list[str] = ['']
        self._hist_to_mas : None | dict = self._get_hist_to_mas()


    def _make_entrance_kerma_col(self) -> None:
        """
        Convert DAP to air kerma for optimization and add to export DataFrame.
        """
        df = self.export_df
        sid = self.config.detector_data.sid
        fov = self.config.xray_tube_data.fov
        ref_point = sid - 30
        new_fov = (ref_point/sid)*fov
        field_area = new_fov**2/2
        if self._hist_to_mas is not None:
            unity = 'mAs'
        else:
            unity = 'hist'
        dap = df[f'DAP (Gycm2/{unity})'].to_numpy()
        kerma = dap.astype(np.float64)*1E3/field_area
        self.export_df[f'Entrance Kerma (mGy/{unity})'] = kerma


    def _get_hist_to_mas(self) -> None | dict:
        """
        Get the conversion dictionary between histogram units and mAs.

        Returns:
            None or dict: Conversion dictionary or None if not available.
        """
        fname = f'{self.config.general_config.output_folder}/calibration.txt'
        if fname == '':
            return None
        df = pd.read_csv(fname, comment='#', sep='\t')
        kv = df['kV'].values
        hist_to_mas = df['Hist/mAs'].values
        hist_to_mas = dict(zip(kv, hist_to_mas))
        return hist_to_mas


    def quantity_and_sample(self) -> tuple[np.ndarray, np.ndarray]:
        """
        Get the quantity and uncertainty arrays from the dose table.

        Returns:
            tuple: (quantity array, uncertainty array)
        """
        df = self.dose_table
        quantity_name = self.quantity_name
        quantity = df[quantity_name[0]].values
        unc = df[quantity_name[1]].values
        quantity = np.maximum(quantity, 0)
        unc = np.maximum(unc, 0)
        return quantity, unc

    def integrate_quantity(self, quantity : np.ndarray, unc : np.ndarray, kv: int) -> tuple[float, float]:
        """
        Integrate the quantity and uncertainty over the spectrum probabilities for a given kV.

        Args:
            quantity (np.ndarray): Quantity array.
            unc (np.ndarray): Uncertainty array.
            kv (int): Tube potential (kV).

        Returns:
            tuple: (integrated quantity, integrated uncertainty)
        """
        cutoff_energy = self.config.general_config.cutoff_energy
        e_bins , probs = auxfuncs.get_spec_prob(self.config.spectrum_data, kv, cutoff_energy=cutoff_energy)
        x_quantity = self.dose_table['Energy (keV)'].values
        # we interpolate the quantity and uncertainty to the energy bins of the spectrum
        quantity = np.interp(e_bins, x_quantity, quantity)
        var = np.interp(e_bins, x_quantity, unc**2)

        integrated = np.sum(probs * quantity[:len(probs)]) / np.sum(probs)
        # just in case
        probs_norm = probs/np.sum(probs)
        unc_integrated = np.sum(probs_norm**2 * var)
        unc_integrated = np.sqrt(unc_integrated)
        return integrated, unc_integrated

    def obtain_quantity_unc(self, kv: int) -> tuple[float, float]:
        """
        Obtain the mean and standard deviation for a given kV, converting units if needed.

        Args:
            kv (int): Tube potential (kV).

        Returns:
            tuple: (mean, standard deviation)
        """
        quantity, unc = self.quantity_and_sample()
        quantity, unc = self.integrate_quantity(quantity, unc, kv)
        mean = quantity
        std = unc
        if self._hist_to_mas is not None:
            # here we convert from hist to mAs
            mas_hist = self._hist_to_mas[kv]
            mean = mean*(mas_hist)
            std = std*(mas_hist)
        return (mean, std)


    def obtain_quantities(self) -> None:
        """
        Parallelize the dose calculations for all kV values and update export DataFrame.
        """
        kv_vec = self.config.spectrum_data.kv_vec
        with mp.Pool() as pool:
            results = pool.map(self.obtain_quantity_unc, kv_vec)
        mean, std = list(zip(*results))
        quantity_name = []
        quantity_name.append(self.quantity_name[0])
        quantity_name.append(self.quantity_name[1])
        if self._hist_to_mas is not None:
             quantity_name[0] = quantity_name[0].replace('hist', 'mAs')
             quantity_name[1] = quantity_name[1].replace('hist', 'mAs')
        self.export_df[quantity_name[0]] = mean
        self.export_df[quantity_name[1]] = std

    @auxfuncs.measure_time
    def obtain_all_quantities(self) -> None:
        """
        Calculate and store all dosimetry quantities for all kV values.
        """
        self.logger.info('Calculating Dose')
        kv_vec = self.config.spectrum_data.kv_vec
        self.export_df['Potential (kV)'] = kv_vec

        for dosimetry in self.config.dose_data.dosimetry_list:
            self.quantity_name = [f'{dosimetry}', f'{dosimetry} Unc.']
            self.obtain_quantities()
        self._make_entrance_kerma_col()


    def save_doses(self) -> None:
        """
        Save calculated dose values to local CSV files.
        """
        self.logger.info('Saving doses to local files')
        output_dir = self.config.general_config.output_folder
        output_dir = f'{output_dir}/dose_values'
        label = self.config.spectrum_data.label
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        dfname = f'{output_dir}/dose_{label}.csv'
        self.export_df.to_csv(dfname, sep='\t', index=False)

integrate_quantity(quantity, unc, kv)

Integrate the quantity and uncertainty over the spectrum probabilities for a given kV.

Parameters:

Name Type Description Default
quantity ndarray

Quantity array.

required
unc ndarray

Uncertainty array.

required
kv int

Tube potential (kV).

required

Returns:

Name Type Description
tuple tuple[float, float]

(integrated quantity, integrated uncertainty)

Source code in flexpose/dose.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def integrate_quantity(self, quantity : np.ndarray, unc : np.ndarray, kv: int) -> tuple[float, float]:
    """
    Integrate the quantity and uncertainty over the spectrum probabilities for a given kV.

    Args:
        quantity (np.ndarray): Quantity array.
        unc (np.ndarray): Uncertainty array.
        kv (int): Tube potential (kV).

    Returns:
        tuple: (integrated quantity, integrated uncertainty)
    """
    cutoff_energy = self.config.general_config.cutoff_energy
    e_bins , probs = auxfuncs.get_spec_prob(self.config.spectrum_data, kv, cutoff_energy=cutoff_energy)
    x_quantity = self.dose_table['Energy (keV)'].values
    # we interpolate the quantity and uncertainty to the energy bins of the spectrum
    quantity = np.interp(e_bins, x_quantity, quantity)
    var = np.interp(e_bins, x_quantity, unc**2)

    integrated = np.sum(probs * quantity[:len(probs)]) / np.sum(probs)
    # just in case
    probs_norm = probs/np.sum(probs)
    unc_integrated = np.sum(probs_norm**2 * var)
    unc_integrated = np.sqrt(unc_integrated)
    return integrated, unc_integrated

obtain_all_quantities()

Calculate and store all dosimetry quantities for all kV values.

Source code in flexpose/dose.py
141
142
143
144
145
146
147
148
149
150
151
152
153
@auxfuncs.measure_time
def obtain_all_quantities(self) -> None:
    """
    Calculate and store all dosimetry quantities for all kV values.
    """
    self.logger.info('Calculating Dose')
    kv_vec = self.config.spectrum_data.kv_vec
    self.export_df['Potential (kV)'] = kv_vec

    for dosimetry in self.config.dose_data.dosimetry_list:
        self.quantity_name = [f'{dosimetry}', f'{dosimetry} Unc.']
        self.obtain_quantities()
    self._make_entrance_kerma_col()

obtain_quantities()

Parallelize the dose calculations for all kV values and update export DataFrame.

Source code in flexpose/dose.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def obtain_quantities(self) -> None:
    """
    Parallelize the dose calculations for all kV values and update export DataFrame.
    """
    kv_vec = self.config.spectrum_data.kv_vec
    with mp.Pool() as pool:
        results = pool.map(self.obtain_quantity_unc, kv_vec)
    mean, std = list(zip(*results))
    quantity_name = []
    quantity_name.append(self.quantity_name[0])
    quantity_name.append(self.quantity_name[1])
    if self._hist_to_mas is not None:
         quantity_name[0] = quantity_name[0].replace('hist', 'mAs')
         quantity_name[1] = quantity_name[1].replace('hist', 'mAs')
    self.export_df[quantity_name[0]] = mean
    self.export_df[quantity_name[1]] = std

obtain_quantity_unc(kv)

Obtain the mean and standard deviation for a given kV, converting units if needed.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required

Returns:

Name Type Description
tuple tuple[float, float]

(mean, standard deviation)

Source code in flexpose/dose.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def obtain_quantity_unc(self, kv: int) -> tuple[float, float]:
    """
    Obtain the mean and standard deviation for a given kV, converting units if needed.

    Args:
        kv (int): Tube potential (kV).

    Returns:
        tuple: (mean, standard deviation)
    """
    quantity, unc = self.quantity_and_sample()
    quantity, unc = self.integrate_quantity(quantity, unc, kv)
    mean = quantity
    std = unc
    if self._hist_to_mas is not None:
        # here we convert from hist to mAs
        mas_hist = self._hist_to_mas[kv]
        mean = mean*(mas_hist)
        std = std*(mas_hist)
    return (mean, std)

quantity_and_sample()

Get the quantity and uncertainty arrays from the dose table.

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

(quantity array, uncertainty array)

Source code in flexpose/dose.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def quantity_and_sample(self) -> tuple[np.ndarray, np.ndarray]:
    """
    Get the quantity and uncertainty arrays from the dose table.

    Returns:
        tuple: (quantity array, uncertainty array)
    """
    df = self.dose_table
    quantity_name = self.quantity_name
    quantity = df[quantity_name[0]].values
    unc = df[quantity_name[1]].values
    quantity = np.maximum(quantity, 0)
    unc = np.maximum(unc, 0)
    return quantity, unc

save_doses()

Save calculated dose values to local CSV files.

Source code in flexpose/dose.py
156
157
158
159
160
161
162
163
164
165
166
def save_doses(self) -> None:
    """
    Save calculated dose values to local CSV files.
    """
    self.logger.info('Saving doses to local files')
    output_dir = self.config.general_config.output_folder
    output_dir = f'{output_dir}/dose_values'
    label = self.config.spectrum_data.label
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    dfname = f'{output_dir}/dose_{label}.csv'
    self.export_df.to_csv(dfname, sep='\t', index=False)

Pixel & SNR Mapping

flexpose.pixel

CalcPixel

Source code in flexpose/pixel.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
class CalcPixel:
    def __init__(self, config : dataformats.ConfigData) -> None:
        """
        Initialize the CalcPixel class with configuration data

        Args:
            config (dataformats.ConfigData): Configuration data object
        """
        self.config : dataformats.ConfigData  = config
        self.logger = auxfuncs.Logger(logdir=str(self.config.general_config.output_folder), logname='snr')
        self.primary : dataformats.SpectralSet | None = None
        self.scatter : dataformats.SpectralSet | None = None
        self.mu : np.ndarray = np.array([])
        self._hist_to_mas : None | dict = None
        self._read_tables()


    def _get_mu(self) -> np.ndarray:
        """
        Get the attenuation coefficient based on object properties provided by the user

        Returns:
            np.ndarray: Attenuation coefficients
        """
        cutoff_energy = self.config.general_config.cutoff_energy
        fname = self.config.object_data.attenuation_path
        rho = self.config.object_data.density
        thick = self.config.object_data.thickness
        df = pd.read_csv(fname, comment='#', header=None, sep='\\s+').values
        mu = df[:,1]
        energy = df[:,0]
        # here we split the array with the index where it meets the minimum energy
        idx_cut = np.argwhere(df[:,0] >= cutoff_energy)[0][0]
        mu = mu[idx_cut:]*rho*thick
        energy = energy[idx_cut:]
        kev = np.round(energy/1000,2)
        return np.array([kev, mu])

    def _get_hist_to_mas(self) -> None:
        """
        Translate the number of histories to mAs using calibration data
        """
        fname = f'{self.config.general_config.output_folder}/calibration.txt'
        if fname == '':
            return 
        df = pd.read_csv(fname, comment='#', sep='\t')
        kv = df['kV'].values
        hist_to_mas = df['Hist/mAs'].values
        self._hist_to_mas = dict(zip(kv, hist_to_mas))

    def _read_tables(self) -> None:
        """
        Initialize the class with the necessary tables for SNR calculations
        """
        keymaps = {"N": "n", "E": "e", "SM": "sm", "kerma": "kerma"}
        self.logger.info('Reading tables for SNR calculations')
        self.primary = auxfuncs.spectral_set_from_json(str(self.config.iq_data.primary_path), 
                                                       keymap=keymaps)
        self.scatter = auxfuncs.spectral_set_from_json(str(self.config.iq_data.scatter_path), 
                                                       keymap=keymaps)
        self.mu = self._get_mu()
        self._get_hist_to_mas()

    def _correct_snr_area(self, snr : np.ndarray) -> np.ndarray:
        """
        Correct SNR values based on object area and magnification.

        Args:
            snr (np.ndarray): SNR values.

        Returns:
            np.ndarray: Area-corrected SNR values.
        """
        object_size = self.config.object_data.size_xy
        sid = self.config.detector_data.sid
        sod = self.config.object_data.sod
        mag = sid/sod
        object_area = object_size[0]*object_size[1]
        snr_area = snr*np.sqrt(object_area*mag)
        return snr_area

    def _correct_quantity_area(self, quantity : np.ndarray) -> np.ndarray:
        """
        Correct quantity values based on object area and magnification.

        Args:
            quantity (np.ndarray): Quantity values.

        Returns:
            np.ndarray: Area-corrected quantity values.
        """
        object_size = self.config.object_data.size_xy
        sid = self.config.detector_data.sid
        sod = self.config.object_data.sod
        mag = sid/sod
        object_area = object_size[0]*object_size[1]
        quantity_area = quantity*(object_area*mag)
        return quantity_area

    def _calc_quantity_mean_area(self, quantity : np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """
        Calculate mean and standard deviation of quantity, corrected for area.

        Args:
            quantity (np.ndarray): Quantity values.

        Returns:
            tuple: (mean, std) area-corrected.
        """
        mean = np.mean(quantity, axis=0)
        std = np.std(quantity, axis=0, ddof=1)

        mean = self._correct_quantity_area(mean)
        std = self._correct_quantity_area(std)

        return mean, std

    def _correct_quantity(self, quantity : str, value : np.ndarray):
        """
        Change the quantity from eV/hist to optical_photons/hist, or optical_photons2/hist for the SM

        Args:
            quantity (str): Quantity type ('e', 'sm', etc.)
            value (np.ndarray): Value to convert

        Returns:
            np.ndarray: Converted value.
        """
        light_yield = self.config.detector_data.light_yield
        convert = light_yield/1000
        if quantity == 'sm':
            value = value*(convert**2)
        else:
            value = value*convert
        return value

    def _apply_mas_to_hist(self, kv: int, quantity: np.ndarray) -> np.ndarray:
        """
        Apply mAs-to-histories conversion for a given kV value.

        Args:
            kv (int): Tube potential (kV).
            quantity (np.ndarray): Quantity to convert.

        Returns:
            np.ndarray: Converted quantity.
        """
        if self._hist_to_mas is None:
            return quantity
        else:
            mas_hist = self._hist_to_mas[kv]
            quantity = quantity*mas_hist
        return quantity


    def get_quantity(self, kv : int, source : dataformats.SpectralSet, mu : np.ndarray | None, quantity : str) -> tuple[np.ndarray, np.ndarray]:
        """
        Get the image quality quantities from input dicts and integrate them over the x-ray spectrum.

        Args:
            kv (int): Tube potential (kV).
            source:  SpectralSet, must have fields N, E, SM, and optional kerma.
            mu (2, M | None): [energies_keV, mu_values] Attenuation coefficients or None.
            quantity (str): Quantity type.

        Returns:
            tuple: (quantity, uncertainty) arrays.
        """
        cutoff_energy = self.config.general_config.cutoff_energy
        pixel_size = self.config.detector_data.pixel_size
        og_pixel_size = self.config.detector_data.og_pixel_size
        img_shape = self.config.iq_data.img_shape
        kev, prob = auxfuncs.get_spec_prob(self.config.spectrum_data, kv, cutoff_energy=cutoff_energy)
        kev = np.round(kev/1000,2)
        len_evec = len(prob)

        prob = prob.astype(float)[:, None, None]

        # check the quantity to pick
        qkey = quantity.lower()
        grid_map = {
            "n": source.N,
            "e": source.E,
            "sm": source.SM,
            "kerma": getattr(source, "kerma", None),
        }
        grid = grid_map.get(qkey, None)
        if grid is None:
            raise KeyError(f"Quantity '{quantity}' is not available in the provided SpectralSet.")


        # Interpolate all energies in one go (returns stacks of shape (E,H,W))
        quant_stack, var_stack = grid.interp_many(kev)          
        norm_stack, _ = source.N.interp_many(kev)               

        # Ensure shapes match the expected image shape
        H, W = quant_stack.shape[1], quant_stack.shape[2]
        if (H, W) != tuple(img_shape):
            raise ValueError(f"Spatial shape mismatch: data {(H, W)} vs expected {tuple(img_shape)}")


        if var_stack is None:
            quant_unc_stack = np.zeros_like(quant_stack, dtype=float)
        else:
            quant_unc_stack = np.sqrt(var_stack, dtype=float)

        # we let uncertainty be at 100% to avoid problems with sampling negative values
        quant_unc_stack = np.minimum(quant_unc_stack, quant_stack)

        # attenuation coefficient part
        if mu is None:
            mu_bins = np.zeros((len_evec,), dtype=float)
        else:
            e_src = mu[0, :].astype(float)
            mu_src = mu[1, :].astype(float)
            order = np.argsort(e_src)
            e_src = e_src[order]
            mu_src = mu_src[order]
            mu_bins = np.interp(kev, e_src, mu_src, left=mu_src[0], right=mu_src[-1])
        rt_vec = np.exp(-mu_bins)[:, None, None]

        if qkey in ("n", "kerma"):
            prob_norm = prob / (np.sum(prob, axis=0) + 1e-60) 
            calc_quant = np.sum(quant_stack * rt_vec * prob_norm, axis=0)
            calc_unc = np.sqrt(np.sum((quant_unc_stack * rt_vec) ** 2 * (prob_norm ** 2), axis=0))

        elif qkey in ("e", "sm"):
            weights_raw = prob * norm_stack * rt_vec            # (E,H,W)
            norm = np.sum(weights_raw, axis=0) + 1e-60
            calc_quant = np.sum(quant_stack * weights_raw, axis=0) / norm
            calc_unc = np.sqrt(np.sum((quant_unc_stack * weights_raw) ** 2, axis=0)) / norm

            # Unit conversion from eV-like quantity to optical photons
            calc_quant = self._correct_quantity(qkey, calc_quant)
            calc_unc = self._correct_quantity(qkey, calc_unc)

        else:
            raise ValueError(f"Unsupported quantity: {quantity}")

        if qkey == "n":
            # scale from 1x1 cm^2 to pixel area
            scale = (pixel_size[0] * pixel_size[1]) / (og_pixel_size[0] * og_pixel_size[1])
            calc_quant = self._apply_mas_to_hist(kv, calc_quant * scale)
            calc_unc = self._apply_mas_to_hist(kv, calc_unc * scale)
        elif qkey == "kerma":
            calc_quant = self._apply_mas_to_hist(kv, calc_quant)
            calc_unc = self._apply_mas_to_hist(kv, calc_unc)

        return calc_quant.astype(float), calc_unc.astype(float)


    def get_signal_difference(self, kv: int) -> np.ndarray:
        """
        Calculate the signal difference between the contrast object and the background

        Args:
            kv (int): Tube potential (kV)

        Returns:
            np.ndarray: Signal difference array
        """
        # signal without object (background)
        primary = self.primary
        mu = self.mu
        n_wo, _ = self.get_quantity(kv, primary, None, 'n')
        e_wo, _ = self.get_quantity(kv, primary, None, 'e')
        signal_wo = n_wo*e_wo

        # get signal with object
        n_o, _ = self.get_quantity(kv, primary, mu, 'n')
        e_o, _ = self.get_quantity(kv, primary, mu, 'e')
        signal_o = n_o*e_o

        return signal_wo - signal_o


    def get_contrast(self, kv: int) -> np.ndarray:
        """
        Calculate the contrast difference between the contrast object and the background

        Args:
            kv (int): Tube potential (kV).

        Returns:
            np.ndarray: Contrast difference array.
        """
        primary = self.primary
        scatter = self.scatter
        mu = self.mu
        # get signal without object (mu=0)
        signal_wo, _ = self.get_quantity(kv, primary, None, 'e')
        signal_wo += self.get_quantity(kv, scatter, None, 'e')
        # get signal with object
        signal_o = self.get_quantity(kv, primary, mu, 'e')
        signal_o += self.get_quantity(kv, scatter, None, 'e')
        # avoid round errors
        return (signal_wo - signal_o)/(signal_wo+EPS)

    def get_total_signal(self, kv: int, mode: str) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        """
        Calculate the total signal and uncertainty for background or object mode.

        Args:
            kv (int): Tube potential (kV).
            mode (str): 'background' or 'object'.

        Returns:
            tuple: (primary signal, primary uncertainty, total signal, total uncertainty)
        """
        primary = self.primary
        scatter = self.scatter
        match mode:
            case 'background':
                mu = None
            case 'object':
                mu = self.mu
            case _:
                raise NotImplementedError("Mode must be 'background' or 'object'.")
        # get primary signal without object (mu=0)
        n_p, unc_p = self.get_quantity(kv, primary, mu, 'n')
        signal_p, unc_signal_p = self.get_quantity(kv, primary, mu, 'e')
        signal_np = signal_p*n_p
        unc_signal_np = signal_np*np.sqrt((unc_p/(n_p+EPS))**2 + (unc_signal_p/(signal_p+EPS))**2)
        # get scatter signal without object (mu=0)
        n_s, unc_s = self.get_quantity(kv, scatter, None, 'n')
        signal_s, unc_signal_s = self.get_quantity(kv, scatter, None, 'e')
        signal_ns = n_s*signal_s
        unc_signal_ns = signal_ns*np.sqrt((unc_s/(n_s+EPS))**2 + (unc_signal_s/(signal_s+EPS))**2)
        signal_nt = signal_np + signal_ns
        unc_signal_nt = np.sqrt(unc_signal_np**2 + unc_signal_ns**2)
        return signal_np, unc_signal_np, signal_nt, unc_signal_nt

    def get_noise_primary(self, kv: int, mode: str) -> tuple[np.ndarray, np.ndarray]:
        """
        Calculate the second moment of energy deposition from primary photons.

        Args:
            kv (int): Tube potential (kV).
            mode (str): 'background' or 'object'.

        Returns:
            tuple: (variance, uncertainty)
        """
        primary = self.primary
        match mode:
            case 'background':
                mu = None
            case 'object':
                mu = self.mu
            case _:
                raise NotImplementedError("Mode must be 'background' or 'object'.")
        n_o, unc_n_o = self.get_quantity(kv, primary, mu, 'n')
        noise_primary, unc_noise_primary = self.get_quantity(kv, primary, mu, 'sm')
        variance = noise_primary*n_o
        unc_variance = variance * np.sqrt((unc_n_o/(n_o+EPS))**2 + (unc_noise_primary/(noise_primary+EPS))**2)
        return variance, unc_variance

    def get_noise_scatter(self, kv: int) -> tuple[np.ndarray, np.ndarray]:
        """
        Calculate the second moment of energy deposition from scattered photons.

        Args:
            kv (int): Tube potential (kV).

        Returns:
            tuple: (variance, uncertainty)
        """
        scatter = self.scatter
        n_s, unc_n_s = self.get_quantity(kv, scatter, None, 'n')
        noise_scatter, unc_noise_scatter = self.get_quantity(kv, scatter, None, 'sm')
        variance = noise_scatter * n_s
        unc_variance = variance * np.sqrt((unc_n_s/(n_s+EPS))**2 + (unc_noise_scatter/(noise_scatter+EPS))**2)
        return variance, unc_variance

    def get_total_noise(self, kv: int, mode: str) -> tuple[np.ndarray, np.ndarray]:
        """
        Combine the noise from primary and scattered photons.

        Args:
            kv (int): Tube potential (kV).
            mode (str): 'background' or 'object'.

        Returns:
            tuple: (total noise, uncertainty)
        """
        sm_primary, unc_sm_primary = self.get_noise_primary(kv, mode)
        sm_scatter, unc_sm_scatter =  self.get_noise_scatter(kv)
        noise_total = np.sqrt(sm_primary + sm_scatter)
        # uncertainty propagation of f(a,b) = (a+b)^0.5
        #d/da(f) = 1/(2f)
        unc_noise_total = 1/(2*noise_total+EPS)*np.sqrt(unc_sm_primary**2 + unc_sm_scatter**2)
        return noise_total, unc_noise_total

    def get_detector_kerma(self, kv: int) -> tuple[np.ndarray, np.ndarray]:
        """
        Calculate the detector air kerma.

        Args:
            kv (int): Tube potential (kV).

        Returns:
            tuple: (kerma, uncertainty)
        """
        primary = self.primary
        mu = None
        # get kerma without object (mu=None)
        kerma, unc_kerma = self.get_quantity(kv, primary, mu, 'kerma')
        return kerma, unc_kerma


    def calc_snr(self, kv: int) -> dict:
        """
        Return a dictionary containing the quantities required to estimate the SNR for a specific kV.

        Args:
            kv (int): Tube potential (kV).

        Returns:
            dict: SNR-related quantities for the given kV.
        """

        m_pv_p_bg, std_pv_p_bg, m_pv_bg, std_pv_bg   = self.get_total_signal(kv, 'background')
        m_pv_p_obj, std_pv_p_obj, m_pv_obj, std_pv_obj  = self.get_total_signal(kv, 'object')

        m_noise_bg, std_noise_bg  = self.get_total_noise(kv, 'background')
        m_noise_obj, std_noise_obj  = self.get_total_noise(kv, 'object')

        m_kerma_det, std_kerma_det  = self.get_detector_kerma(kv)

        output  = {'PV BG': m_pv_bg.tolist(), 'PV BG Unc.': std_pv_bg.tolist(),
                   'PV P BG': m_pv_p_bg.tolist(), 'PV P BG Unc.': std_pv_p_bg.tolist(),
                   'PV OBJ': m_pv_obj.tolist(), 'PV OBJ Unc.': std_pv_obj.tolist(),
                   'PV P OBJ': m_pv_p_obj.tolist(), 'PV P OBJ Unc.': std_pv_p_obj.tolist(),
                   'NOISE BG': m_noise_bg.tolist(), 'NOISE BG Unc.': std_noise_bg.tolist(),
                   'NOISE OBJ': m_noise_obj.tolist(), 'NOISE OBJ Unc.': std_noise_obj.tolist(),
                   'KERMA DET': m_kerma_det.tolist(), 'KERMA DET Unc.': std_kerma_det.tolist()
                  }

        return output

    @auxfuncs.measure_time
    def create_snr_map(self) -> dict:
        """
        Parallelize the SNR calculations and create pixel maps for all kV values.

        Returns:
            dict: Dictionary containing pixel maps for all kV values.
        """
        self.logger.info('Calculating Pixel maps')
        kv_vec = self.config.spectrum_data.kv_vec
        dict_results = {}
        imgs = {}

        # for i in range(len(combined)):
            # results = self.calc_snr(kv_vec[i], rng_generator[i])
            # imgs[f'{kv_vec[i]} (kv)'] = results
        with mp.Pool() as pool:
            results = pool.map(self.calc_snr, kv_vec)
        for idx, kv in enumerate(kv_vec):
            imgs[f'{kv} (kv)'] = results[idx]
        dict_results['imgs'] = imgs
        return dict_results

    def save_snr_map(self, dict_results: dict) -> None:
        """
        Save the pixel maps into a dictionary for a specified folder.

        Args:
            dict_results (dict): Dictionary containing pixel maps.
        """
        self.logger.info('Saving Pixel maps as dictionaries')
        output_dir = self.config.general_config.output_folder
        output_dir = f'{output_dir}/snr_maps'
        cu = self.config.spectrum_data.filt
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        dictname = f'{output_dir}/snr_{cu}cu.json'
        with open(dictname, 'w') as f:
            json.dump(dict_results, f, indent=4)   

calc_snr(kv)

Return a dictionary containing the quantities required to estimate the SNR for a specific kV.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required

Returns:

Name Type Description
dict dict

SNR-related quantities for the given kV.

Source code in flexpose/pixel.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def calc_snr(self, kv: int) -> dict:
    """
    Return a dictionary containing the quantities required to estimate the SNR for a specific kV.

    Args:
        kv (int): Tube potential (kV).

    Returns:
        dict: SNR-related quantities for the given kV.
    """

    m_pv_p_bg, std_pv_p_bg, m_pv_bg, std_pv_bg   = self.get_total_signal(kv, 'background')
    m_pv_p_obj, std_pv_p_obj, m_pv_obj, std_pv_obj  = self.get_total_signal(kv, 'object')

    m_noise_bg, std_noise_bg  = self.get_total_noise(kv, 'background')
    m_noise_obj, std_noise_obj  = self.get_total_noise(kv, 'object')

    m_kerma_det, std_kerma_det  = self.get_detector_kerma(kv)

    output  = {'PV BG': m_pv_bg.tolist(), 'PV BG Unc.': std_pv_bg.tolist(),
               'PV P BG': m_pv_p_bg.tolist(), 'PV P BG Unc.': std_pv_p_bg.tolist(),
               'PV OBJ': m_pv_obj.tolist(), 'PV OBJ Unc.': std_pv_obj.tolist(),
               'PV P OBJ': m_pv_p_obj.tolist(), 'PV P OBJ Unc.': std_pv_p_obj.tolist(),
               'NOISE BG': m_noise_bg.tolist(), 'NOISE BG Unc.': std_noise_bg.tolist(),
               'NOISE OBJ': m_noise_obj.tolist(), 'NOISE OBJ Unc.': std_noise_obj.tolist(),
               'KERMA DET': m_kerma_det.tolist(), 'KERMA DET Unc.': std_kerma_det.tolist()
              }

    return output

create_snr_map()

Parallelize the SNR calculations and create pixel maps for all kV values.

Returns:

Name Type Description
dict dict

Dictionary containing pixel maps for all kV values.

Source code in flexpose/pixel.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
@auxfuncs.measure_time
def create_snr_map(self) -> dict:
    """
    Parallelize the SNR calculations and create pixel maps for all kV values.

    Returns:
        dict: Dictionary containing pixel maps for all kV values.
    """
    self.logger.info('Calculating Pixel maps')
    kv_vec = self.config.spectrum_data.kv_vec
    dict_results = {}
    imgs = {}

    # for i in range(len(combined)):
        # results = self.calc_snr(kv_vec[i], rng_generator[i])
        # imgs[f'{kv_vec[i]} (kv)'] = results
    with mp.Pool() as pool:
        results = pool.map(self.calc_snr, kv_vec)
    for idx, kv in enumerate(kv_vec):
        imgs[f'{kv} (kv)'] = results[idx]
    dict_results['imgs'] = imgs
    return dict_results

get_contrast(kv)

Calculate the contrast difference between the contrast object and the background

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required

Returns:

Type Description
ndarray

np.ndarray: Contrast difference array.

Source code in flexpose/pixel.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def get_contrast(self, kv: int) -> np.ndarray:
    """
    Calculate the contrast difference between the contrast object and the background

    Args:
        kv (int): Tube potential (kV).

    Returns:
        np.ndarray: Contrast difference array.
    """
    primary = self.primary
    scatter = self.scatter
    mu = self.mu
    # get signal without object (mu=0)
    signal_wo, _ = self.get_quantity(kv, primary, None, 'e')
    signal_wo += self.get_quantity(kv, scatter, None, 'e')
    # get signal with object
    signal_o = self.get_quantity(kv, primary, mu, 'e')
    signal_o += self.get_quantity(kv, scatter, None, 'e')
    # avoid round errors
    return (signal_wo - signal_o)/(signal_wo+EPS)

get_detector_kerma(kv)

Calculate the detector air kerma.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

(kerma, uncertainty)

Source code in flexpose/pixel.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def get_detector_kerma(self, kv: int) -> tuple[np.ndarray, np.ndarray]:
    """
    Calculate the detector air kerma.

    Args:
        kv (int): Tube potential (kV).

    Returns:
        tuple: (kerma, uncertainty)
    """
    primary = self.primary
    mu = None
    # get kerma without object (mu=None)
    kerma, unc_kerma = self.get_quantity(kv, primary, mu, 'kerma')
    return kerma, unc_kerma

get_noise_primary(kv, mode)

Calculate the second moment of energy deposition from primary photons.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
mode str

'background' or 'object'.

required

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

(variance, uncertainty)

Source code in flexpose/pixel.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def get_noise_primary(self, kv: int, mode: str) -> tuple[np.ndarray, np.ndarray]:
    """
    Calculate the second moment of energy deposition from primary photons.

    Args:
        kv (int): Tube potential (kV).
        mode (str): 'background' or 'object'.

    Returns:
        tuple: (variance, uncertainty)
    """
    primary = self.primary
    match mode:
        case 'background':
            mu = None
        case 'object':
            mu = self.mu
        case _:
            raise NotImplementedError("Mode must be 'background' or 'object'.")
    n_o, unc_n_o = self.get_quantity(kv, primary, mu, 'n')
    noise_primary, unc_noise_primary = self.get_quantity(kv, primary, mu, 'sm')
    variance = noise_primary*n_o
    unc_variance = variance * np.sqrt((unc_n_o/(n_o+EPS))**2 + (unc_noise_primary/(noise_primary+EPS))**2)
    return variance, unc_variance

get_noise_scatter(kv)

Calculate the second moment of energy deposition from scattered photons.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

(variance, uncertainty)

Source code in flexpose/pixel.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def get_noise_scatter(self, kv: int) -> tuple[np.ndarray, np.ndarray]:
    """
    Calculate the second moment of energy deposition from scattered photons.

    Args:
        kv (int): Tube potential (kV).

    Returns:
        tuple: (variance, uncertainty)
    """
    scatter = self.scatter
    n_s, unc_n_s = self.get_quantity(kv, scatter, None, 'n')
    noise_scatter, unc_noise_scatter = self.get_quantity(kv, scatter, None, 'sm')
    variance = noise_scatter * n_s
    unc_variance = variance * np.sqrt((unc_n_s/(n_s+EPS))**2 + (unc_noise_scatter/(noise_scatter+EPS))**2)
    return variance, unc_variance

get_quantity(kv, source, mu, quantity)

Get the image quality quantities from input dicts and integrate them over the x-ray spectrum.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
source SpectralSet

SpectralSet, must have fields N, E, SM, and optional kerma.

required
mu (2, M | None)

[energies_keV, mu_values] Attenuation coefficients or None.

required
quantity str

Quantity type.

required

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

(quantity, uncertainty) arrays.

Source code in flexpose/pixel.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def get_quantity(self, kv : int, source : dataformats.SpectralSet, mu : np.ndarray | None, quantity : str) -> tuple[np.ndarray, np.ndarray]:
    """
    Get the image quality quantities from input dicts and integrate them over the x-ray spectrum.

    Args:
        kv (int): Tube potential (kV).
        source:  SpectralSet, must have fields N, E, SM, and optional kerma.
        mu (2, M | None): [energies_keV, mu_values] Attenuation coefficients or None.
        quantity (str): Quantity type.

    Returns:
        tuple: (quantity, uncertainty) arrays.
    """
    cutoff_energy = self.config.general_config.cutoff_energy
    pixel_size = self.config.detector_data.pixel_size
    og_pixel_size = self.config.detector_data.og_pixel_size
    img_shape = self.config.iq_data.img_shape
    kev, prob = auxfuncs.get_spec_prob(self.config.spectrum_data, kv, cutoff_energy=cutoff_energy)
    kev = np.round(kev/1000,2)
    len_evec = len(prob)

    prob = prob.astype(float)[:, None, None]

    # check the quantity to pick
    qkey = quantity.lower()
    grid_map = {
        "n": source.N,
        "e": source.E,
        "sm": source.SM,
        "kerma": getattr(source, "kerma", None),
    }
    grid = grid_map.get(qkey, None)
    if grid is None:
        raise KeyError(f"Quantity '{quantity}' is not available in the provided SpectralSet.")


    # Interpolate all energies in one go (returns stacks of shape (E,H,W))
    quant_stack, var_stack = grid.interp_many(kev)          
    norm_stack, _ = source.N.interp_many(kev)               

    # Ensure shapes match the expected image shape
    H, W = quant_stack.shape[1], quant_stack.shape[2]
    if (H, W) != tuple(img_shape):
        raise ValueError(f"Spatial shape mismatch: data {(H, W)} vs expected {tuple(img_shape)}")


    if var_stack is None:
        quant_unc_stack = np.zeros_like(quant_stack, dtype=float)
    else:
        quant_unc_stack = np.sqrt(var_stack, dtype=float)

    # we let uncertainty be at 100% to avoid problems with sampling negative values
    quant_unc_stack = np.minimum(quant_unc_stack, quant_stack)

    # attenuation coefficient part
    if mu is None:
        mu_bins = np.zeros((len_evec,), dtype=float)
    else:
        e_src = mu[0, :].astype(float)
        mu_src = mu[1, :].astype(float)
        order = np.argsort(e_src)
        e_src = e_src[order]
        mu_src = mu_src[order]
        mu_bins = np.interp(kev, e_src, mu_src, left=mu_src[0], right=mu_src[-1])
    rt_vec = np.exp(-mu_bins)[:, None, None]

    if qkey in ("n", "kerma"):
        prob_norm = prob / (np.sum(prob, axis=0) + 1e-60) 
        calc_quant = np.sum(quant_stack * rt_vec * prob_norm, axis=0)
        calc_unc = np.sqrt(np.sum((quant_unc_stack * rt_vec) ** 2 * (prob_norm ** 2), axis=0))

    elif qkey in ("e", "sm"):
        weights_raw = prob * norm_stack * rt_vec            # (E,H,W)
        norm = np.sum(weights_raw, axis=0) + 1e-60
        calc_quant = np.sum(quant_stack * weights_raw, axis=0) / norm
        calc_unc = np.sqrt(np.sum((quant_unc_stack * weights_raw) ** 2, axis=0)) / norm

        # Unit conversion from eV-like quantity to optical photons
        calc_quant = self._correct_quantity(qkey, calc_quant)
        calc_unc = self._correct_quantity(qkey, calc_unc)

    else:
        raise ValueError(f"Unsupported quantity: {quantity}")

    if qkey == "n":
        # scale from 1x1 cm^2 to pixel area
        scale = (pixel_size[0] * pixel_size[1]) / (og_pixel_size[0] * og_pixel_size[1])
        calc_quant = self._apply_mas_to_hist(kv, calc_quant * scale)
        calc_unc = self._apply_mas_to_hist(kv, calc_unc * scale)
    elif qkey == "kerma":
        calc_quant = self._apply_mas_to_hist(kv, calc_quant)
        calc_unc = self._apply_mas_to_hist(kv, calc_unc)

    return calc_quant.astype(float), calc_unc.astype(float)

get_signal_difference(kv)

Calculate the signal difference between the contrast object and the background

Parameters:

Name Type Description Default
kv int

Tube potential (kV)

required

Returns:

Type Description
ndarray

np.ndarray: Signal difference array

Source code in flexpose/pixel.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def get_signal_difference(self, kv: int) -> np.ndarray:
    """
    Calculate the signal difference between the contrast object and the background

    Args:
        kv (int): Tube potential (kV)

    Returns:
        np.ndarray: Signal difference array
    """
    # signal without object (background)
    primary = self.primary
    mu = self.mu
    n_wo, _ = self.get_quantity(kv, primary, None, 'n')
    e_wo, _ = self.get_quantity(kv, primary, None, 'e')
    signal_wo = n_wo*e_wo

    # get signal with object
    n_o, _ = self.get_quantity(kv, primary, mu, 'n')
    e_o, _ = self.get_quantity(kv, primary, mu, 'e')
    signal_o = n_o*e_o

    return signal_wo - signal_o

get_total_noise(kv, mode)

Combine the noise from primary and scattered photons.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
mode str

'background' or 'object'.

required

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

(total noise, uncertainty)

Source code in flexpose/pixel.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def get_total_noise(self, kv: int, mode: str) -> tuple[np.ndarray, np.ndarray]:
    """
    Combine the noise from primary and scattered photons.

    Args:
        kv (int): Tube potential (kV).
        mode (str): 'background' or 'object'.

    Returns:
        tuple: (total noise, uncertainty)
    """
    sm_primary, unc_sm_primary = self.get_noise_primary(kv, mode)
    sm_scatter, unc_sm_scatter =  self.get_noise_scatter(kv)
    noise_total = np.sqrt(sm_primary + sm_scatter)
    # uncertainty propagation of f(a,b) = (a+b)^0.5
    #d/da(f) = 1/(2f)
    unc_noise_total = 1/(2*noise_total+EPS)*np.sqrt(unc_sm_primary**2 + unc_sm_scatter**2)
    return noise_total, unc_noise_total

get_total_signal(kv, mode)

Calculate the total signal and uncertainty for background or object mode.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
mode str

'background' or 'object'.

required

Returns:

Name Type Description
tuple tuple[ndarray, ndarray, ndarray, ndarray]

(primary signal, primary uncertainty, total signal, total uncertainty)

Source code in flexpose/pixel.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def get_total_signal(self, kv: int, mode: str) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """
    Calculate the total signal and uncertainty for background or object mode.

    Args:
        kv (int): Tube potential (kV).
        mode (str): 'background' or 'object'.

    Returns:
        tuple: (primary signal, primary uncertainty, total signal, total uncertainty)
    """
    primary = self.primary
    scatter = self.scatter
    match mode:
        case 'background':
            mu = None
        case 'object':
            mu = self.mu
        case _:
            raise NotImplementedError("Mode must be 'background' or 'object'.")
    # get primary signal without object (mu=0)
    n_p, unc_p = self.get_quantity(kv, primary, mu, 'n')
    signal_p, unc_signal_p = self.get_quantity(kv, primary, mu, 'e')
    signal_np = signal_p*n_p
    unc_signal_np = signal_np*np.sqrt((unc_p/(n_p+EPS))**2 + (unc_signal_p/(signal_p+EPS))**2)
    # get scatter signal without object (mu=0)
    n_s, unc_s = self.get_quantity(kv, scatter, None, 'n')
    signal_s, unc_signal_s = self.get_quantity(kv, scatter, None, 'e')
    signal_ns = n_s*signal_s
    unc_signal_ns = signal_ns*np.sqrt((unc_s/(n_s+EPS))**2 + (unc_signal_s/(signal_s+EPS))**2)
    signal_nt = signal_np + signal_ns
    unc_signal_nt = np.sqrt(unc_signal_np**2 + unc_signal_ns**2)
    return signal_np, unc_signal_np, signal_nt, unc_signal_nt

save_snr_map(dict_results)

Save the pixel maps into a dictionary for a specified folder.

Parameters:

Name Type Description Default
dict_results dict

Dictionary containing pixel maps.

required
Source code in flexpose/pixel.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def save_snr_map(self, dict_results: dict) -> None:
    """
    Save the pixel maps into a dictionary for a specified folder.

    Args:
        dict_results (dict): Dictionary containing pixel maps.
    """
    self.logger.info('Saving Pixel maps as dictionaries')
    output_dir = self.config.general_config.output_folder
    output_dir = f'{output_dir}/snr_maps'
    cu = self.config.spectrum_data.filt
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    dictname = f'{output_dir}/snr_{cu}cu.json'
    with open(dictname, 'w') as f:
        json.dump(dict_results, f, indent=4)   

Water Equivalent Thickness (WET)

flexpose.wet

CalcWET

Calculates Water Equivalent Thickness (WET) maps

Source code in flexpose/wet.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
class CalcWET:
    """
    Calculates Water Equivalent Thickness (WET) maps
    """
    def __init__(self, config: dataformats.ConfigData, seed: int = 42) -> None:
        """
        Initialize CalcWET with configuration and random seed

        Args:
            config (ConfigData): Configuration data object.
            seed (int, optional): Random seed for reproducibility. Defaults to 42
        """
        self.config : dataformats.ConfigData = config
        self.logger = auxfuncs.Logger(logdir=str(self.config.general_config.output_folder), logname='wet')
        self.seed : int = seed
        self.wet_mono : dict = {}
        self.repeat : int = 20
        self.rng = np.random.default_rng(seed=seed)
        self.wet_thickness : dict = {}
        self._hist_to_mas : None | dict = None
        self._get_hist_to_mas()


    def _get_hist_to_mas(self) -> None:
        """This function translates the number of histories to mAs
        """
        fname = f'{self.config.general_config.output_folder}/calibration.txt'
        if fname == '':
            return 
        df = pd.read_csv(fname, comment='#', sep='\t')
        kv = df['kV'].values
        hist_to_mas = df['Hist/mAs'].values
        self._hist_to_mas = dict(zip(kv, hist_to_mas))

    def _load_wet_table_mono(self, thick: int) -> dict:
        """
        Load monoenergetic WET table for a given thickness.

        Args:
            thick (int): Thickness value.

        Returns:
            dict: Loaded WET data.
        """
        material = self.config.wet_data.wet_material
        grid = self.config.wet_data.grid
        path = self.config.wet_data.wet_path

        with open(f'{path}/{material}_{grid}_{thick}.json', 'r') as f:
            wet = json.load(f)
        return wet

    def _correct_quantity(self, quantity : str, value : np.ndarray):
        """
        Change the quantity from eV/hist to optical_photons/hist, or optical_photons^2/hist for the SM

        Args:
            quantity (str): Quantity type ('e', 'sm')
            value (np.ndarray): Value to convert

        Returns:
            np.ndarray: Converted value.
        """
        light_yield = self.config.detector_data.light_yield
        convert = light_yield/1000
        if quantity == 'sm':
            value = value*(convert**2)
        else:
            value = value*convert
        return value

    def _apply_mas_to_hist(self, kv: int, quantity: np.ndarray) -> np.ndarray:
        """
        Apply mAs-to-histories conversion for a given kV value

        Args:
            kv (int): Tube potential (kV)
            quantity (np.ndarray): Quantity to convert

        Returns:
            np.ndarray: Converted quantity
        """
        if self._hist_to_mas is None:
            return quantity
        else:
            mas_hist = self._hist_to_mas[kv]
            quantity = quantity*mas_hist
        return quantity

    def integrate_signal(self, kv: int, wet: dict, rng: np.random.Generator) -> np.ndarray:
        """
        Integrate signal for a given kV using WET data and random sampling

        Args:
            kv (int): Tube potential (kV)
            wet (dict): WET data dictionary
            rng (np.random.Generator): Random number generator

        Returns:
            np.ndarray: Integrated signal array
        """
        pixel_size = self.config.detector_data.pixel_size
        kev, prob = auxfuncs.get_spec_prob(self.config.spectrum_data, kv)
        wet_type = 'primary' #self.config.wet_data.wet_type
        img_shape = self.config.iq_data.img_shape
        edepos = np.zeros((len(kev), img_shape[0], img_shape[1]))
        unc_edepos = np.zeros((len(kev), img_shape[0], img_shape[1]))
        for idx, energy in enumerate(kev):
            energy = np.round(energy/1000, 2)
            edepos[idx, :, :] = np.array(wet[f'{energy}'][wet_type]['edepos'])
            unc_edepos[idx, :, :] = np.array(wet[f'{energy}'][wet_type]['unc_edepos'])
        e_sampled = rng.normal(loc=edepos, scale=unc_edepos)
        prob = prob.reshape((-1,1,1))
        edepos_sampled = np.sum(e_sampled*prob,axis=0)/np.sum(prob)
        edepos_sampled = self._correct_quantity('edepos', edepos_sampled)
        # convert N based on area (from 1x1 cm2 to pixel area)
        edepos_sampled = edepos_sampled*pixel_size[0]*pixel_size[1]
        return edepos_sampled

    def sample_signal(self, kv: int, rng: np.random.Generator) -> dict:
        """
        Sample signal for a given kV multiple times and return mean and uncertainty

        Args:
            kv (int): Tube potential (kV)
            rng (np.random.Generator): Random number generator

        Returns:
            dict: Dictionary with mean and uncertainty of signal
        """
        wet = self.wet_mono
        repeat_samples = self.repeat
        img_shape = self.config.iq_data.img_shape
        imgs = np.zeros((repeat_samples, img_shape[0], img_shape[1]))
        for i in range(repeat_samples):
            edepos_sampled = self.integrate_signal(kv, wet, rng)
            imgs[i, :, :] = edepos_sampled

        mean = np.mean(imgs, axis=0)
        std = np.std(imgs, axis=0, ddof=1)
        mean = self._apply_mas_to_hist(kv, mean)
        std = self._apply_mas_to_hist(kv, std)
        output = {'Signal': mean.tolist(), 'Signal Unc.': std.tolist()}
        return output

    def create_wet_map(self, thick: int) -> dict:
        """
        Parallelize WET map calculations for all kV values at a given thickness

        Args:
            thick (int): Thickness value

        Returns:
            dict: Dictionary containing WET maps for all kV values
        """
        kv_vec = self.config.spectrum_data.kv_vec
        dict_results = {}
        imgs = {}
        rng_generator = self.rng.spawn(len(kv_vec))
        combined = list(zip(kv_vec, rng_generator))
        self.wet_mono = self._load_wet_table_mono(thick)
        with mp.Pool() as pool:
            results = pool.starmap(self.sample_signal, combined)
        for idx, kv in enumerate(kv_vec):
            imgs[f'{kv} (kv)'] = results[idx]
        dict_results['imgs'] = imgs
        return dict_results

    @auxfuncs.measure_time
    def create_wet_map_thicks(self) -> None:
        """
        Calculate WET maps for all thickness values and store results
        """
        self.logger.info('Calculating WET maps')
        for thick in self.config.wet_data.thickness:
            self.wet_thickness[thick] = self.create_wet_map(thick)

    def create_look_up_table(self, kv: int):
        """
        Create a lookup table for WET values at a given kV

        Args:
            kv (int): Tube potential (kV)

        Returns:
            tuple: (interpolated thickness array, interpolated values array)
        """
        thick_vec = self.config.wet_data.thickness
        img_shape = self.config.iq_data.img_shape
        wet_map = np.zeros([len(thick_vec), img_shape[0], img_shape[1]])
        for idx, thick in enumerate(thick_vec):
            wet = self.wet_thickness[thick]['imgs'][f'{kv} (kv)']['Signal']
            wet_map[idx, :, :] = wet

        wet_map = np.log(wet_map)
        cubic = CubicSpline(thick_vec, wet_map, axis=0)
        interp_thick = np.linspace(thick_vec[0], thick_vec[-1], 71)
        interp_vals = cubic(interp_thick)
        return interp_thick, interp_vals

    def find_thick_kv(self, image_signal: np.ndarray, interp_thick: np.ndarray, interp_vals: np.ndarray) -> np.ndarray:
        """
        Find equivalent thickness for a given image signal using interpolation arrays.

        Args:
            image_signal (np.ndarray): Image signal array.
            interp_thick (np.ndarray): Interpolated thickness array.
            interp_vals (np.ndarray): Interpolated values array.

        Returns:
            np.ndarray: Estimated thickness array.
        """
        diff = np.abs(interp_vals - image_signal)
        idx = diff.argmin(axis=0)
        thick = interp_thick[idx.flatten()]
        thick = thick.reshape(image_signal.shape)
        return thick

    def find_thick_all_kv(self, dict_image_phantom: dict) -> dict:
        """
        Find thickness maps for all kV values using phantom image data.

        Args:
            dict_image_phantom (dict): Dictionary of phantom image data.

        Returns:
            dict: Dictionary of thickness maps for all kV values.
        """
        kv_vec = self.config.spectrum_data.kv_vec
        wet_type = self.config.wet_data.wet_type
        thick_map = {}
        for kv in kv_vec:
            img_phantom = dict_image_phantom['imgs'][f'{kv} (kv)'][wet_type.upper()]
            img_phantom = np.array(img_phantom)
            img_phantom = np.log(img_phantom)
            interp_thick, interp_vals = self.create_look_up_table(kv)
            thick = self.find_thick_kv(img_phantom, interp_thick, interp_vals)
            thick_map[kv] = thick

        return thick_map

create_look_up_table(kv)

Create a lookup table for WET values at a given kV

Parameters:

Name Type Description Default
kv int

Tube potential (kV)

required

Returns:

Name Type Description
tuple

(interpolated thickness array, interpolated values array)

Source code in flexpose/wet.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def create_look_up_table(self, kv: int):
    """
    Create a lookup table for WET values at a given kV

    Args:
        kv (int): Tube potential (kV)

    Returns:
        tuple: (interpolated thickness array, interpolated values array)
    """
    thick_vec = self.config.wet_data.thickness
    img_shape = self.config.iq_data.img_shape
    wet_map = np.zeros([len(thick_vec), img_shape[0], img_shape[1]])
    for idx, thick in enumerate(thick_vec):
        wet = self.wet_thickness[thick]['imgs'][f'{kv} (kv)']['Signal']
        wet_map[idx, :, :] = wet

    wet_map = np.log(wet_map)
    cubic = CubicSpline(thick_vec, wet_map, axis=0)
    interp_thick = np.linspace(thick_vec[0], thick_vec[-1], 71)
    interp_vals = cubic(interp_thick)
    return interp_thick, interp_vals

create_wet_map(thick)

Parallelize WET map calculations for all kV values at a given thickness

Parameters:

Name Type Description Default
thick int

Thickness value

required

Returns:

Name Type Description
dict dict

Dictionary containing WET maps for all kV values

Source code in flexpose/wet.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def create_wet_map(self, thick: int) -> dict:
    """
    Parallelize WET map calculations for all kV values at a given thickness

    Args:
        thick (int): Thickness value

    Returns:
        dict: Dictionary containing WET maps for all kV values
    """
    kv_vec = self.config.spectrum_data.kv_vec
    dict_results = {}
    imgs = {}
    rng_generator = self.rng.spawn(len(kv_vec))
    combined = list(zip(kv_vec, rng_generator))
    self.wet_mono = self._load_wet_table_mono(thick)
    with mp.Pool() as pool:
        results = pool.starmap(self.sample_signal, combined)
    for idx, kv in enumerate(kv_vec):
        imgs[f'{kv} (kv)'] = results[idx]
    dict_results['imgs'] = imgs
    return dict_results

create_wet_map_thicks()

Calculate WET maps for all thickness values and store results

Source code in flexpose/wet.py
177
178
179
180
181
182
183
184
@auxfuncs.measure_time
def create_wet_map_thicks(self) -> None:
    """
    Calculate WET maps for all thickness values and store results
    """
    self.logger.info('Calculating WET maps')
    for thick in self.config.wet_data.thickness:
        self.wet_thickness[thick] = self.create_wet_map(thick)

find_thick_all_kv(dict_image_phantom)

Find thickness maps for all kV values using phantom image data.

Parameters:

Name Type Description Default
dict_image_phantom dict

Dictionary of phantom image data.

required

Returns:

Name Type Description
dict dict

Dictionary of thickness maps for all kV values.

Source code in flexpose/wet.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def find_thick_all_kv(self, dict_image_phantom: dict) -> dict:
    """
    Find thickness maps for all kV values using phantom image data.

    Args:
        dict_image_phantom (dict): Dictionary of phantom image data.

    Returns:
        dict: Dictionary of thickness maps for all kV values.
    """
    kv_vec = self.config.spectrum_data.kv_vec
    wet_type = self.config.wet_data.wet_type
    thick_map = {}
    for kv in kv_vec:
        img_phantom = dict_image_phantom['imgs'][f'{kv} (kv)'][wet_type.upper()]
        img_phantom = np.array(img_phantom)
        img_phantom = np.log(img_phantom)
        interp_thick, interp_vals = self.create_look_up_table(kv)
        thick = self.find_thick_kv(img_phantom, interp_thick, interp_vals)
        thick_map[kv] = thick

    return thick_map

find_thick_kv(image_signal, interp_thick, interp_vals)

Find equivalent thickness for a given image signal using interpolation arrays.

Parameters:

Name Type Description Default
image_signal ndarray

Image signal array.

required
interp_thick ndarray

Interpolated thickness array.

required
interp_vals ndarray

Interpolated values array.

required

Returns:

Type Description
ndarray

np.ndarray: Estimated thickness array.

Source code in flexpose/wet.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def find_thick_kv(self, image_signal: np.ndarray, interp_thick: np.ndarray, interp_vals: np.ndarray) -> np.ndarray:
    """
    Find equivalent thickness for a given image signal using interpolation arrays.

    Args:
        image_signal (np.ndarray): Image signal array.
        interp_thick (np.ndarray): Interpolated thickness array.
        interp_vals (np.ndarray): Interpolated values array.

    Returns:
        np.ndarray: Estimated thickness array.
    """
    diff = np.abs(interp_vals - image_signal)
    idx = diff.argmin(axis=0)
    thick = interp_thick[idx.flatten()]
    thick = thick.reshape(image_signal.shape)
    return thick

integrate_signal(kv, wet, rng)

Integrate signal for a given kV using WET data and random sampling

Parameters:

Name Type Description Default
kv int

Tube potential (kV)

required
wet dict

WET data dictionary

required
rng Generator

Random number generator

required

Returns:

Type Description
ndarray

np.ndarray: Integrated signal array

Source code in flexpose/wet.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def integrate_signal(self, kv: int, wet: dict, rng: np.random.Generator) -> np.ndarray:
    """
    Integrate signal for a given kV using WET data and random sampling

    Args:
        kv (int): Tube potential (kV)
        wet (dict): WET data dictionary
        rng (np.random.Generator): Random number generator

    Returns:
        np.ndarray: Integrated signal array
    """
    pixel_size = self.config.detector_data.pixel_size
    kev, prob = auxfuncs.get_spec_prob(self.config.spectrum_data, kv)
    wet_type = 'primary' #self.config.wet_data.wet_type
    img_shape = self.config.iq_data.img_shape
    edepos = np.zeros((len(kev), img_shape[0], img_shape[1]))
    unc_edepos = np.zeros((len(kev), img_shape[0], img_shape[1]))
    for idx, energy in enumerate(kev):
        energy = np.round(energy/1000, 2)
        edepos[idx, :, :] = np.array(wet[f'{energy}'][wet_type]['edepos'])
        unc_edepos[idx, :, :] = np.array(wet[f'{energy}'][wet_type]['unc_edepos'])
    e_sampled = rng.normal(loc=edepos, scale=unc_edepos)
    prob = prob.reshape((-1,1,1))
    edepos_sampled = np.sum(e_sampled*prob,axis=0)/np.sum(prob)
    edepos_sampled = self._correct_quantity('edepos', edepos_sampled)
    # convert N based on area (from 1x1 cm2 to pixel area)
    edepos_sampled = edepos_sampled*pixel_size[0]*pixel_size[1]
    return edepos_sampled

sample_signal(kv, rng)

Sample signal for a given kV multiple times and return mean and uncertainty

Parameters:

Name Type Description Default
kv int

Tube potential (kV)

required
rng Generator

Random number generator

required

Returns:

Name Type Description
dict dict

Dictionary with mean and uncertainty of signal

Source code in flexpose/wet.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def sample_signal(self, kv: int, rng: np.random.Generator) -> dict:
    """
    Sample signal for a given kV multiple times and return mean and uncertainty

    Args:
        kv (int): Tube potential (kV)
        rng (np.random.Generator): Random number generator

    Returns:
        dict: Dictionary with mean and uncertainty of signal
    """
    wet = self.wet_mono
    repeat_samples = self.repeat
    img_shape = self.config.iq_data.img_shape
    imgs = np.zeros((repeat_samples, img_shape[0], img_shape[1]))
    for i in range(repeat_samples):
        edepos_sampled = self.integrate_signal(kv, wet, rng)
        imgs[i, :, :] = edepos_sampled

    mean = np.mean(imgs, axis=0)
    std = np.std(imgs, axis=0, ddof=1)
    mean = self._apply_mas_to_hist(kv, mean)
    std = self._apply_mas_to_hist(kv, std)
    output = {'Signal': mean.tolist(), 'Signal Unc.': std.tolist()}
    return output