Skip to content

Utilities & Helpers

Internal helpers, constants, and the Spekpy wrapper for spectra generation.

Spectra Generation

flexpose.spectra_gen

MissingDependencyError

Bases: ImportError

Raised when an optional dependency is required for a feature

Source code in flexpose/spectra_gen.py
20
21
22
class MissingDependencyError(ImportError):
    """Raised when an optional dependency is required for a feature"""
    pass

SpectrumGenerator

Source code in flexpose/spectra_gen.py
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
class SpectrumGenerator:
    def __init__(self, config: dataformats.SpectrumData) -> None:
        """
        Initialize the SpectrumGenerator class with configuration data

        Args:
            config (dataformats.SpectrumData): Configuration data object
        """
        self.config : dataformats.SpectrumData = config

    def make_spectrum(self, kv: int) -> None:
        """
        Generate the X-ray spectrum for a given kilovoltage (kV)

        Args:
            kv (int): Kilovoltage for which to generate the spectrum
        """
        _require_spekpy()
        # Generate unfiltered spectrum
        anode_angle = self.config.anode_angle
        bin_width = self.config.bin_width
        anode = self.config.anode_material
        s=spekpy.Spek(kvp=kv,th=anode_angle, dk=bin_width, targ=anode)
        # Filter the spectrum
        for filtration in self.config.filtration:
            filter_name, thickness = filtration
            print(filter_name, thickness)
            s.filter(filter_name, thickness)
        folder = self.config.spectrum_folder
        output_path = f'{folder}/{kv}kv.spk'
        s.export_spectrum(output_path)


    def loop_spectra(self) -> None:
        """
        Loop through the specified kV range and generate spectra for each kV
        """
        kv_values = self.config.kv_vec
        folder = self.config.spectrum_folder
        Path(folder).mkdir(parents=True, exist_ok=True)
        with mp.Pool() as pool:
                pool.map(self.make_spectrum, kv_values)

loop_spectra()

Loop through the specified kV range and generate spectra for each kV

Source code in flexpose/spectra_gen.py
67
68
69
70
71
72
73
74
75
def loop_spectra(self) -> None:
    """
    Loop through the specified kV range and generate spectra for each kV
    """
    kv_values = self.config.kv_vec
    folder = self.config.spectrum_folder
    Path(folder).mkdir(parents=True, exist_ok=True)
    with mp.Pool() as pool:
            pool.map(self.make_spectrum, kv_values)

make_spectrum(kv)

Generate the X-ray spectrum for a given kilovoltage (kV)

Parameters:

Name Type Description Default
kv int

Kilovoltage for which to generate the spectrum

required
Source code in flexpose/spectra_gen.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def make_spectrum(self, kv: int) -> None:
    """
    Generate the X-ray spectrum for a given kilovoltage (kV)

    Args:
        kv (int): Kilovoltage for which to generate the spectrum
    """
    _require_spekpy()
    # Generate unfiltered spectrum
    anode_angle = self.config.anode_angle
    bin_width = self.config.bin_width
    anode = self.config.anode_material
    s=spekpy.Spek(kvp=kv,th=anode_angle, dk=bin_width, targ=anode)
    # Filter the spectrum
    for filtration in self.config.filtration:
        filter_name, thickness = filtration
        print(filter_name, thickness)
        s.filter(filter_name, thickness)
    folder = self.config.spectrum_folder
    output_path = f'{folder}/{kv}kv.spk'
    s.export_spectrum(output_path)

Auxiliary Functions

flexpose.auxfuncs

Calibration

Class to perform the calibration of hist to mAs

