Skip to content

Core Engine & Optimization

The execution layer of Flexpose. This includes the SNR optimizers, the multi-processed calculators, and the main CLI entry points.

Optimization

flexpose.optimizer

OptimizeSNR

Source code in flexpose/optimizer.py
 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
class OptimizeSNR:
    def __init__(self, config: dataformats.ConfigData, measure_cls : measure.Measure, 
                 observer_cls : BaseObserver, dose_cls : dose.CalcDose) -> None:
        """
        Initialize the OptimizeSNR class with configuration and required measurement, observer, and dose classes.

        Args:
            config (dataformats.ConfigData): Configuration data object.
            measure_cls (measure.Measure): Measurement class instance.
            observer_cls (BaseObserver): Observer class instance.
            dose_cls (dose.CalcDose): Dose calculation class instance.
        """
        self.config : dataformats.ConfigData =  config
        self.measurer : measure.Measure = measure_cls
        self.rng : np.random.Generator | None =  None
        self.observer: BaseObserver = observer_cls
        self.dose : dose.CalcDose = dose_cls
        self.index : int | None = None


        if isinstance(self.config.general_config, dataformats.ConfigCalculator):
            raise TypeError("Expected ConfigGeneral, not ConfigCalculator")


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

        Args:
            rng (np.random.Generator): Random number generator instance.
        """
        self.rng = rng
        self.measurer.set_rng(self.rng)
        self.measurer.sample_pixels()

    def set_index(self, index: int) -> None:
        """
        Set the index for the optimizer instance (used for result file naming).

        Args:
            index (int): Index value.
        """
        self.index = index


    def _calc_snr_observer(self, t: float, ma: float, kv: int, focus_size_xy: tuple[float, float]) -> float:
        """
        Calculate the product of SNR and observer value for given parameters.

        Args:
            t (float): Exposure time.
            ma (float): Tube current (mA).
            kv (int): Tube potential (kV).
            focus_size_xy (tuple): Focal spot size (x, y).

        Returns:
            float: SNR multiplied by observer value.
        """


        params = AcquisitionParams(
                focus_size_xy=focus_size_xy,
                exposure_time_s=t,
            )
        gamma = self.observer.compute_gamma(params)

        #observer_val = self.observer.calc_observer(focus_size_xy, t)
        snr = self.measurer.measure_snr(kv, t, ma)
        return snr*gamma

    def _snr_wrapper_mas(self, ma: float, t: float, kv: int, focus_size_xy: tuple[float, float]) -> float:
        """
        Wrapper function for SNR optimization with respect to mA.

        Args:
            ma (float): Tube current (mA).
            t (float): Exposure time.
            kv (float): Tube potential (kV).
            focus_size_xy (tuple): Focal spot size (x, y).

        Returns:
            float: Squared difference between calculated and target SNR.
        """
        target_snr = self.config.general_config.minimum_snr
        snr = self._calc_snr_observer(t, ma, kv, focus_size_xy)
        return (snr-target_snr)**2


    def _solve_ma_equation(self, t: float, kv: int, focus_size_xy: tuple[float, float]) -> float:
        """
        Solve for mA required to achieve the target SNR for given parameters.

        Args:
            t (float): Exposure time.
            kv (int): Tube potential (kV).
            focus_size_xy (tuple): Focal spot size (x, y).

        Returns:
            float: Required mA value.
        """
        target_snr = self.config.general_config.minimum_snr
        snr_1ma = self._calc_snr_observer(t, 1, kv, focus_size_xy)
        ma = (target_snr/snr_1ma)**2
        return ma


    def solve_pulse_length(self, kv: int, focus: dataformats.FocalSpotSize) -> tuple[np.ndarray, np.ndarray]:
        """
        Calculate observer values and corresponding exposure times for a range of pulse lengths.

        Args:
            kv (int): Tube potential (kV).
            focus (dict): Focal spot information.

        Returns:
            tuple: (observer values array, exposure times array)
        """
        tmax = self.config.xray_tube_data.max_exposure_time
        tmin = self.config.xray_tube_data.min_exposure_time
        tvec = np.linspace(tmin, tmax, 50)
        focus_size_xy = (focus['size_x'], focus['size_y'])
        observer_val = np.zeros(len(tvec))
        for idx, t in enumerate(tvec):
            #observer_val[idx] = self.observer.calc_observer(focus_size_xy, t)
            params = AcquisitionParams(focus_size_xy=focus_size_xy, exposure_time_s=t)
            observer_val[idx] = self.observer.compute_gamma(params)
        order = observer_val.argsort()
        observer_val = observer_val[order[::-1]]
        tvec = tvec[order[::-1]]
        #snr_ma = observer_val*np.sqrt(tvec)*snr
        return observer_val, tvec

    def solver_snr_observer(self, kv: int, focus: dataformats.FocalSpotSize) -> tuple[float, float, float]:
        """
        Solve for optimal exposure time and mA to achieve target SNR for a given focal spot and kV.
        Applies air kerma rate constraints.

        Args:
            kv (float): Tube potential (kV).
            focus (dict): Focal spot information.

        Returns:
            tuple: (optimal exposure time, optimal mA, achieved SNR)
        """
        target_snr = self.config.general_config.minimum_snr
        focus_label = focus['label']
        focus_size = (focus['size_x'], focus['size_y'])
        df = self.config.xray_tube_data.tube_specs
        if df is not None:
            max_ma = df.loc[df['Tube Potential (kV)'] == kv][focus_label].values[0]
            if max_ma > focus['max_ma']:
                max_ma = focus['max_ma']
        else: 
            max_ma = focus['max_ma']

        min_ma = focus['min_ma']
        min_t = self.config.xray_tube_data.min_exposure_time
        observer_val, tvec = self.solve_pulse_length(kv, focus)
        max_kerma_rate = self.config.general_config.maximum_kerma_rate


        # here we apply the max air kerma rate constrain
        max_ma_vec = []
        for t in tvec:
            res = self.measurer.calc_img_quality(kv, t, 1)
            res = self.measurer.calc_entrance_kerma(res)
            air_kerma_1ma = res['Entrance kerma (mGy/min)']
            max_ma_tmp = max_kerma_rate/air_kerma_1ma
            max_ma_vec.append(max_ma_tmp)

        max_ma_vec = np.array(max_ma_vec)
        max_ma_vec[max_ma_vec>max_ma] = max_ma

        snr_max_ma = self.measurer.measure_snr(kv, tvec, max_ma_vec)
        snr_max = snr_max_ma*observer_val
        achieved_mask = (snr_max >= target_snr)

        # Case 1: Target SNR cannot be achieved (select point of maximum SNR)
        if not np.any(achieved_mask):
            argmax = np.argmax(snr_max)
            t = tvec[argmax]
            ma = max_ma_vec[argmax]
        else:
            # Candidate times ordered from best observer score to worst
            tvec_achieved = tvec[achieved_mask]
            max_ma_vec_achieved = max_ma_vec[achieved_mask]
            observer_val_achieved = observer_val[achieved_mask]

            # Compute SNR at min_ma for all achieved t
            snr_min_ma_vec = self.measurer.measure_snr(kv, tvec_achieved, min_ma)
            snr_at_min_ma = snr_min_ma_vec * observer_val_achieved

            # Check overshoot condition (>1% above target) across all candidate times
            overshoots = snr_at_min_ma > 1.01 * target_snr

            # Find candidate times that do NOT overshoot
            valid_indices = np.where(~overshoots)[0]

            if len(valid_indices) > 0:
                # Pick the first index (best observer score) that doesn't overshoot
                best_idx = valid_indices[0]
            else:
                # If ALL candidates overshoot, select the one with the lowest exposure time (ms)
                best_idx = np.argmin(tvec_achieved)

            t = tvec_achieved[best_idx]
            max_ma = max_ma_vec_achieved[best_idx]

            bnds = [(1.0, max_ma)]
            if self.rng is None:
                initial_guess = max_ma*0.5
            else:
                initial_guess = self.rng.uniform(1.0, max_ma)
            required_ma = optimize.minimize(fun=self._snr_wrapper_mas, x0=initial_guess, args=(t, kv, focus_size), bounds=bnds)
            ma = required_ma.x[0]
            ma = min(ma, max_ma)
            ma = max(ma, min_ma)



        res = self.measurer.calc_img_quality(kv, t, ma)
        res = self.measurer.calc_entrance_kerma(res)
        air_kerma_rate = res['Entrance kerma (mGy/min)']

        # as a last resort, we decrease t if we cannot decrease mA anymore
        if air_kerma_rate > max_kerma_rate:
            t *= max_kerma_rate/air_kerma_rate
            t = max(t, min_t)
        snr_opt = self._calc_snr_observer(t, ma, kv, focus_size_xy=focus_size)

        return t, ma, snr_opt


    def calc_dose_val(self, kv: int, cost: str, t: float, ma: float) -> float:
        """
        Calculate the dose value for given parameters, optionally with uncertainty

        Args:
            kv (int): Tube potential (kV).
            cost (str): Cost function name.
            t (float): Exposure time.
            ma (float): Tube current (mA).

        Returns:
            float: Calculated dose value.
        """
        df = self.dose.export_df
        dose_val = df.loc[df['Potential (kV)'] == kv][cost].values[0]
        if self.rng is not None:
            unc_dose_val = df.loc[df['Potential (kV)'] == kv][f'{cost} Unc.'].values[0]
            dose_val = self.rng.normal(dose_val, unc_dose_val)
        dose_val = dose_val*t*ma
        return dose_val


    def calc_fom(self, kv: int, focus: dataformats.FocalSpotSize) -> dict:
        """
        Calculate the figure of merit (FOM) and other image/dosimetry metrics for given kV and focal spot

        Args:
            kv (float): Tube potential (kV).
            focus (dict): Focal spot information.

        Returns:
            dict: Dictionary of calculated metrics and FOM.
        """
        cost = self.config.dose_data.cost_function
        target_snr = self.config.general_config.minimum_snr
        t, ma, snr_opt = self.solver_snr_observer(kv, focus)
        res = self.measurer.calc_img_quality(kv, t, ma)
        focus_size_xy = (focus['size_x'], focus['size_y'])
        params = AcquisitionParams(
                focus_size_xy=focus_size_xy,
                exposure_time_s=t,
            )
        gamma = self.observer.compute_gamma(params)
        res['Gamma'] =  gamma
        res['SNRW'] = res['SNR']*gamma

        dose_val = self.calc_dose_val(kv, cost, t, ma)
        #IQ overshoot signal
        if snr_opt>1.01*target_snr:
            res['Overshoot'] = 1
        else:
            res['Overshoot'] = 0
        fom = snr_opt**2/dose_val
        res['FOM'] = fom
        res[cost] = dose_val

        other_dosimetry = self.config.dose_data.dosimetry_list

        for dosimetry in other_dosimetry:
            dosimetry_mas = dosimetry.replace('hist', 'mAs')
            res[dosimetry_mas] = self.calc_dose_val(kv, dosimetry_mas, t, ma)
        return res

    def run_optimizer_focus(self, focus: dataformats.FocalSpotSize) -> dict:
        """
        Run optimization for a single focal spot across all kV values.

        Args:
            focus (dataformats.FocalSpotSize): Focal spot size information.

        Returns:
            dict: Results for each kV value.
        """
        kv_vec = self.config.spectrum_data.kv_vec
        results = {}
        for kv in kv_vec:
            min_snr = self.config.general_config.minimum_snr
            res = self.calc_fom(kv, focus)
            res['Potential (kV)'] = kv
            res['Focus'] = focus['label']
            if res['SNRW'] >= min_snr*0.99:
                res['Achieved'] = 1
            else:
                res['Achieved'] = 0
            results[kv] = res
        return results


    def run_optmizer(self) -> None:
        """
        Run optimization for all focal spot options and save results
        """
        focus_options = self.config.xray_tube_data.focal_spot_sizes
        for focus in focus_options:
            results = self.run_optimizer_focus(focus)
            self.save_results(focus, results)


    def save_results(self, focus: dataformats.FocalSpotSize, results: dict) -> None:
        """
        Save optimization results to a JSON file for a given focal spot

        Args:
            focus (dataformats.FocalSpotSize): Focal spot size information
            results (dict): Optimization results
        """
        output_path = self.config.general_config.output_folder
        focus_label = focus['label']
        output_path = f'{output_path}/opt/{focus_label}'
        Path(output_path).mkdir(parents=True, exist_ok=True)
        if self.index is None:
            dictname = f'{output_path}/opt.json'
        else:
            dictname = f'{output_path}/opt_{self.index}.json'
        with open(dictname, 'w') as f:
            json.dump(results, f, indent=3)

calc_dose_val(kv, cost, t, ma)

Calculate the dose value for given parameters, optionally with uncertainty

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
cost str

Cost function name.

required
t float

Exposure time.

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Calculated dose value.

Source code in flexpose/optimizer.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def calc_dose_val(self, kv: int, cost: str, t: float, ma: float) -> float:
    """
    Calculate the dose value for given parameters, optionally with uncertainty

    Args:
        kv (int): Tube potential (kV).
        cost (str): Cost function name.
        t (float): Exposure time.
        ma (float): Tube current (mA).

    Returns:
        float: Calculated dose value.
    """
    df = self.dose.export_df
    dose_val = df.loc[df['Potential (kV)'] == kv][cost].values[0]
    if self.rng is not None:
        unc_dose_val = df.loc[df['Potential (kV)'] == kv][f'{cost} Unc.'].values[0]
        dose_val = self.rng.normal(dose_val, unc_dose_val)
    dose_val = dose_val*t*ma
    return dose_val

calc_fom(kv, focus)

Calculate the figure of merit (FOM) and other image/dosimetry metrics for given kV and focal spot

Parameters:

Name Type Description Default
kv float

Tube potential (kV).

required
focus dict

Focal spot information.

required

Returns:

Name Type Description
dict dict

Dictionary of calculated metrics and FOM.

Source code in flexpose/optimizer.py
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
def calc_fom(self, kv: int, focus: dataformats.FocalSpotSize) -> dict:
    """
    Calculate the figure of merit (FOM) and other image/dosimetry metrics for given kV and focal spot

    Args:
        kv (float): Tube potential (kV).
        focus (dict): Focal spot information.

    Returns:
        dict: Dictionary of calculated metrics and FOM.
    """
    cost = self.config.dose_data.cost_function
    target_snr = self.config.general_config.minimum_snr
    t, ma, snr_opt = self.solver_snr_observer(kv, focus)
    res = self.measurer.calc_img_quality(kv, t, ma)
    focus_size_xy = (focus['size_x'], focus['size_y'])
    params = AcquisitionParams(
            focus_size_xy=focus_size_xy,
            exposure_time_s=t,
        )
    gamma = self.observer.compute_gamma(params)
    res['Gamma'] =  gamma
    res['SNRW'] = res['SNR']*gamma

    dose_val = self.calc_dose_val(kv, cost, t, ma)
    #IQ overshoot signal
    if snr_opt>1.01*target_snr:
        res['Overshoot'] = 1
    else:
        res['Overshoot'] = 0
    fom = snr_opt**2/dose_val
    res['FOM'] = fom
    res[cost] = dose_val

    other_dosimetry = self.config.dose_data.dosimetry_list

    for dosimetry in other_dosimetry:
        dosimetry_mas = dosimetry.replace('hist', 'mAs')
        res[dosimetry_mas] = self.calc_dose_val(kv, dosimetry_mas, t, ma)
    return res

run_optimizer_focus(focus)

Run optimization for a single focal spot across all kV values.

Parameters:

Name Type Description Default
focus FocalSpotSize

Focal spot size information.

required

Returns:

Name Type Description
dict dict

Results for each kV value.

Source code in flexpose/optimizer.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def run_optimizer_focus(self, focus: dataformats.FocalSpotSize) -> dict:
    """
    Run optimization for a single focal spot across all kV values.

    Args:
        focus (dataformats.FocalSpotSize): Focal spot size information.

    Returns:
        dict: Results for each kV value.
    """
    kv_vec = self.config.spectrum_data.kv_vec
    results = {}
    for kv in kv_vec:
        min_snr = self.config.general_config.minimum_snr
        res = self.calc_fom(kv, focus)
        res['Potential (kV)'] = kv
        res['Focus'] = focus['label']
        if res['SNRW'] >= min_snr*0.99:
            res['Achieved'] = 1
        else:
            res['Achieved'] = 0
        results[kv] = res
    return results

run_optmizer()

Run optimization for all focal spot options and save results

Source code in flexpose/optimizer.py
340
341
342
343
344
345
346
347
def run_optmizer(self) -> None:
    """
    Run optimization for all focal spot options and save results
    """
    focus_options = self.config.xray_tube_data.focal_spot_sizes
    for focus in focus_options:
        results = self.run_optimizer_focus(focus)
        self.save_results(focus, results)

save_results(focus, results)

Save optimization results to a JSON file for a given focal spot

Parameters:

Name Type Description Default
focus FocalSpotSize

Focal spot size information

required
results dict

Optimization results

required
Source code in flexpose/optimizer.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def save_results(self, focus: dataformats.FocalSpotSize, results: dict) -> None:
    """
    Save optimization results to a JSON file for a given focal spot

    Args:
        focus (dataformats.FocalSpotSize): Focal spot size information
        results (dict): Optimization results
    """
    output_path = self.config.general_config.output_folder
    focus_label = focus['label']
    output_path = f'{output_path}/opt/{focus_label}'
    Path(output_path).mkdir(parents=True, exist_ok=True)
    if self.index is None:
        dictname = f'{output_path}/opt.json'
    else:
        dictname = f'{output_path}/opt_{self.index}.json'
    with open(dictname, 'w') as f:
        json.dump(results, f, indent=3)

set_index(index)

Set the index for the optimizer instance (used for result file naming).

Parameters:

Name Type Description Default
index int

Index value.

required
Source code in flexpose/optimizer.py
54
55
56
57
58
59
60
61
def set_index(self, index: int) -> None:
    """
    Set the index for the optimizer instance (used for result file naming).

    Args:
        index (int): Index value.
    """
    self.index = index

set_rng(rng)

Set the random number generator for reproducibility and update measurer.

Parameters:

Name Type Description Default
rng Generator

Random number generator instance.

required
Source code in flexpose/optimizer.py
43
44
45
46
47
48
49
50
51
52
def set_rng(self, rng: np.random.Generator) -> None:
    """
    Set the random number generator for reproducibility and update measurer.

    Args:
        rng (np.random.Generator): Random number generator instance.
    """
    self.rng = rng
    self.measurer.set_rng(self.rng)
    self.measurer.sample_pixels()

solve_pulse_length(kv, focus)

Calculate observer values and corresponding exposure times for a range of pulse lengths.

Parameters:

Name Type Description Default
kv int

Tube potential (kV).

required
focus dict

Focal spot information.

required

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

(observer values array, exposure times array)

Source code in flexpose/optimizer.py
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
def solve_pulse_length(self, kv: int, focus: dataformats.FocalSpotSize) -> tuple[np.ndarray, np.ndarray]:
    """
    Calculate observer values and corresponding exposure times for a range of pulse lengths.

    Args:
        kv (int): Tube potential (kV).
        focus (dict): Focal spot information.

    Returns:
        tuple: (observer values array, exposure times array)
    """
    tmax = self.config.xray_tube_data.max_exposure_time
    tmin = self.config.xray_tube_data.min_exposure_time
    tvec = np.linspace(tmin, tmax, 50)
    focus_size_xy = (focus['size_x'], focus['size_y'])
    observer_val = np.zeros(len(tvec))
    for idx, t in enumerate(tvec):
        #observer_val[idx] = self.observer.calc_observer(focus_size_xy, t)
        params = AcquisitionParams(focus_size_xy=focus_size_xy, exposure_time_s=t)
        observer_val[idx] = self.observer.compute_gamma(params)
    order = observer_val.argsort()
    observer_val = observer_val[order[::-1]]
    tvec = tvec[order[::-1]]
    #snr_ma = observer_val*np.sqrt(tvec)*snr
    return observer_val, tvec

solver_snr_observer(kv, focus)

Solve for optimal exposure time and mA to achieve target SNR for a given focal spot and kV. Applies air kerma rate constraints.

Parameters:

Name Type Description Default
kv float

Tube potential (kV).

required
focus dict

Focal spot information.

required

Returns:

Name Type Description
tuple tuple[float, float, float]

(optimal exposure time, optimal mA, achieved SNR)

Source code in flexpose/optimizer.py
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
def solver_snr_observer(self, kv: int, focus: dataformats.FocalSpotSize) -> tuple[float, float, float]:
    """
    Solve for optimal exposure time and mA to achieve target SNR for a given focal spot and kV.
    Applies air kerma rate constraints.

    Args:
        kv (float): Tube potential (kV).
        focus (dict): Focal spot information.

    Returns:
        tuple: (optimal exposure time, optimal mA, achieved SNR)
    """
    target_snr = self.config.general_config.minimum_snr
    focus_label = focus['label']
    focus_size = (focus['size_x'], focus['size_y'])
    df = self.config.xray_tube_data.tube_specs
    if df is not None:
        max_ma = df.loc[df['Tube Potential (kV)'] == kv][focus_label].values[0]
        if max_ma > focus['max_ma']:
            max_ma = focus['max_ma']
    else: 
        max_ma = focus['max_ma']

    min_ma = focus['min_ma']
    min_t = self.config.xray_tube_data.min_exposure_time
    observer_val, tvec = self.solve_pulse_length(kv, focus)
    max_kerma_rate = self.config.general_config.maximum_kerma_rate


    # here we apply the max air kerma rate constrain
    max_ma_vec = []
    for t in tvec:
        res = self.measurer.calc_img_quality(kv, t, 1)
        res = self.measurer.calc_entrance_kerma(res)
        air_kerma_1ma = res['Entrance kerma (mGy/min)']
        max_ma_tmp = max_kerma_rate/air_kerma_1ma
        max_ma_vec.append(max_ma_tmp)

    max_ma_vec = np.array(max_ma_vec)
    max_ma_vec[max_ma_vec>max_ma] = max_ma

    snr_max_ma = self.measurer.measure_snr(kv, tvec, max_ma_vec)
    snr_max = snr_max_ma*observer_val
    achieved_mask = (snr_max >= target_snr)

    # Case 1: Target SNR cannot be achieved (select point of maximum SNR)
    if not np.any(achieved_mask):
        argmax = np.argmax(snr_max)
        t = tvec[argmax]
        ma = max_ma_vec[argmax]
    else:
        # Candidate times ordered from best observer score to worst
        tvec_achieved = tvec[achieved_mask]
        max_ma_vec_achieved = max_ma_vec[achieved_mask]
        observer_val_achieved = observer_val[achieved_mask]

        # Compute SNR at min_ma for all achieved t
        snr_min_ma_vec = self.measurer.measure_snr(kv, tvec_achieved, min_ma)
        snr_at_min_ma = snr_min_ma_vec * observer_val_achieved

        # Check overshoot condition (>1% above target) across all candidate times
        overshoots = snr_at_min_ma > 1.01 * target_snr

        # Find candidate times that do NOT overshoot
        valid_indices = np.where(~overshoots)[0]

        if len(valid_indices) > 0:
            # Pick the first index (best observer score) that doesn't overshoot
            best_idx = valid_indices[0]
        else:
            # If ALL candidates overshoot, select the one with the lowest exposure time (ms)
            best_idx = np.argmin(tvec_achieved)

        t = tvec_achieved[best_idx]
        max_ma = max_ma_vec_achieved[best_idx]

        bnds = [(1.0, max_ma)]
        if self.rng is None:
            initial_guess = max_ma*0.5
        else:
            initial_guess = self.rng.uniform(1.0, max_ma)
        required_ma = optimize.minimize(fun=self._snr_wrapper_mas, x0=initial_guess, args=(t, kv, focus_size), bounds=bnds)
        ma = required_ma.x[0]
        ma = min(ma, max_ma)
        ma = max(ma, min_ma)



    res = self.measurer.calc_img_quality(kv, t, ma)
    res = self.measurer.calc_entrance_kerma(res)
    air_kerma_rate = res['Entrance kerma (mGy/min)']

    # as a last resort, we decrease t if we cannot decrease mA anymore
    if air_kerma_rate > max_kerma_rate:
        t *= max_kerma_rate/air_kerma_rate
        t = max(t, min_t)
    snr_opt = self._calc_snr_observer(t, ma, kv, focus_size_xy=focus_size)

    return t, ma, snr_opt

OptimizeSNRMP

Source code in flexpose/optimizer.py
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
class OptimizeSNRMP:
    def __init__(self, config: dataformats.ConfigData, measure_cls: measure.Measure, 
                 observer_cls: BaseObserver, dose_cls: dose.CalcDose) -> None:
        """
        Initialize the OptimizeSNRMP class for multiprocessing optimization.

        Args:
            config (dataformats.ConfigData): Configuration data object.
            measure_cls (measure.Measure): Measurement class instance.
            observer_cls (observer.Observer): Observer class instance.
            dose_cls (dose.CalcDose): Dose calculation class instance.
        """

        self.logger = auxfuncs.Logger(logdir=str(config.general_config.output_folder), logname='optimizer')
        self.config : dataformats.ConfigData =  config
        self.measurer : measure.Measure = measure_cls
        self.observer: BaseObserver = observer_cls
        self.dose : dose.CalcDose = dose_cls
        self.optimizers : list[OptimizeSNR] = self.make_optimizers()
        self.elements_average = self.generate_elements_average()

    def generate_elements_average(self) -> list[str]:
        """
        Generate a list of elements to be averaged in the optimization results.

        Returns:
            list: List of element names for averaging.
        """
        average_list = ['mA', 'ms', 'SNR', 'Gamma', 'SNRW',
                            'Contrast', 'FOM', self.config.dose_data.cost_function, 
                            'PV BG', 'PV OBJ', 'Noise BG', 'Noise OBJ', 'PV BG P', 'DET KERMA (nGy)', 'Entrance kerma (mGy/min)',
                            'Achieved', 'Overshoot']
        other_dosimetry = self.config.dose_data.dosimetry_list
        for dosimetry in other_dosimetry:
            dosimetry_mas = dosimetry.replace('hist', 'mAs')
            average_list.append(dosimetry_mas)
        return average_list


    def make_optimizers(self) -> list[OptimizeSNR]:
        """
        Create a list of OptimizeSNR instances for each repetition, with independent RNGs if needed.

        Returns:
            list: List of OptimizeSNR instances.
        """
        if self.config.general_config.repetitions == 1:
            optimizers = [OptimizeSNR(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                           dose_cls = self.dose)]
            seed = None
        else:
            rng, seed = auxfuncs.make_rng(self.config.general_config.seed)
            optimizers = []
            rng_children = rng.spawn(self.config.general_config.repetitions)
            optimizer = OptimizeSNR(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                           dose_cls = self.dose)
            for i in range(self.config.general_config.repetitions):
                optimizer_copy = copy.deepcopy(optimizer)
                optimizer_copy.set_rng(rng_children[i])
                optimizer_copy.set_index(i)
                optimizers.append(optimizer_copy)
        self.logger.info(f'Using seed {seed}')
        return optimizers

    def run_optimizer_wrapper(self, idx: int) -> None:
        """
        Run the optimizer for a specific repetition index.

        Args:
            idx (int): Index of the optimizer to run.
        """
        optimizer = self.optimizers[idx]
        optimizer.run_optmizer()

    def run_optimizers_mp(self) -> None:
        """
        Run all optimizers in parallel using multiprocessing.
        """
        repetitions = self.config.general_config.repetitions
        if  repetitions == 1:
            self.run_optimizer_wrapper(0)
        else:
            with mp.Pool() as pool:
                pool.map(self.run_optimizer_wrapper, list(range(repetitions)))

    def run(self) -> None:
        """
        Run the full optimization workflow, including merging results and selecting optimal focus.
        """
        self.run_optimizers_mp()
        focus_options = self.config.xray_tube_data.focal_spot_sizes
        for focus in focus_options:
            self.merge_results_focus(focus)

        self.select_focus()


    def merge_results_kv(self, results: list[dict], kv: int) -> dict:
        """
        Merge results for a specific kV value across repetitions, averaging relevant metrics.

        Args:
            results (list): List of result dictionaries.
            kv (int): Tube potential (kV).

        Returns:
            dict: Merged results for the given kV.
        """
        results_list = []
        achieved_list = [] 
        achieved = 0
        failed = True
        for result in results:
            result_kv = result[str(kv)]
            results_list.append(result_kv)
            achieved_list.append(result_kv['Achieved'])
            achieved += result_kv['Achieved']
        if achieved > len(achieved_list) // 2:
            failed = False

        results_filtered = []
        if failed:
            for result in results_list:
                if result['Achieved'] == 0:
                    results_filtered.append(result)
        else:
            for result in results_list:
                if result['Achieved'] == 1:
                    results_filtered.append(result)

        merged_results = {}
        for key in list(results_filtered[0].keys()):
            if key not in self.elements_average:
                merged_results[key] = results_filtered[0][key]
            else:
                merged_results[key] = np.mean([value[key] for value in results_list])
                if len(results_list) > 3:
                    merged_results[f'{key} Unc.'] = np.std([value[key] for value in results_list], ddof=1)
        if failed:
            merged_results['Achieved'] = 0
            merged_results['Agreement'] = 1 - achieved/len(achieved_list)
        else:
            merged_results['Achieved'] = 1
            merged_results['Agreement'] = achieved/len(achieved_list)

        return merged_results


    def merge_results_focus(self, focus: dataformats.FocalSpotSize) -> None:
        """
        Merge results for all kV values for a given focal spot and save to file.

        Args:
            focus (dict): Focal spot information.
        """
        output_path = self.config.general_config.output_folder
        focus_label = focus['label']
        output_path = f'{output_path}/opt/{focus_label}'
        results = glob.glob(f'{output_path}/opt*.json')
        results_list = []

        dict_results = {}

        for fpath in results:
            with open(fpath, 'r') as f:
                json_dict = json.load(f)
            results_list.append(json_dict)

        for kv in self.config.spectrum_data.kv_vec:
            merged_kv = self.merge_results_kv(results=results_list, kv=kv)
            dict_results[str(kv)] = merged_kv

        save_path = f'{output_path}/merged.json'
        with open(save_path, 'w') as f:
            json.dump(dict_results, f, indent=3)

    def select_focus_kv(self, dict_results_list: list[dict], kv: int) -> dict:
        """
        Select the optimal focus for a given kV value based on FOM or SNRW.

        Args:
            dict_results_list (list): List of merged result dictionaries for each focus.
            kv (float): Tube potential (kV).

        Returns:
            dict: Selected focus result for the given kV.
        """
        row_list = []
        achieved_list = []
        for dict_res in dict_results_list:
            row = dict_res[str(kv)]
            row_list.append(row)
            if row['Achieved'] == 1:
                achieved_list.append(row)

        # Case 1: at least one focus achieved the target IQ
        if len(achieved_list)>0:
            fom = 0
            fom_unc = 0
            idx_selected = None
            for idx, achieved in enumerate(achieved_list):
                if achieved['FOM']>fom:
                    z = np.abs(achieved['FOM']-fom)/np.sqrt(achieved['FOM Unc.']**2 + fom_unc**2 + 1E-20)
                    achieved['Z'] = z
                    idx_selected = int(idx)
                    fom = achieved['FOM']
                    fom_unc = achieved['FOM Unc.']
            if idx_selected is None:
                raise ValueError("No focus selected for this kV.")
            return achieved_list[idx_selected]

        # Case 2: no focus achieved the target IQ, select the one with highest IQ
        snru = 0
        snru_unc = 0
        idx_selected = None
        for idx, achieved in enumerate(row_list):
            if achieved['SNRW']>snru:
                z = np.abs(achieved['SNRW']-snru)/np.sqrt(achieved['SNRW Unc.']**2 + snru_unc**2 + 1E-20)
                achieved['Z'] = z
                idx_selected = idx
                snru = achieved['SNRW']
                snru_unc = achieved['SNRW Unc.']
        if idx_selected is None:
            raise ValueError("No focus selected for this kV.")
        return row_list[idx_selected]

    def select_focus(self) -> None:
        """
        Select the optimal focus across all kV values and save the selected parameters to a file.
        """
        dict_results_list = []
        focus_options = self.config.xray_tube_data.focal_spot_sizes
        for focus in focus_options:
            focus_label = focus['label']
            output_path = self.config.general_config.output_folder
            output_path = f'{output_path}/opt/{focus_label}'
            saved_path = f'{output_path}/merged.json'
            with open(saved_path, 'r') as f:
                results = json.load(f)
                dict_results_list.append(results)

        merged_results = []
        for kv in self.config.spectrum_data.kv_vec:
            selected_focus_kv = self.select_focus_kv(dict_results_list, kv)
            merged_results.append(selected_focus_kv)

        df_merged = pd.DataFrame(merged_results)
        output_path = f"{self.config.general_config.output_folder}/opt/parameters_selected.txt"
        df_merged.to_csv(output_path, sep='\t')
        for focus in focus_options:
            focus_label = focus['label']
            output_path = self.config.general_config.output_folder
            zipped_file = f'{output_path}/opt/{focus_label}'
            # zip some of the generated files
            if not Path(f'{zipped_file}.zip').exists():
                shutil.make_archive(zipped_file, 'zip', zipped_file)
                shutil.rmtree(zipped_file)

generate_elements_average()

Generate a list of elements to be averaged in the optimization results.

Returns:

Name Type Description
list list[str]

List of element names for averaging.

Source code in flexpose/optimizer.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def generate_elements_average(self) -> list[str]:
    """
    Generate a list of elements to be averaged in the optimization results.

    Returns:
        list: List of element names for averaging.
    """
    average_list = ['mA', 'ms', 'SNR', 'Gamma', 'SNRW',
                        'Contrast', 'FOM', self.config.dose_data.cost_function, 
                        'PV BG', 'PV OBJ', 'Noise BG', 'Noise OBJ', 'PV BG P', 'DET KERMA (nGy)', 'Entrance kerma (mGy/min)',
                        'Achieved', 'Overshoot']
    other_dosimetry = self.config.dose_data.dosimetry_list
    for dosimetry in other_dosimetry:
        dosimetry_mas = dosimetry.replace('hist', 'mAs')
        average_list.append(dosimetry_mas)
    return average_list

make_optimizers()

Create a list of OptimizeSNR instances for each repetition, with independent RNGs if needed.

Returns:

Name Type Description
list list[OptimizeSNR]

List of OptimizeSNR instances.

Source code in flexpose/optimizer.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def make_optimizers(self) -> list[OptimizeSNR]:
    """
    Create a list of OptimizeSNR instances for each repetition, with independent RNGs if needed.

    Returns:
        list: List of OptimizeSNR instances.
    """
    if self.config.general_config.repetitions == 1:
        optimizers = [OptimizeSNR(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                       dose_cls = self.dose)]
        seed = None
    else:
        rng, seed = auxfuncs.make_rng(self.config.general_config.seed)
        optimizers = []
        rng_children = rng.spawn(self.config.general_config.repetitions)
        optimizer = OptimizeSNR(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                       dose_cls = self.dose)
        for i in range(self.config.general_config.repetitions):
            optimizer_copy = copy.deepcopy(optimizer)
            optimizer_copy.set_rng(rng_children[i])
            optimizer_copy.set_index(i)
            optimizers.append(optimizer_copy)
    self.logger.info(f'Using seed {seed}')
    return optimizers

merge_results_focus(focus)

Merge results for all kV values for a given focal spot and save to file.

Parameters:

Name Type Description Default
focus dict

Focal spot information.

required
Source code in flexpose/optimizer.py
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def merge_results_focus(self, focus: dataformats.FocalSpotSize) -> None:
    """
    Merge results for all kV values for a given focal spot and save to file.

    Args:
        focus (dict): Focal spot information.
    """
    output_path = self.config.general_config.output_folder
    focus_label = focus['label']
    output_path = f'{output_path}/opt/{focus_label}'
    results = glob.glob(f'{output_path}/opt*.json')
    results_list = []

    dict_results = {}

    for fpath in results:
        with open(fpath, 'r') as f:
            json_dict = json.load(f)
        results_list.append(json_dict)

    for kv in self.config.spectrum_data.kv_vec:
        merged_kv = self.merge_results_kv(results=results_list, kv=kv)
        dict_results[str(kv)] = merged_kv

    save_path = f'{output_path}/merged.json'
    with open(save_path, 'w') as f:
        json.dump(dict_results, f, indent=3)

merge_results_kv(results, kv)

Merge results for a specific kV value across repetitions, averaging relevant metrics.

Parameters:

Name Type Description Default
results list

List of result dictionaries.

required
kv int

Tube potential (kV).

required

Returns:

Name Type Description
dict dict

Merged results for the given kV.

Source code in flexpose/optimizer.py
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def merge_results_kv(self, results: list[dict], kv: int) -> dict:
    """
    Merge results for a specific kV value across repetitions, averaging relevant metrics.

    Args:
        results (list): List of result dictionaries.
        kv (int): Tube potential (kV).

    Returns:
        dict: Merged results for the given kV.
    """
    results_list = []
    achieved_list = [] 
    achieved = 0
    failed = True
    for result in results:
        result_kv = result[str(kv)]
        results_list.append(result_kv)
        achieved_list.append(result_kv['Achieved'])
        achieved += result_kv['Achieved']
    if achieved > len(achieved_list) // 2:
        failed = False

    results_filtered = []
    if failed:
        for result in results_list:
            if result['Achieved'] == 0:
                results_filtered.append(result)
    else:
        for result in results_list:
            if result['Achieved'] == 1:
                results_filtered.append(result)

    merged_results = {}
    for key in list(results_filtered[0].keys()):
        if key not in self.elements_average:
            merged_results[key] = results_filtered[0][key]
        else:
            merged_results[key] = np.mean([value[key] for value in results_list])
            if len(results_list) > 3:
                merged_results[f'{key} Unc.'] = np.std([value[key] for value in results_list], ddof=1)
    if failed:
        merged_results['Achieved'] = 0
        merged_results['Agreement'] = 1 - achieved/len(achieved_list)
    else:
        merged_results['Achieved'] = 1
        merged_results['Agreement'] = achieved/len(achieved_list)

    return merged_results

run()

Run the full optimization workflow, including merging results and selecting optimal focus.

Source code in flexpose/optimizer.py
455
456
457
458
459
460
461
462
463
464
def run(self) -> None:
    """
    Run the full optimization workflow, including merging results and selecting optimal focus.
    """
    self.run_optimizers_mp()
    focus_options = self.config.xray_tube_data.focal_spot_sizes
    for focus in focus_options:
        self.merge_results_focus(focus)

    self.select_focus()

run_optimizer_wrapper(idx)

Run the optimizer for a specific repetition index.

Parameters:

Name Type Description Default
idx int

Index of the optimizer to run.

required
Source code in flexpose/optimizer.py
434
435
436
437
438
439
440
441
442
def run_optimizer_wrapper(self, idx: int) -> None:
    """
    Run the optimizer for a specific repetition index.

    Args:
        idx (int): Index of the optimizer to run.
    """
    optimizer = self.optimizers[idx]
    optimizer.run_optmizer()

run_optimizers_mp()

Run all optimizers in parallel using multiprocessing.

Source code in flexpose/optimizer.py
444
445
446
447
448
449
450
451
452
453
def run_optimizers_mp(self) -> None:
    """
    Run all optimizers in parallel using multiprocessing.
    """
    repetitions = self.config.general_config.repetitions
    if  repetitions == 1:
        self.run_optimizer_wrapper(0)
    else:
        with mp.Pool() as pool:
            pool.map(self.run_optimizer_wrapper, list(range(repetitions)))

select_focus()

Select the optimal focus across all kV values and save the selected parameters to a file.

Source code in flexpose/optimizer.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
def select_focus(self) -> None:
    """
    Select the optimal focus across all kV values and save the selected parameters to a file.
    """
    dict_results_list = []
    focus_options = self.config.xray_tube_data.focal_spot_sizes
    for focus in focus_options:
        focus_label = focus['label']
        output_path = self.config.general_config.output_folder
        output_path = f'{output_path}/opt/{focus_label}'
        saved_path = f'{output_path}/merged.json'
        with open(saved_path, 'r') as f:
            results = json.load(f)
            dict_results_list.append(results)

    merged_results = []
    for kv in self.config.spectrum_data.kv_vec:
        selected_focus_kv = self.select_focus_kv(dict_results_list, kv)
        merged_results.append(selected_focus_kv)

    df_merged = pd.DataFrame(merged_results)
    output_path = f"{self.config.general_config.output_folder}/opt/parameters_selected.txt"
    df_merged.to_csv(output_path, sep='\t')
    for focus in focus_options:
        focus_label = focus['label']
        output_path = self.config.general_config.output_folder
        zipped_file = f'{output_path}/opt/{focus_label}'
        # zip some of the generated files
        if not Path(f'{zipped_file}.zip').exists():
            shutil.make_archive(zipped_file, 'zip', zipped_file)
            shutil.rmtree(zipped_file)

select_focus_kv(dict_results_list, kv)

Select the optimal focus for a given kV value based on FOM or SNRW.

Parameters:

Name Type Description Default
dict_results_list list

List of merged result dictionaries for each focus.

required
kv float

Tube potential (kV).

required

Returns:

Name Type Description
dict dict

Selected focus result for the given kV.

Source code in flexpose/optimizer.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
def select_focus_kv(self, dict_results_list: list[dict], kv: int) -> dict:
    """
    Select the optimal focus for a given kV value based on FOM or SNRW.

    Args:
        dict_results_list (list): List of merged result dictionaries for each focus.
        kv (float): Tube potential (kV).

    Returns:
        dict: Selected focus result for the given kV.
    """
    row_list = []
    achieved_list = []
    for dict_res in dict_results_list:
        row = dict_res[str(kv)]
        row_list.append(row)
        if row['Achieved'] == 1:
            achieved_list.append(row)

    # Case 1: at least one focus achieved the target IQ
    if len(achieved_list)>0:
        fom = 0
        fom_unc = 0
        idx_selected = None
        for idx, achieved in enumerate(achieved_list):
            if achieved['FOM']>fom:
                z = np.abs(achieved['FOM']-fom)/np.sqrt(achieved['FOM Unc.']**2 + fom_unc**2 + 1E-20)
                achieved['Z'] = z
                idx_selected = int(idx)
                fom = achieved['FOM']
                fom_unc = achieved['FOM Unc.']
        if idx_selected is None:
            raise ValueError("No focus selected for this kV.")
        return achieved_list[idx_selected]

    # Case 2: no focus achieved the target IQ, select the one with highest IQ
    snru = 0
    snru_unc = 0
    idx_selected = None
    for idx, achieved in enumerate(row_list):
        if achieved['SNRW']>snru:
            z = np.abs(achieved['SNRW']-snru)/np.sqrt(achieved['SNRW Unc.']**2 + snru_unc**2 + 1E-20)
            achieved['Z'] = z
            idx_selected = idx
            snru = achieved['SNRW']
            snru_unc = achieved['SNRW Unc.']
    if idx_selected is None:
        raise ValueError("No focus selected for this kV.")
    return row_list[idx_selected]

Calculator

flexpose.calculator

Calculator

Performs image quality and dose calculations for a single configuration, and saves results.

Source code in flexpose/calculator.py
 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
class Calculator:
    """
    Performs image quality and dose calculations for a single configuration, and saves results.
    """
    def __init__(self, config: dataformats.ConfigDataCalculator, measure_cls : measure.Measure, 
                observer_cls : BaseObserver, dose_cls : dose.CalcDose) -> None:
        """
        Initialize Calculator with configuration and calculation classes.

        Args:
            config (ConfigDataCalculator): Calculator configuration data.
            measure_cls (Measure): Image quality measurement class.
            observer_cls (BaseObserver): Observer model class.
            dose_cls (CalcDose): Dose calculation class.
        """
        self.config : dataformats.ConfigDataCalculator =  config
        self.measurer : measure.Measure = measure_cls
        self.rng : np.random.Generator | None =  None
        #self.observer : observer.Observer = observer_cls
        self.observer: BaseObserver = observer_cls
        self.dose : dose.CalcDose = dose_cls
        self.index : int | None = None

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

        Args:
            rng (np.random.Generator): Random number generator.
        """
        self.rng = rng
        self.measurer.set_rng(self.rng)
        self.measurer.sample_pixels()

    def set_index(self, index: int) -> None:
        """
        Set the index for this calculator instance.

        Args:
            index (int): Index value.
        """
        self.index = index


    def calc_dose_val(self, kv: int, cost: str, t: float, ma: float) -> float:
        """
        Calculate the dose value for given parameters.

        Args:
            kv (int): Tube potential.
            cost (str): Cost function name.
            t (float): Exposure time (s).
            ma (float): Tube current (mA).

        Returns:
            float: Calculated dose value.
        """
        df = self.dose.export_df
        dose_val = df.loc[df['Potential (kV)'] == kv][cost].values[0]
        if self.rng is not None:
            unc_dose_val = df.loc[df['Potential (kV)'] == kv][f'{cost} Unc.'].values[0]
            dose_val = self.rng.normal(dose_val, unc_dose_val)
        dose_val = dose_val*t*ma
        return dose_val


    def calc_values(self, kv: int, focus: dataformats.FocalSpotSize, ma: float, t: float) -> dict[str, Any]:
        """
        Calculate image quality, dose, and figure of merit for given parameters.

        Args:
            kv (int): Tube potential.
            focus (dict): Focal spot size dictionary.
            ma (float): Tube current (mA).
            t (float): Exposure time (s).

        Returns:
            dict: Dictionary of calculated quantities.
        """
        cost = self.config.dose_data.cost_function
        res = self.measurer.calc_img_quality(kv, t, ma)
        focus_size_xy = (focus['size_x'], focus['size_y'])

        params = AcquisitionParams(
            focus_size_xy=focus_size_xy,
            exposure_time_s=t,
        )

        #gamma = self.observer.calc_observer(focus_size_xy, t)
        gamma = self.observer.compute_gamma(params)
        res['Gamma'] =  gamma
        res['SNRW'] = res['SNR']*gamma

        dose_val = self.calc_dose_val(kv, cost, t, ma)
        fom = res['SNRW']**2/dose_val
        res['FOM'] = fom
        res[cost] = dose_val

        other_dosimetry = self.config.dose_data.dosimetry_list

        for dosimetry in other_dosimetry:
            dosimetry_mas = dosimetry.replace('hist', 'mAs')
            res[dosimetry_mas] = self.calc_dose_val(kv, cost, t, ma)
        return res


    def run_table(self) -> dict[str, Any]:
        """
        Run calculations for all parameter sets in the configuration table

        Returns:
            dict: Results for all parameter sets.
        """
        df = self.config.general_config.parameters
        results = {}
        for index, row in df.iterrows():
            ma = row['mA']
            t = row['t [ms]']
            t /= 1000.0
            kv = row['Potential [kV]']
            focus_label = row['focus']
            focal_spot = None
            for focus in self.config.xray_tube_data.focal_spot_sizes:
                if focus['label'] == focus_label:
                    focal_spot = focus
                    break
            if focal_spot is None:
                        raise ValueError(f"Focal spot with label {focus_label!r} not found")
            res = self.calc_values(kv, focal_spot, ma, t)
            results[str(index)] = res
        return results


    def save_results(self, results: dict[str, Any]) -> None:
        """
        Save calculation results to a JSON file in the output folder

        Args:
            results (dict): Results to save.
        """
        output_path = self.config.general_config.output_folder
        output_path = f'{output_path}/calculator/'
        Path(output_path).mkdir(parents=True, exist_ok=True)
        if self.index is None:
            dictname = f'{output_path}/calculated.json'
        else:
            dictname = f'{output_path}/calculated_{self.index}.json'
        with open(dictname, 'w') as f:
            json.dump(results, f, indent=3)

    def run_save(self) -> None:
        """
        Run calculations and save results for this calculator instance
        """
        results = self.run_table()
        self.save_results(results=results)

