Skip to content

Data Structures & Formats

This module contains all the strictly typed dataclasses used to configure the Flexpose engine. It handles reading and organizing JSON/YAML data into objects.

flexpose.dataformats

ConfigCalculator dataclass

Stores calculator-specific configuration parameters.

Attributes:

Name Type Description
output_folder Path

Output folder path.

task_weight_path Path

Path to task weight file.

snr_mode Literal

SNR calculation mode.

observer Literal

Observer type.

frame_rate float

Frame rate.

parameters_path str

Path to parameters file.

repetitions int

Number of repetitions.

seed int

Random seed.

parameters DataFrame

Parameters data (initialized post-init).

Source code in flexpose/dataformats.py
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
@dataclass
class ConfigCalculator:
    """
    Stores calculator-specific configuration parameters.

    Attributes:
        output_folder (Path): Output folder path.
        task_weight_path (Path): Path to task weight file.
        snr_mode (Literal): SNR calculation mode.
        observer (Literal): Observer type.
        frame_rate (float): Frame rate.
        parameters_path (str): Path to parameters file.
        repetitions (int): Number of repetitions.
        seed (int): Random seed.
        parameters (pd.DataFrame): Parameters data (initialized post-init).
    """
    output_folder : Path
    task_weight_path : Path
    cutoff_energy : float
    snr_mode : Literal['mean', 'median', 'window', 'center']
    observer : Literal['NPWE', 'Ideal', 'MTF', 'None']
    frame_rate : float
    parameters_path : str
    repetitions : int
    seed : int = field(default=0)
    parameters : pd.DataFrame = field(init=False)
    def __post_init__(self):
        """
        Loads parameters data from file.
        """
        self.parameters = pd.read_csv(self.parameters_path, sep='\t')

ConfigData dataclass

Stores all configuration data for optimization and simulation.

Attributes:

Name Type Description
spectrum_data SpectrumData

Spectrum data.

object_data ContrastObject

Contrast object data.

iq_data ImageQualityData

Image quality data.

dose_data DoseData

Dose data.

wet_data WetData

WET data.

detector_data DetectorData

Detector data.

xray_tube_data XrayTubeData

X-ray tube data.

general_config ConfigGeneral

General configuration.

Source code in flexpose/dataformats.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
@dataclass
class ConfigData:
    """
    Stores all configuration data for optimization and simulation.

    Attributes:
        spectrum_data (SpectrumData): Spectrum data.
        object_data (ContrastObject): Contrast object data.
        iq_data (ImageQualityData): Image quality data.
        dose_data (DoseData): Dose data.
        wet_data (WetData): WET data.
        detector_data (DetectorData): Detector data.
        xray_tube_data (XrayTubeData): X-ray tube data.
        general_config (ConfigGeneral): General configuration.
    """
    spectrum_data : SpectrumData
    object_data: ContrastObject
    iq_data: ImageQualityData
    dose_data : DoseData
    wet_data : WetData
    detector_data : DetectorData
    xray_tube_data : XrayTubeData
    general_config : ConfigGeneral | ConfigCalculator

ConfigDataCalculator dataclass

Stores all configuration data for calculator-based optimization and simulation.

Attributes:

Name Type Description
spectrum_data SpectrumData

Spectrum data.

object_data ContrastObject

Contrast object data.

iq_data ImageQualityData

Image quality data.

dose_data DoseData

Dose data.

wet_data WetData

WET data.

detector_data DetectorData

Detector data.

xray_tube_data XrayTubeData

X-ray tube data.

general_config ConfigCalculator

Calculator configuration.

Source code in flexpose/dataformats.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
@dataclass
class ConfigDataCalculator:
    """
    Stores all configuration data for calculator-based optimization and simulation.

    Attributes:
        spectrum_data (SpectrumData): Spectrum data.
        object_data (ContrastObject): Contrast object data.
        iq_data (ImageQualityData): Image quality data.
        dose_data (DoseData): Dose data.
        wet_data (WetData): WET data.
        detector_data (DetectorData): Detector data.
        xray_tube_data (XrayTubeData): X-ray tube data.
        general_config (ConfigCalculator): Calculator configuration.
    """
    spectrum_data : SpectrumData
    object_data: ContrastObject
    iq_data: ImageQualityData
    dose_data : DoseData
    wet_data : WetData
    detector_data : DetectorData
    xray_tube_data : XrayTubeData
    general_config : ConfigCalculator

ConfigGeneral dataclass

Stores general configuration parameters for optimization.