Source code in flexpose/auxfuncs.py
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
class Calibration:
    """
    Class to perform the calibration of hist to mAs
    """
    def __init__(self, config, seed: int = 42):
        self.config : dataformats.ConfigData  = config
        self.logger = Logger(logdir=str(self.config.general_config.output_folder), logname='calibration')
        self.dose_table : pd.DataFrame = pd.read_csv(self.config.dose_data.dose_path, sep='\t')
        self.rng : np.random.Generator = np.random.default_rng(seed=seed)
        self.repeat : int = 10

    def quantity_and_sample(self, rng : np.random.Generator) -> np.ndarray:
        """
        Function to retrieve the DAP values from the dose tables
        """
        df = self.dose_table
        quantity_name = ['DAP (Gycm2/hist)', 'DAP (Gycm2/hist) Unc.']
        quantity: np.ndarray = df[quantity_name[0]].to_numpy()
        unc: np.ndarray = df[quantity_name[1]].to_numpy()
        if self.repeat <= 2:
            sampled_quantity = quantity
        else:
            sampled_quantity = rng.normal(loc=quantity, scale=unc)
        return sampled_quantity

    def integrate_quantity(self, quantity : np.ndarray, kv: int, cutoff_energy : float) -> float:
        """
        Integrate the DAP over the x-ray spectrum using 1:1 linear interpolation.

        Args:
            quantity (np.ndarray): The DAP values corresponding to the energies in the dose table.
            kv (int): The tube potential (kV) for which to retrieve the x-ray spectrum.
            cutoff_energy (float): The minimum energy (in eV) to consider in the integration.
        Returns:
            float: The integrated DAP value.
        """
        e_bins, probs = get_spec_prob(self.config.spectrum_data, kv, cutoff_energy=cutoff_energy)
        dose_energies = self.dose_table['Energy (keV)'].to_numpy()
        # we interpolate the quantity to the energy bins of the spectrum
        quantity_interp = np.interp(e_bins, dose_energies, quantity)
        integrated = np.sum(probs * quantity_interp) / np.sum(probs)
        return integrated

    def from_dap_to_kerma(self, dap_values) -> np.ndarray:
        """ 
        This function converts DAP to Air kerma
        """
        sid = self.config.detector_data.sid
        fov = self.config.xray_tube_data.fov
        # the reference point is fixed at 100 cm
        ref_point = 100
        new_fov = (ref_point/sid)*fov
        field_area = new_fov**2/2
        kerma = dap_values/field_area
        return kerma

    def read_spekpy_kerma(self, kv : int):
        """
        This function reads the nominal air Kerma from Spekpy
        per mAs at 100 cm
        """
        spec_direc = self.config.spectrum_data.spectrum_folder
        fname = f'{spec_direc}/{kv}kv.spk'
        with open(fname, 'r') as f:
            text = f.read()
            kerma = text.split('Air Kerma:')[1].split('[uGy]')[0]
            kerma = float(kerma)*1E-6 # from microGy to Gy
        return kerma


    def get_measured_kerma(self, kv) -> None | dict:
        """
        This function gets the air kerma from measured values
        """
        df = self.config.spectrum_data.df_hist_to_mas
        kerma = df[df['kV'] == kv]['Air Kerma (uGy/mAs)'].values[0]*1E-6 # from microGy to Gy
        return kerma

    def calc_hist_mas(self, kv: int, rng: np.random.Generator) -> tuple[float, float]:
        """
        Function to calculate the conversion factor of hist to mAs for a given kV
        Args:
            kv (int): Tube potential (kV).
            rng (np.random.Generator): Random number generator.
        Returns:
            tuple: (hist to mAs conversion factor, its uncertainty)
        """

        sid = self.config.detector_data.sid
        quantity_vec = []
        cutoff_energy = self.config.general_config.cutoff_energy
        for _ in range(self.repeat):
            quantity = self.quantity_and_sample(rng)
            quantity = self.integrate_quantity(quantity, kv, cutoff_energy)
            quantity_vec.append(quantity)
        mean = np.mean(quantity_vec)
        std = np.std(quantity_vec, ddof=1)
        mean_kerma = self.from_dap_to_kerma(mean)
        std_kerma = self.from_dap_to_kerma(std)
        if self.config.spectrum_data.hist_to_mas is None:
            reference_kerma = self.read_spekpy_kerma(kv)
        else:
            reference_kerma = self.get_measured_kerma(kv)

        hist_to_mas = reference_kerma/mean_kerma if mean_kerma > 0 else 0
        hist_to_mas_std = (std_kerma/mean_kerma)*hist_to_mas if mean_kerma > 0 else 0

        hist_to_mas = float(hist_to_mas)
        hist_to_mas_std = float(hist_to_mas_std)

        return (hist_to_mas, hist_to_mas_std)

    @measure_time
    def calc_hist_mas_mp(self) -> pd.DataFrame:
        """
        Wrapper to parallelize the reference kerma calculations
        """
        kv_vec = self.config.spectrum_data.kv_vec
        rng_generator = self.rng.spawn(len(kv_vec))
        combined = list(zip(kv_vec, rng_generator))
        with mp.Pool() as pool:
            results = pool.starmap(self.calc_hist_mas, combined)
        hist_to_mas, hist_to_mas_std = list(zip(*results))


        df_results = pd.DataFrame()

        df_results['kV'] = kv_vec
        df_results['Hist/mAs'] = hist_to_mas
        df_results['Hist/mAs Unc.'] = hist_to_mas_std
        return df_results

    def make_calibration(self) -> None:
        """
        Main function to perform the calibrations
        """

        self.logger.info('Generating the calibration maps')
        if self.config.spectrum_data.hist_to_mas is None:
            self.logger.info('Using default Spekpy Kerma/mAs tables')
        else:
            self.logger.info('Using measured Kerma/mAs tables')
        df_calibration = self.calc_hist_mas_mp()
        self.logger.info('Saving files')
        fname = f'{self.config.general_config.output_folder}/calibration.txt'
        df_calibration.to_csv(fname, sep='\t', index=False)