calc_dose_val(kv, cost, t, ma)

Calculate the dose value for given parameters.

Parameters:

Name Type Description Default
kv int

Tube potential.

required
cost str

Cost function name.

required
t float

Exposure time (s).

required
ma float

Tube current (mA).

required

Returns:

Name Type Description
float float

Calculated dose value.

Source code in flexpose/calculator.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def calc_dose_val(self, kv: int, cost: str, t: float, ma: float) -> float:
    """
    Calculate the dose value for given parameters.

    Args:
        kv (int): Tube potential.
        cost (str): Cost function name.
        t (float): Exposure time (s).
        ma (float): Tube current (mA).

    Returns:
        float: Calculated dose value.
    """
    df = self.dose.export_df
    dose_val = df.loc[df['Potential (kV)'] == kv][cost].values[0]
    if self.rng is not None:
        unc_dose_val = df.loc[df['Potential (kV)'] == kv][f'{cost} Unc.'].values[0]
        dose_val = self.rng.normal(dose_val, unc_dose_val)
    dose_val = dose_val*t*ma
    return dose_val

calc_values(kv, focus, ma, t)

Calculate image quality, dose, and figure of merit for given parameters.

Parameters:

Name Type Description Default
kv int

Tube potential.

required
focus dict

Focal spot size dictionary.