Attributes:

Name Type Description
output_folder Path

Output folder path.

task_weight_path Path

Path to task weight file.

minimum_snr float

Minimum SNR value.

snr_mode Literal

SNR calculation mode.

observer Literal

Observer type.

frame_rate float

Frame rate.

maximum_kerma_rate float

Maximum kerma rate.

repetitions int

Number of repetitions.

seed int

Random seed.

Source code in flexpose/dataformats.py
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
@dataclass
class ConfigGeneral:
    """
    Stores general configuration parameters for optimization.

    Attributes:
        output_folder (Path): Output folder path.
        task_weight_path (Path): Path to task weight file.
        minimum_snr (float): Minimum SNR value.
        snr_mode (Literal): SNR calculation mode.
        observer (Literal): Observer type.
        frame_rate (float): Frame rate.
        maximum_kerma_rate (float): Maximum kerma rate.
        repetitions (int): Number of repetitions.
        seed (int): Random seed.
    """
    output_folder : Path
    task_weight_path : Path | str
    cutoff_energy : float
    minimum_snr : float
    snr_mode : Literal['mean', 'median', 'window', 'center']
    observer : Literal['NPWE', 'Ideal', 'SNRU', 'None']
    frame_rate : float
    maximum_kerma_rate : float  = field(default=88.0)
    repetitions : int = field(default=1)
    seed : int = field(default=0)

    def __post_init__(self):
        """
        Ensures repetitions is at least 1 and odd.
        """
        if self.repetitions < 1:
            self.repetitions = 1
        elif self.repetitions % 2 == 0:
            self.repetitions += 1

ContrastObject dataclass

Stores information about the contrast object being imaged.

Attributes:

Name Type Description
object_name str

Name of the object.

attenuation_path Path

Path to attenuation data.

density float

Object density.

thickness float

Object thickness.

size_xy tuple[float, float]

Object size in x and y.

velocity_xy tuple[tuple[float]]

Object velocity in x and y.

sod float

Source-to-object distance.

shape Literal

Object shape ('cylinder', 'disk', 'rectangular').

Source code in flexpose/dataformats.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@dataclass
class ContrastObject:
    """
    Stores information about the contrast object being imaged.

    Attributes:
        object_name (str): Name of the object.
        attenuation_path (Path): Path to attenuation data.
        density (float): Object density.
        thickness (float): Object thickness.
        size_xy (tuple[float, float]): Object size in x and y.
        velocity_xy (tuple[tuple[float]]): Object velocity in x and y.
        sod (float): Source-to-object distance.
        shape (Literal): Object shape ('cylinder', 'disk', 'rectangular').
    """
    object_name : str
    attenuation_path : Path
    density : float
    thickness : float
    size_xy : tuple[float, float]
    velocity_xy : tuple[float, float]
    sod : float
    shape : Literal['cylinder', 'disk', 'rectangular']

DetectorData dataclass

Stores information about the detector and its properties.

Attributes:

Name Type Description
og_pixel_size tuple[float, float]

Original pixel size.

pixel_size tuple[float, float]

Current pixel size.

light_yield float

Optical photons per keV.

sid float

Source-to-image distance.

iopd float

Image object plane distance.

e_noise float

Electronic noise.

dqe_path Path

Path to DQE data.

mtf_path Path

Path to MTF data.

dqe DataFrame

DQE data (initialized post-init).

mtf DataFrame

MTF data (initialized post-init).

Source code in flexpose/dataformats.py
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
@dataclass
class DetectorData:
    """
    Stores information about the detector and its properties.

    Attributes:
        og_pixel_size (tuple[float, float]): Original pixel size.
        pixel_size (tuple[float, float]): Current pixel size.
        light_yield (float): Optical photons per keV.
        sid (float): Source-to-image distance.
        iopd (float): Image object plane distance.
        e_noise (float): Electronic noise.
        dqe_path (Path): Path to DQE data.
        mtf_path (Path): Path to MTF data.
        dqe (pd.DataFrame): DQE data (initialized post-init).
        mtf (pd.DataFrame): MTF data (initialized post-init).
    """
    og_pixel_size : tuple[float, float]
    pixel_size : tuple[float, float]
    light_yield : float # optical photons per keV
    sid : float
    iopd : float
    e_noise : float
    dqe_path : Path
    mtf_path : Path
    dqe : pd.DataFrame = field(init=False)
    mtf : pd.DataFrame = field(init=False)


    def __post_init__(self):
        """
        Reads detector DQE and MTF data from files.
        """
        self.dqe = pd.read_csv(self.dqe_path, sep ='\t')
        self.mtf = pd.read_csv(self.mtf_path, sep ='\t')