calc_hist_mas(kv, rng)

Function to calculate the conversion factor of hist to mAs for a given kV Args: kv (int): Tube potential (kV). rng (np.random.Generator): Random number generator. Returns: tuple: (hist to mAs conversion factor, its uncertainty)

Source code in flexpose/auxfuncs.py
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
def calc_hist_mas(self, kv: int, rng: np.random.Generator) -> tuple[float, float]:
    """
    Function to calculate the conversion factor of hist to mAs for a given kV
    Args:
        kv (int): Tube potential (kV).
        rng (np.random.Generator): Random number generator.
    Returns:
        tuple: (hist to mAs conversion factor, its uncertainty)
    """

    sid = self.config.detector_data.sid
    quantity_vec = []
    cutoff_energy = self.config.general_config.cutoff_energy
    for _ in range(self.repeat):
        quantity = self.quantity_and_sample(rng)
        quantity = self.integrate_quantity(quantity, kv, cutoff_energy)
        quantity_vec.append(quantity)
    mean = np.mean(quantity_vec)
    std = np.std(quantity_vec, ddof=1)
    mean_kerma = self.from_dap_to_kerma(mean)
    std_kerma = self.from_dap_to_kerma(std)
    if self.config.spectrum_data.hist_to_mas is None:
        reference_kerma = self.read_spekpy_kerma(kv)
    else:
        reference_kerma = self.get_measured_kerma(kv)

    hist_to_mas = reference_kerma/mean_kerma if mean_kerma > 0 else 0
    hist_to_mas_std = (std_kerma/mean_kerma)*hist_to_mas if mean_kerma > 0 else 0

    hist_to_mas = float(hist_to_mas)
    hist_to_mas_std = float(hist_to_mas_std)

    return (hist_to_mas, hist_to_mas_std)

calc_hist_mas_mp()

Wrapper to parallelize the reference kerma calculations

Source code in flexpose/auxfuncs.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
@measure_time
def calc_hist_mas_mp(self) -> pd.DataFrame:
    """
    Wrapper to parallelize the reference kerma calculations
    """
    kv_vec = self.config.spectrum_data.kv_vec
    rng_generator = self.rng.spawn(len(kv_vec))
    combined = list(zip(kv_vec, rng_generator))
    with mp.Pool() as pool:
        results = pool.starmap(self.calc_hist_mas, combined)
    hist_to_mas, hist_to_mas_std = list(zip(*results))


    df_results = pd.DataFrame()

    df_results['kV'] = kv_vec
    df_results['Hist/mAs'] = hist_to_mas
    df_results['Hist/mAs Unc.'] = hist_to_mas_std
    return df_results

from_dap_to_kerma(dap_values)

This function converts DAP to Air kerma