required
ma float

Tube current (mA).

required
t float

Exposure time (s).

required

Returns:

Name Type Description
dict dict[str, Any]

Dictionary of calculated quantities.

Source code in flexpose/calculator.py
 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
def calc_values(self, kv: int, focus: dataformats.FocalSpotSize, ma: float, t: float) -> dict[str, Any]:
    """
    Calculate image quality, dose, and figure of merit for given parameters.

    Args:
        kv (int): Tube potential.
        focus (dict): Focal spot size dictionary.
        ma (float): Tube current (mA).
        t (float): Exposure time (s).

    Returns:
        dict: Dictionary of calculated quantities.
    """
    cost = self.config.dose_data.cost_function
    res = self.measurer.calc_img_quality(kv, t, ma)
    focus_size_xy = (focus['size_x'], focus['size_y'])

    params = AcquisitionParams(
        focus_size_xy=focus_size_xy,
        exposure_time_s=t,
    )

    #gamma = self.observer.calc_observer(focus_size_xy, t)
    gamma = self.observer.compute_gamma(params)
    res['Gamma'] =  gamma
    res['SNRW'] = res['SNR']*gamma

    dose_val = self.calc_dose_val(kv, cost, t, ma)
    fom = res['SNRW']**2/dose_val
    res['FOM'] = fom
    res[cost] = dose_val

    other_dosimetry = self.config.dose_data.dosimetry_list

    for dosimetry in other_dosimetry:
        dosimetry_mas = dosimetry.replace('hist', 'mAs')
        res[dosimetry_mas] = self.calc_dose_val(kv, cost, t, ma)
    return res