DoseData dataclass

Stores information about dose calculations.

Attributes:

Name Type Description
dose_path Path

Path to dose data.

dosimetry_list list[str]

List of dosimetry metrics.

cost_function str

Cost function used for optimization.

Source code in flexpose/dataformats.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@dataclass
class DoseData:
    """
    Stores information about dose calculations.

    Attributes:
        dose_path (Path): Path to dose data.
        dosimetry_list (list[str]): List of dosimetry metrics.
        cost_function (str): Cost function used for optimization.
    """
    dose_path : Path
    dosimetry_list : list[str] #= field(init=False)
    cost_function : str 

FocalSpotSize

Bases: TypedDict

Dictionary to store information about the focal spot size.

Keys

label (str): Focal spot label. size_x (float): Size in x direction. size_y (float): Size in y direction. max_ma (float): Maximum mA. min_ma (float): Minimum mA.

Source code in flexpose/dataformats.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class FocalSpotSize(TypedDict):
    """
    Dictionary to store information about the focal spot size.

    Keys:
        label (str): Focal spot label.
        size_x (float): Size in x direction.
        size_y (float): Size in y direction.
        max_ma (float): Maximum mA.
        min_ma (float): Minimum mA.
    """
    label : str
    size_x : float
    size_y : float
    max_ma : float
    min_ma : float

ImageQualityData dataclass

Stores information about image quality data.

Attributes:

Name Type Description
primary_path Path

Path to primary image data.

scatter_path Path

Path to scatter image data.

img_shape tuple[tuple[int]]

Shape of the image array.

Source code in flexpose/dataformats.py
74
75
76
77
78
79
80
81
82
83
84
85
86
@dataclass
class ImageQualityData:
    """
    Stores information about image quality data.

    Attributes:
        primary_path (Path): Path to primary image data.
        scatter_path (Path): Path to scatter image data.
        img_shape (tuple[tuple[int]]): Shape of the image array.
    """
    primary_path: Path
    scatter_path: Path
    img_shape: tuple[int, int]

SpectralGrid dataclass

A single quantity tabulated over energy with optional per-pixel variance.

energies: (E,) float (keV) value: (E, H, W) float variance: (E, H, W) float or None units: optional string

Source code in flexpose/dataformats.py
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
@dataclass
class SpectralGrid:
    """
    A single quantity tabulated over energy with optional per-pixel variance.

    energies: (E,)      float (keV)
    value:    (E, H, W) float
    variance: (E, H, W) float or None
    units:    optional string
    """
    energies: np.ndarray
    value: np.ndarray
    variance: Optional[np.ndarray] = None
    units: Optional[str] = None

    def __post_init__(self):
        self.energies = np.asarray(self.energies, dtype=float).reshape(-1)
        if self.energies.ndim != 1 or self.energies.size == 0:
            raise ValueError("energies must be a non-empty 1D array")
        if self.value.shape[0] != self.energies.shape[0]:
            raise ValueError("value.shape[0] must match energies length")
        if self.variance is not None and self.variance.shape[0] != self.energies.shape[0]:
            raise ValueError("variance.shape[0] must match energies length")

        # Ensure sorted by energy (and reorder arrays accordingly)
        if not np.all(np.diff(self.energies) >= 0):
            order = np.argsort(self.energies)
            self.energies = self.energies[order]
            self.value = self.value[order, ...]
            if self.variance is not None:
                self.variance = self.variance[order, ...]

    def _bracket(self, e: float):
        idx = np.searchsorted(self.energies, e)
        if idx == 0:
            return 0, 0, 1.0, 0.0
        if idx >= len(self.energies):
            i = len(self.energies) - 1
            return i, i, 0.0, 1.0
        iL, iR = idx - 1, idx
        eL, eR = self.energies[iL], self.energies[iR]
        if eR == eL:
            return iL, iR, 1.0, 0.0
        wR = float((e - eL) / (eR - eL))
        wL = 1.0 - wR
        return iL, iR, wL, wR

    def interp(self, e: float):
        """
        Interpolate at scalar energy e.
        Returns (value_e, variance_e or None), shape (H, W)
        """
        iL, iR, wL, wR = self._bracket(float(e))
        val_e = wL * self.value[iL] + wR * self.value[iR]
        if self.variance is None:
            var_e = None
        else:
            var_e = wL * self.variance[iL] + wR * self.variance[iR]
        return val_e, var_e

    def interp_many(self, e_vec: np.ndarray):
        """
        Vectorized interpolation
        returns stacks on axis 0: (vals, vars or None), shape (E_bins, H, W)
        """
        e_vec = np.asarray(e_vec, dtype=float)
        H, W = self.value.shape[1], self.value.shape[2]
        out_val = np.empty((len(e_vec), H, W), dtype=self.value.dtype)
        out_var = None if self.variance is None else np.empty_like(out_val)

        for j, e in enumerate(e_vec):
            v, var = self.interp(e)
            out_val[j] = v
            if out_var is not None:
                out_var[j] = var
        return out_val, out_var