Source code in flexpose/auxfuncs.py
175
176
177
178
179
180
181
182
183
184
185
186
def from_dap_to_kerma(self, dap_values) -> np.ndarray:
    """ 
    This function converts DAP to Air kerma
    """
    sid = self.config.detector_data.sid
    fov = self.config.xray_tube_data.fov
    # the reference point is fixed at 100 cm
    ref_point = 100
    new_fov = (ref_point/sid)*fov
    field_area = new_fov**2/2
    kerma = dap_values/field_area
    return kerma

get_measured_kerma(kv)

This function gets the air kerma from measured values

Source code in flexpose/auxfuncs.py
202
203
204
205
206
207
208
def get_measured_kerma(self, kv) -> None | dict:
    """
    This function gets the air kerma from measured values
    """
    df = self.config.spectrum_data.df_hist_to_mas
    kerma = df[df['kV'] == kv]['Air Kerma (uGy/mAs)'].values[0]*1E-6 # from microGy to Gy
    return kerma

integrate_quantity(quantity, kv, cutoff_energy)

Integrate the DAP over the x-ray spectrum using 1:1 linear interpolation.

Parameters:

Name Type Description Default
quantity ndarray

The DAP values corresponding to the energies in the dose table.

required
kv int

The tube potential (kV) for which to retrieve the x-ray spectrum.

required
cutoff_energy float

The minimum energy (in eV) to consider in the integration.

required

Returns: float: The integrated DAP value.

Source code in flexpose/auxfuncs.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def integrate_quantity(self, quantity : np.ndarray, kv: int, cutoff_energy : float) -> float:
    """
    Integrate the DAP over the x-ray spectrum using 1:1 linear interpolation.

    Args:
        quantity (np.ndarray): The DAP values corresponding to the energies in the dose table.
        kv (int): The tube potential (kV) for which to retrieve the x-ray spectrum.
        cutoff_energy (float): The minimum energy (in eV) to consider in the integration.
    Returns:
        float: The integrated DAP value.
    """
    e_bins, probs = get_spec_prob(self.config.spectrum_data, kv, cutoff_energy=cutoff_energy)
    dose_energies = self.dose_table['Energy (keV)'].to_numpy()
    # we interpolate the quantity to the energy bins of the spectrum
    quantity_interp = np.interp(e_bins, dose_energies, quantity)
    integrated = np.sum(probs * quantity_interp) / np.sum(probs)
    return integrated

make_calibration()

Main function to perform the calibrations

Source code in flexpose/auxfuncs.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def make_calibration(self) -> None:
    """
    Main function to perform the calibrations
    """

    self.logger.info('Generating the calibration maps')
    if self.config.spectrum_data.hist_to_mas is None:
        self.logger.info('Using default Spekpy Kerma/mAs tables')
    else:
        self.logger.info('Using measured Kerma/mAs tables')
    df_calibration = self.calc_hist_mas_mp()
    self.logger.info('Saving files')
    fname = f'{self.config.general_config.output_folder}/calibration.txt'
    df_calibration.to_csv(fname, sep='\t', index=False)

quantity_and_sample(rng)

Function to retrieve the DAP values from the dose tables

Source code in flexpose/auxfuncs.py
143
144
145
146
147
148
149
150
151
152
153
154
155
def quantity_and_sample(self, rng : np.random.Generator) -> np.ndarray:
    """
    Function to retrieve the DAP values from the dose tables
    """
    df = self.dose_table
    quantity_name = ['DAP (Gycm2/hist)', 'DAP (Gycm2/hist) Unc.']
    quantity: np.ndarray = df[quantity_name[0]].to_numpy()
    unc: np.ndarray = df[quantity_name[1]].to_numpy()
    if self.repeat <= 2:
        sampled_quantity = quantity
    else:
        sampled_quantity = rng.normal(loc=quantity, scale=unc)
    return sampled_quantity

read_spekpy_kerma(kv)

This function reads the nominal air Kerma from Spekpy per mAs at 100 cm