run_save()

Run calculations and save results for this calculator instance

Source code in flexpose/calculator.py
166
167
168
169
170
171
def run_save(self) -> None:
    """
    Run calculations and save results for this calculator instance
    """
    results = self.run_table()
    self.save_results(results=results)

run_table()

Run calculations for all parameter sets in the configuration table

Returns:

Name Type Description
dict dict[str, Any]

Results for all parameter sets.

Source code in flexpose/calculator.py
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
def run_table(self) -> dict[str, Any]:
    """
    Run calculations for all parameter sets in the configuration table

    Returns:
        dict: Results for all parameter sets.
    """
    df = self.config.general_config.parameters
    results = {}
    for index, row in df.iterrows():
        ma = row['mA']
        t = row['t [ms]']
        t /= 1000.0
        kv = row['Potential [kV]']
        focus_label = row['focus']
        focal_spot = None
        for focus in self.config.xray_tube_data.focal_spot_sizes:
            if focus['label'] == focus_label:
                focal_spot = focus
                break
        if focal_spot is None:
                    raise ValueError(f"Focal spot with label {focus_label!r} not found")
        res = self.calc_values(kv, focal_spot, ma, t)
        results[str(index)] = res
    return results

save_results(results)

Save calculation results to a JSON file in the output folder

Parameters:

Name Type Description Default
results dict

Results to save.

required
Source code in flexpose/calculator.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def save_results(self, results: dict[str, Any]) -> None:
    """
    Save calculation results to a JSON file in the output folder

    Args:
        results (dict): Results to save.
    """
    output_path = self.config.general_config.output_folder
    output_path = f'{output_path}/calculator/'
    Path(output_path).mkdir(parents=True, exist_ok=True)
    if self.index is None:
        dictname = f'{output_path}/calculated.json'
    else:
        dictname = f'{output_path}/calculated_{self.index}.json'
    with open(dictname, 'w') as f:
        json.dump(results, f, indent=3)

set_index(index)

Set the index for this calculator instance.

Parameters:

Name Type Description Default
index int

Index value.

required
Source code in flexpose/calculator.py
50
51
52
53
54
55
56
57
def set_index(self, index: int) -> None:
    """
    Set the index for this calculator instance.

    Args:
        index (int): Index value.
    """
    self.index = index

set_rng(rng)

Set the random number generator for reproducibility.

Parameters:

Name Type Description Default
rng Generator

Random number generator.

required
Source code in flexpose/calculator.py
39
40
41
42
43
44
45
46
47
48
def set_rng(self, rng: np.random.Generator) -> None:
    """
    Set the random number generator for reproducibility.

    Args:
        rng (np.random.Generator): Random number generator.
    """
    self.rng = rng
    self.measurer.set_rng(self.rng)
    self.measurer.sample_pixels()