interp(e)

Interpolate at scalar energy e. Returns (value_e, variance_e or None), shape (H, W)

Source code in flexpose/dataformats.py
381
382
383
384
385
386
387
388
389
390
391
392
def interp(self, e: float):
    """
    Interpolate at scalar energy e.
    Returns (value_e, variance_e or None), shape (H, W)
    """
    iL, iR, wL, wR = self._bracket(float(e))
    val_e = wL * self.value[iL] + wR * self.value[iR]
    if self.variance is None:
        var_e = None
    else:
        var_e = wL * self.variance[iL] + wR * self.variance[iR]
    return val_e, var_e

interp_many(e_vec)

Vectorized interpolation returns stacks on axis 0: (vals, vars or None), shape (E_bins, H, W)

Source code in flexpose/dataformats.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def interp_many(self, e_vec: np.ndarray):
    """
    Vectorized interpolation
    returns stacks on axis 0: (vals, vars or None), shape (E_bins, H, W)
    """
    e_vec = np.asarray(e_vec, dtype=float)
    H, W = self.value.shape[1], self.value.shape[2]
    out_val = np.empty((len(e_vec), H, W), dtype=self.value.dtype)
    out_var = None if self.variance is None else np.empty_like(out_val)

    for j, e in enumerate(e_vec):
        v, var = self.interp(e)
        out_val[j] = v
        if out_var is not None:
            out_var[j] = var
    return out_val, out_var

SpectralSet dataclass

A collection of SpectralGrids sharing a canonical energy axis. Required: N, E, SM. Optional: kerma.

Source code in flexpose/dataformats.py
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
@dataclass
class SpectralSet:
    """
    A collection of SpectralGrids sharing a canonical energy axis.
    Required: N, E, SM. Optional: kerma.
    """
    energies: np.ndarray
    N: SpectralGrid
    E: SpectralGrid
    SM: SpectralGrid
    kerma: Optional[SpectralGrid] = None
    meta: Optional[dict] = None

    def __post_init__(self):
        self.energies = np.asarray(self.energies, dtype=float).reshape(-1)
        if self.energies.ndim != 1 or self.energies.size == 0:
            raise ValueError("energies must be a non-empty 1D array")
        if not np.all(np.diff(self.energies) >= 0):
            self.energies = np.sort(self.energies)

        def _align_to_canonical(grid: SpectralGrid | None) -> SpectralGrid | None:
            if grid is None:
                return None
            if grid.energies.shape != self.energies.shape or not np.allclose(
                grid.energies, self.energies, rtol=0, atol=1e-12
            ):
                vals, vars_ = grid.interp_many(self.energies)  # clamps at ends
                grid.energies = self.energies
                grid.value = vals
                grid.variance = vars_
            return grid

        self.N = _align_to_canonical(self.N)
        self.E = _align_to_canonical(self.E)
        self.SM = _align_to_canonical(self.SM)
        self.kerma = _align_to_canonical(self.kerma)

    def has_kerma(self) -> bool:
        return self.kerma is not None

    def interp(self, e: float) -> dict[str, tuple[np.ndarray, Optional[np.ndarray]]]:
        out = {
            "N": self.N.interp(e),
            "E": self.E.interp(e),
            "SM": self.SM.interp(e),
        }
        if self.kerma is not None:
            out["kerma"] = self.kerma.interp(e)
        return out

    def interp_many(self, e_vec: np.ndarray) -> dict[str, tuple[np.ndarray, Optional[np.ndarray]]]:
        out = {
            "N": self.N.interp_many(e_vec),
            "E": self.E.interp_many(e_vec),
            "SM": self.SM.interp_many(e_vec),
        }
        if self.kerma is not None:
            out["kerma"] = self.kerma.interp_many(e_vec)
        return out

SpectrumData dataclass