Source code in flexpose/auxfuncs.py
188
189
190
191
192
193
194
195
196
197
198
199
def read_spekpy_kerma(self, kv : int):
    """
    This function reads the nominal air Kerma from Spekpy
    per mAs at 100 cm
    """
    spec_direc = self.config.spectrum_data.spectrum_folder
    fname = f'{spec_direc}/{kv}kv.spk'
    with open(fname, 'r') as f:
        text = f.read()
        kerma = text.split('Air Kerma:')[1].split('[uGy]')[0]
        kerma = float(kerma)*1E-6 # from microGy to Gy
    return kerma

Logger

This class handles the logs that can be called for each class

Source code in flexpose/auxfuncs.py
 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
class Logger:
    """
    This class handles the logs that can be called for each class
    """
    def __init__(self, logdir: str, logname: str, timer: bool = False):
        """Initializes the logger attributes

        :param logdir: str:  input directory for log
        :param logname: str: logname for log file
        :param timer: add  current time to log entries
        """
        self.logdir = f'{logdir}/logs/'
        self.logname = logname
        self.logpath = f'{self.logdir}{self.logname}.log'
        self.timer = timer
        self.logger = self.init_log()

    def init_log(self) -> logging.Logger:
        """
        This function initializes the logger
        :return: logger object
        """
        # creates log folder if not exists
        Path(self.logdir).mkdir(parents=True, exist_ok=True)
        handler = logging.FileHandler(filename=self.logpath, mode='w')
        if self.timer:
            formatter = logging.Formatter('%(asctime)s %(message)s')
            handler.setFormatter(formatter)
        logger = logging.getLogger(self.logname)
        logger.setLevel(logging.INFO)
        logger.addHandler(handler)
        return logger

    def close_log(self) -> None:
        """
        This function closes the current log
        :return: nothing
        """
        handlers = self.logger.handlers[:]
        for handler in handlers:
            handler.close()
            self.logger.removeHandler(handler)

    def info(self, text: str) -> None:
        """
        This function writes a string to a log
        :return: nothing
        """
        self.logger.info(text)

close_log()

This function closes the current log :return: nothing

Source code in flexpose/auxfuncs.py
113
114
115
116
117
118
119
120
121
def close_log(self) -> None:
    """
    This function closes the current log
    :return: nothing
    """
    handlers = self.logger.handlers[:]
    for handler in handlers:
        handler.close()
        self.logger.removeHandler(handler)

info(text)

This function writes a string to a log :return: nothing

Source code in flexpose/auxfuncs.py
123
124
125
126
127
128
def info(self, text: str) -> None:
    """
    This function writes a string to a log
    :return: nothing
    """
    self.logger.info(text)

init_log()

This function initializes the logger :return: logger object

Source code in flexpose/auxfuncs.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def init_log(self) -> logging.Logger:
    """
    This function initializes the logger
    :return: logger object
    """
    # creates log folder if not exists
    Path(self.logdir).mkdir(parents=True, exist_ok=True)
    handler = logging.FileHandler(filename=self.logpath, mode='w')
    if self.timer:
        formatter = logging.Formatter('%(asctime)s %(message)s')
        handler.setFormatter(formatter)
    logger = logging.getLogger(self.logname)
    logger.setLevel(logging.INFO)
    logger.addHandler(handler)
    return logger

cut_mtf_zero(freq, mtf)

This function cuts MTF when it reaches 0 to avoid going above the nyquist frequency

Source code in flexpose/auxfuncs.py
68
69
70
71
72
73
74
75
76
77
def cut_mtf_zero(freq : np.ndarray, mtf : np.ndarray) -> np.ndarray:
    """
    This function cuts MTF when it reaches 0 to avoid going above the nyquist frequency
    """
    indices = np.where(mtf<0)
    if indices[0].size > 0:
        freq_cut = indices[0][0]
        mtf[freq>freq[freq_cut]] = 0
        mtf[mtf<0] = 0
    return mtf

get_spec_prob(specdata, kv, cutoff_energy=0.0)

Auxiliary function to read the spectrum file based on kv