CalculatorMP

Manages multiple Calculator instances for parallel execution and merges results

Source code in flexpose/calculator.py
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
class CalculatorMP:
    """
    Manages multiple Calculator instances for parallel execution and merges results
    """
    def __init__(self, config: dataformats.ConfigDataCalculator, measure_cls : measure.Measure, 
                 observer_cls : BaseObserver, dose_cls : dose.CalcDose) -> None:
        """
        Initialize CalculatorMP with configuration and calculation classes

        Args:
            config (ConfigData): Configuration data
            measure_cls (Measure): Image quality measurement class
            observer_cls (Observer): Observer model class
            dose_cls (CalcDose): Dose calculation class
        """
        self.logger = auxfuncs.Logger(logdir=str(config.general_config.output_folder), logname='calculator')
        self.config : dataformats.ConfigDataCalculator =  config
        self.measurer : measure.Measure = measure_cls
        self.observer: BaseObserver = observer_cls
        self.dose : dose.CalcDose = dose_cls
        self.calculators : list[Calculator] = self.make_calculators()
        self.elements_average = self.generate_elements_average()

    def generate_elements_average(self) -> list[str]:
        """
        Generate list of elements to average when merging results

        Returns:
            list: List of element names to average
        """
        average_list = ['mA', 'ms', 'SNR', 'Gamma', 'SNRW',
                            'Contrast', 'FOM', self.config.dose_data.cost_function, 
                            'PV BG', 'PV OBJ', 'Noise BG', 'Noise OBJ', 'PV BG P', 'DET KERMA (nGy)', 'Entrance kerma (mGy/min)']
        other_dosimetry = self.config.dose_data.dosimetry_list
        for dosimetry in other_dosimetry:
            dosimetry_mas = dosimetry.replace('hist', 'mAs')
            average_list.append(dosimetry_mas)
        return average_list


    def make_calculators(self) -> list[Calculator]:
        """
        Create Calculator instances for each repetition, with independent RNGs if needed

        Returns:
            list: List of Calculator instances
        """
        if self.config.general_config.repetitions == 1:
            calculators = [Calculator(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                           dose_cls = self.dose)]
            seed = None
        else:
            rng, seed = auxfuncs.make_rng(self.config.general_config.seed)
            calculators = []
            rng_children = rng.spawn(self.config.general_config.repetitions)
            calculator = Calculator(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                           dose_cls = self.dose)
            for i in range(self.config.general_config.repetitions):
                calculator_copy = copy.deepcopy(calculator)
                calculator_copy.set_rng(rng_children[i])
                calculator_copy.set_index(i)
                calculators.append(calculator_copy)
        self.logger.info(f'Using seed {seed}')
        return calculators

    def run_calculator_wrapper(self, idx: int) -> None:
        """
        Run and save results for a single Calculator instance by index

        Args:
            idx (int): Index of Calculator instance
        """
        calculator = self.calculators[idx]
        calculator.run_save()

    def run_calculators_mp(self) -> None:
        """
        Run all Calculator instances in parallel using multiprocessing
        """
        repetitions = self.config.general_config.repetitions
        if  repetitions == 1:
            self.run_calculator_wrapper(0)
        else:
            with mp.Pool() as pool:
                pool.map(self.run_calculator_wrapper, list(range(repetitions)))

    def merge_results_index(self, results: list[dict[str, Any]], index: int) -> dict[str, Any]:
        """
        Merge results for a single index across all repetitions

        Args:
            results (list): List of result dictionaries
            index (int): Index to merge.

        Returns:
            dict: Merged results for the index
        """
        results_list = []
        for result in results:
            results_list.append(result[str(index)])
        merged_results = {}
        for key in list(results_list[0].keys()):
            if key not in self.elements_average:
                merged_results[key] = results_list[0][key]
            else:
                merged_results[key] = np.mean([value[key] for value in results_list])
                if len(results_list) > 3:
                    merged_results[f'{key} Unc.'] = np.std([value[key] for value in results_list], ddof=1)
        return merged_results


    def merge_results(self) -> None:
        """
        Merge results from all Calculator instances and save merged outputs
        """
        output_path = self.config.general_config.output_folder
        output_path = f'{output_path}/calculator/'
        results = glob.glob(f'{output_path}/calculated*.json')
        results_list = []

        dict_results = {}

        for fpath in results:
            with open(fpath, 'r') as f:
                json_dict = json.load(f)
            results_list.append(json_dict)

        df = self.config.general_config.parameters
        for index, _ in df.itertuples():
            merged_index = self.merge_results_index(results=results_list, index=index)
            dict_results[str(index)] = merged_index

        save_path = f'{output_path}/merged.json'
        with open(save_path, 'w') as f:
            json.dump(dict_results, f, indent=3)

        df_merged = pd.DataFrame.from_dict(dict_results, orient='index')
        output_path = f'{output_path}/merged.txt'
        df_merged.to_csv(output_path, sep='\t', index=False)

    def run(self) -> None:
        """
        Run all calculations in parallel and merge results
        """
        self.run_calculators_mp()
        self.merge_results()