Stores information about the x-ray spectrum used in optimization calculations.

Attributes:

Name Type Description
min_kv int

Minimum tube potential.

max_kv int

Maximum tube potential.

kv_step int

Step size for tube potential.

filt str

Filter type.

spectrum_folder Path

Path to spectrum data folder.

hist_to_mas Path | None

Path to history-to-mAs calibration file.

kv_vec list[int]

List of kV values (initialized post-init).

df_hist_to_mas DataFrame

Calibration data (initialized post-init).

Source code in flexpose/dataformats.py
 7
 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
@dataclass
class SpectrumData:
    """
    Stores information about the x-ray spectrum used in optimization calculations.

    Attributes:
        min_kv (int): Minimum tube potential.
        max_kv (int): Maximum tube potential.
        kv_step (int): Step size for tube potential.
        filt (str): Filter type.
        spectrum_folder (Path): Path to spectrum data folder.
        hist_to_mas (Path | None): Path to history-to-mAs calibration file.
        kv_vec (list[int]): List of kV values (initialized post-init).
        df_hist_to_mas (pd.DataFrame): Calibration data (initialized post-init).
    """
    min_kv : int
    max_kv : int
    kv_step: int
    label: str
    filtration: list[tuple[str, float]]
    anode_material: str
    anode_angle : float
    bin_width : float
    spectrum_folder : Path
    hist_to_mas : Path | None
    kv_vec : list[int] = field(init=False)
    df_hist_to_mas : pd.DataFrame = field(init=False)

    def __post_init__(self):
        """
        Calculates kV array and loads calibration data if available.
        """
        self.kv_vec = np.arange(self.min_kv, self.max_kv + self.kv_step, self.kv_step).tolist()
        if self.hist_to_mas is not None:
            self.df_hist_to_mas = pd.read_csv(self.hist_to_mas, comment='#', sep='\t')

        if not Path(self.spectrum_folder).exists():
            from flexpose import spectra_gen
            gen_spec = spectra_gen.SpectrumGenerator(config=self)
            gen_spec.loop_spectra()

WetData dataclass

Stores information about Water Equivalent Thickness (WET) calculations.

Attributes:

Name Type Description
wet_path Path

Path to WET data.

wet_type Literal

Type of WET ('primary', 'total').

wet_material str

Material for WET calculation.

grid str

Grid type.

thickness list[int]

List of thickness values.

Source code in flexpose/dataformats.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@dataclass
class WetData:
    """
    Stores information about Water Equivalent Thickness (WET) calculations.

    Attributes:
        wet_path (Path): Path to WET data.
        wet_type (Literal): Type of WET ('primary', 'total').
        wet_material (str): Material for WET calculation.
        grid (str): Grid type.
        thickness (list[int]): List of thickness values.
    """
    wet_path : Path
    wet_type: Literal['primary', 'total']
    wet_material: str
    grid : str
    thickness : list[int]

XrayTubeData dataclass

Stores information about the X-ray tube and its calibration.

Attributes:

Name Type Description
tube_specs_path Path | None

Path to tube specifications file.

calibration_path Path

Path to calibration data.

focal_spot_sizes list[FocalSpotSize]

List of focal spot sizes.

fov float

Field of view.

max_exposure_time float

Maximum exposure time.

min_exposure_time float

Minimum exposure time.

tube_specs DataFrame | None

Tube specifications data (initialized post-init).

Source code in flexpose/dataformats.py
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
@dataclass
class XrayTubeData:
    """
    Stores information about the X-ray tube and its calibration.

    Attributes:
        tube_specs_path (Path | None): Path to tube specifications file.
        calibration_path (Path): Path to calibration data.
        focal_spot_sizes (list[FocalSpotSize]): List of focal spot sizes.
        fov (float): Field of view.
        max_exposure_time (float): Maximum exposure time.
        min_exposure_time (float): Minimum exposure time.
        tube_specs (pd.DataFrame | None): Tube specifications data (initialized post-init).
    """
    tube_specs_path : Path | None
    calibration_path : Path
    focal_spot_sizes : list[FocalSpotSize]
    fov : float
    # used in the optimization process
    max_exposure_time : float = 0.0
    min_exposure_time : float = 0.0
    tube_specs : pd.DataFrame| None = field(init=False)

    def __post_init__(self):
        """
        Loads tube specifications from file if available.
        """
        if self.tube_specs_path is not None:
            self.tube_specs = pd.read_csv(self.tube_specs_path, sep ='\t')
        else:
            self.tube_specs = None