Source code in flexpose/auxfuncs.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def get_spec_prob(specdata: dataformats.SpectrumData, kv: int, cutoff_energy : float = 0.0) -> tuple[np.ndarray, np.ndarray]:
    """
    Auxiliary function to read the spectrum file based on kv
    """
    spec_direc = specdata.spectrum_folder
    fname = f'{spec_direc}/{kv}kv.spk'
    if not Path(fname).is_file():
        raise FileNotFoundError(f'Spectrum file {fname} not found')
    df = pd.read_csv(fname, header=None, sep=';', comment='#').values
    df[:,0] *= 1000.0
    prob = df[:,1]
    # here we split the array with the index where it meets the minimum kV
    idx_cut = np.argwhere(df[:,0] >= cutoff_energy)[0][0]
    kev = df[idx_cut:,0]
    prob = df[idx_cut:,1]
    # normalize probabilities to 1
    prob = prob/np.sum(prob)
    return kev, prob

load_json(path)

Auxiliary function to read a json file and return as dictionary

Source code in flexpose/auxfuncs.py
31
32
33
34
35
36
37
38
def load_json(path : str) -> dict:
    """
    Auxiliary function to read a json file and 
    return as dictionary
    """
    with open(path, 'r') as f:
        read_dict = json.load(f)
    return read_dict

make_rng(seed)

Function to return a rng based on an input seed

Source code in flexpose/auxfuncs.py
55
56
57
58
59
60
61
62
63
64
65
def make_rng(seed : int) -> tuple[np.random.Generator, int]:
    """
    Function to return a rng based on an input seed
    """
    # generating the seed
    if seed == 0:
        seed_sequence = np.random.SeedSequence()
        seed = seed_sequence.generate_state(1, dtype=np.uint64)[0]

    rng = np.random.default_rng(seed=seed)
    return rng, seed

measure_time(function)

Decorator to measure execution time

Source code in flexpose/auxfuncs.py
42
43
44
45
46
47
48
49
50
51
52
def measure_time(function):
    """
    Decorator to measure execution time
    """
    def wrapper(self, *args, **kwargs):
        time_start = time.time()
        result = function(self, *args, **kwargs)
        time_finish = np.round((time.time() - time_start) / 60, 2)
        self.logger.info(f'This process took {time_finish} minutes')
        return result
    return wrapper

spectral_set_from_json(path, keymap=None, dtype=np.float64)

Reads a JSON file and constructs a SpectralSet.

Source code in flexpose/auxfuncs.py
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
def spectral_set_from_json(
    path: str,
    keymap: dict[str, str] | None = None,      
    dtype: np.dtype = np.float64,
) -> dataformats.SpectralSet:
    """
    Reads a JSON file and constructs a SpectralSet.
    """
    if keymap is None:
        keymap = {"N": "n", "E": "e", "SM": "sm", "kerma": "kerma"}

    if not Path(path).exists():
        raise FileNotFoundError(path)

    with open(path, "r") as f:
        raw = json.load(f)

    # 1. Parse and sort valid energies upfront
    energy_map = {}
    for k in raw.keys():
        try:
            energy_map[float(k)] = k
        except (TypeError, ValueError):
            continue

    if not energy_map:
        raise ValueError("No energy-like keys found in JSON.")

    # Python dictionaries maintain insertion order, so we create a sorted dictionary
    sorted_energy_map = {k: energy_map[k] for k in sorted(energy_map.keys())}

    # 2. Build individual SpectralGrids using the helper
    N_grid = _build_spectral_grid(raw, sorted_energy_map, keymap.get("N", "n"), dtype, "counts", required=True)
    E_grid = _build_spectral_grid(raw, sorted_energy_map, keymap.get("E", "e"), dtype, "a.u.", required=True)
    SM_grid = _build_spectral_grid(raw, sorted_energy_map, keymap.get("SM", "sm"), dtype, "a.u.", required=True)

    # Optional kerma
    kerma_grid = None
    if "kerma" in keymap:
        kerma_grid = _build_spectral_grid(raw, sorted_energy_map, keymap["kerma"], dtype, "Gy", required=False)

    meta = {"schema_version": 1, "units": {"energy": "keV"}}
    energies = np.array(list(sorted_energy_map.keys()), dtype=float)

    # 3. Assemble and return the SpectralSet
    return dataformats.SpectralSet(
        energies=energies, 
        N=N_grid, 
        E=E_grid, 
        SM=SM_grid, 
        kerma=kerma_grid, 
        meta=meta
    )

Constants

flexpose.constants