generate_elements_average()

Generate list of elements to average when merging results

Returns:

Name Type Description
list list[str]

List of element names to average

Source code in flexpose/calculator.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def generate_elements_average(self) -> list[str]:
    """
    Generate list of elements to average when merging results

    Returns:
        list: List of element names to average
    """
    average_list = ['mA', 'ms', 'SNR', 'Gamma', 'SNRW',
                        'Contrast', 'FOM', self.config.dose_data.cost_function, 
                        'PV BG', 'PV OBJ', 'Noise BG', 'Noise OBJ', 'PV BG P', 'DET KERMA (nGy)', 'Entrance kerma (mGy/min)']
    other_dosimetry = self.config.dose_data.dosimetry_list
    for dosimetry in other_dosimetry:
        dosimetry_mas = dosimetry.replace('hist', 'mAs')
        average_list.append(dosimetry_mas)
    return average_list

make_calculators()

Create Calculator instances for each repetition, with independent RNGs if needed

Returns:

Name Type Description
list list[Calculator]

List of Calculator instances

Source code in flexpose/calculator.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def make_calculators(self) -> list[Calculator]:
    """
    Create Calculator instances for each repetition, with independent RNGs if needed

    Returns:
        list: List of Calculator instances
    """
    if self.config.general_config.repetitions == 1:
        calculators = [Calculator(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                       dose_cls = self.dose)]
        seed = None
    else:
        rng, seed = auxfuncs.make_rng(self.config.general_config.seed)
        calculators = []
        rng_children = rng.spawn(self.config.general_config.repetitions)
        calculator = Calculator(self.config, measure_cls = self.measurer, observer_cls = self.observer, 
                                       dose_cls = self.dose)
        for i in range(self.config.general_config.repetitions):
            calculator_copy = copy.deepcopy(calculator)
            calculator_copy.set_rng(rng_children[i])
            calculator_copy.set_index(i)
            calculators.append(calculator_copy)
    self.logger.info(f'Using seed {seed}')
    return calculators

merge_results()

Merge results from all Calculator instances and save merged outputs

Source code in flexpose/calculator.py
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
def merge_results(self) -> None:
    """
    Merge results from all Calculator instances and save merged outputs
    """
    output_path = self.config.general_config.output_folder
    output_path = f'{output_path}/calculator/'
    results = glob.glob(f'{output_path}/calculated*.json')
    results_list = []

    dict_results = {}

    for fpath in results:
        with open(fpath, 'r') as f:
            json_dict = json.load(f)
        results_list.append(json_dict)

    df = self.config.general_config.parameters
    for index, _ in df.itertuples():
        merged_index = self.merge_results_index(results=results_list, index=index)
        dict_results[str(index)] = merged_index

    save_path = f'{output_path}/merged.json'
    with open(save_path, 'w') as f:
        json.dump(dict_results, f, indent=3)

    df_merged = pd.DataFrame.from_dict(dict_results, orient='index')
    output_path = f'{output_path}/merged.txt'
    df_merged.to_csv(output_path, sep='\t', index=False)

merge_results_index(results, index)

Merge results for a single index across all repetitions

Parameters:

Name Type Description Default
results list

List of result dictionaries

required
index int

Index to merge.

required

Returns:

Name Type Description
dict dict[str, Any]

Merged results for the index

Source code in flexpose/calculator.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 merge_results_index(self, results: list[dict[str, Any]], index: int) -> dict[str, Any]:
    """
    Merge results for a single index across all repetitions

    Args:
        results (list): List of result dictionaries
        index (int): Index to merge.

    Returns:
        dict: Merged results for the index
    """
    results_list = []
    for result in results:
        results_list.append(result[str(index)])
    merged_results = {}
    for key in list(results_list[0].keys()):
        if key not in self.elements_average:
            merged_results[key] = results_list[0][key]
        else:
            merged_results[key] = np.mean([value[key] for value in results_list])
            if len(results_list) > 3:
                merged_results[f'{key} Unc.'] = np.std([value[key] for value in results_list], ddof=1)
    return merged_results

run()

Run all calculations in parallel and merge results

Source code in flexpose/calculator.py
315
316
317
318
319
320
def run(self) -> None:
    """
    Run all calculations in parallel and merge results
    """
    self.run_calculators_mp()
    self.merge_results()

run_calculator_wrapper(idx)

Run and save results for a single Calculator instance by index

Parameters:

Name Type Description Default
idx int

Index of Calculator instance

required
Source code in flexpose/calculator.py
240
241
242
243
244
245
246
247
248
def run_calculator_wrapper(self, idx: int) -> None:
    """
    Run and save results for a single Calculator instance by index

    Args:
        idx (int): Index of Calculator instance
    """
    calculator = self.calculators[idx]
    calculator.run_save()

run_calculators_mp()

Run all Calculator instances in parallel using multiprocessing

Source code in flexpose/calculator.py
250
251
252
253
254
255
256
257
258
259
def run_calculators_mp(self) -> None:
    """
    Run all Calculator instances in parallel using multiprocessing
    """
    repetitions = self.config.general_config.repetitions
    if  repetitions == 1:
        self.run_calculator_wrapper(0)
    else:
        with mp.Pool() as pool:
            pool.map(self.run_calculator_wrapper, list(range(repetitions)))

CLI Entry Points

flexpose.main