fab.datasources.special

  1from . import DataSource, HDFSource
  2import h5py as h5
  3import dask
  4import numpy as np
  5
  6from ..settings import cfg
  7
  8import logging
  9logger = logging.getLogger(__name__)
 10
 11__all__ = ['Timestamp', 'GMD', 'BAM', 'Gotthard']
 12
 13class Timestamp(HDFSource):
 14    ''' Loads the (indicative) timestamps for each pulse train
 15    
 16        Provides the timestamp of each FLASH pulse train. Be aware that the values 
 17        might not be accurate enough to be used for synchronization with other data
 18        sources that are not based on the HDF5 files provided by FLASH.
 19    Args:
 20        date_dtype (bool): If True, the timestamps are converted to a datetime64[s] dtype.
 21            default: True
 22        Other arguments: see `fab.datasources.HDFSource`
 23    '''
 24    def __init__(self, name='timestamp', 
 25                       hdf_key = "/zraw/FLASH.DIAG/TIMINGINFO/TIME1.BUNCH_FIRST_INDEX.2/dGroup", *args,
 26                       preload_values=True, date_dtype=True, **kwargs):
 27
 28        super().__init__(name, hdf_key, *args, preload_values=preload_values, **kwargs)
 29
 30        if date_dtype:
 31            self.dtype = 'datetime64[s]'
 32        else:
 33            self.dtype = 'float64'
 34
 35        self._preload_key_vals.append(self.dtype)
 36
 37    @staticmethod
 38    @dask.delayed
 39    def _load_key(hdf_key, fname):         #Override loading to get the 'time' field instead of 'value'
 40        return h5.File(fname)[hdf_key]['time'][:]
 41
 42    def _load_from_file(self, file_data):  #Intercept data shape and take only lenght
 43        newshape = (file_data.data_shape[0], )
 44        return super()._load_from_file(file_data._replace(data_shape=newshape))
 45
 46    def _load(self, *args, **kwargs):      #Intercept data and cast to chosen dtype
 47        return super()._load(*args, **kwargs).astype(self.dtype)
 48
 49class _FastGMD(HDFSource):
 50    ''' Helper class to load the raw GMD data from the HDF files without extra dimensions
 51    
 52    Do not use this class directly, use the `GMD` class instead. If you want to load the
 53    fast data without calibration, set the calibration_key to "".
 54
 55    This class clean up the raw HDF data from a GMD monitor and only loads pulse intensities
 56    in a 2 dimensional array with shape (train_id, shotnum).
 57
 58    Args:
 59        same as HDFSource
 60    '''
 61    def __init__(self, *args, **kwargs):
 62        super().__init__(*args, **kwargs)
 63        self.dim_names = ['shot_id']
 64
 65    @staticmethod
 66    @dask.delayed
 67    def _load_key(hdf_key, fname):         #Override loading to get only first element of second dimension
 68        return h5.File(fname)[hdf_key]['value'][:, 0, :]  
 69
 70    def _load_from_file(self, file_data):  #Intercept data shape and remove second dimension, we won't be loading it
 71        newshape = file_data.data_shape[0], file_data.data_shape[2]
 72        return super()._load_from_file(file_data._replace(data_shape=newshape))
 73
 74
 75class GMD(DataSource):
 76    """ Ad-hoc loader for the GMD data for gmd monitors (pulse resolved)
 77    
 78        Loads pulse resolved GMD data and calibrates it using the average GMD data.
 79        If a calibration key is provided, the data is units of uJ.
 80
 81        Args:
 82            name (str): Name of the data source
 83            data_key (str): HDF key for the pulse-resolved GMD data, 
 84                eg: "/FL2/Photon Diagnostic/GMD/Pulse resolved energy/energy hall"
 85            calibration_key (str): HDF key pointing average GMD data for calibration
 86                eg: "/FL2/Photon Diagnostic/GMD/Average energy/energy hall"
 87                Set this to "" to disable calibration. Skipping calibration will
 88                increase loading performance. If you do not need absolute values
 89                for the GMD, you can safely skip calibration.
 90            block_size (int): Number of shots to average over for calibration
 91    """
 92
 93    def __init__(self, *args, data_key: str, calibration_key: str = None, block_size = 2000, 
 94                                             beamtime = None, idx_path = None, hdf_path = None, **kwargs):
 95        super().__init__(*args, **kwargs)
 96        self.fast = _FastGMD(f"_{self.name}_fast", data_key, beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
 97        self.block_size = block_size
 98        
 99        match calibration_key:
100            case "":
101                self.slow = None
102
103            case None:
104                logger.warn('GMD data will not be calibrated. Please provide an average_key argument or set it to "" to disable this warning.')
105                self.slow = None
106
107            case _:
108                self.slow = HDFSource(f"_{self.name}_slow", calibration_key, preload_values=kwargs.get('preload_values', None))
109
110
111    def _repr_rows(self):
112        rows = super()._repr_rows()
113        rows += [
114            ('Data key',        self.fast.hdf_key),
115            ('Calibration key', self.slow.hdf_key if self.slow else 'disabled'),
116        ]
117        if self.slow:
118            rows += [('Calibration block size', self.block_size)]
119        return rows
120
121    def load(self, *, daq_run=None):
122        fast = self.fast.load(daq_run=daq_run)
123
124        #Calibrate fast data using slow data average
125        if self.slow:
126            slow = self.slow.load(daq_run=daq_run).reindex_like(fast).ffill(dim='train_id')
127
128            slow_avg = slow.rolling(train_id = self.block_size, min_periods=2).mean()
129            fast_avg = fast.rolling(train_id = self.block_size, min_periods=2).mean().mean(dim='shot_id')
130            ratio = (slow_avg/fast_avg)
131            fast = fast * ratio
132
133        return fast.rename(self.name)
134
135class BAM(DataSource):
136    ''' Ad-hoc loader for the BAM data from bunch arrival monitors
137    
138    Cleans up the raw HDF data for BAM data and only loads valid data
139    in a two-dimensional array with shape (train_id, shot_id).
140
141    Args:
142        name (str): Name of the data source
143        timing_key (str): HDF key where to load the number of shots per pulse train
144            e.g. `/zraw/FLASH.DIAG/TIMINGINFO/TIME1.BUNCH_FIRST_INDEX.2/dGroup`
145        data_key (str): HDF key for actual BAM data, e.g.
146            `/zraw/FLASH.SDIAG/BAM.DAQ/FL2.SEED5.ARRIVAL_TIME.ABSOLUTE.SA2.COMP/dGroup`
147        fillna_method: see `fab.datasources.DataSource`
148    '''
149    def __init__(self, *args, timing_key, data_key,                        
150                              beamtime = None, idx_path = None, hdf_path = None, **kwargs):
151        super().__init__(*args, **kwargs)
152        self.timing = HDFSource(f"_{self.name}_timing", timing_key, preload_values=kwargs.get('preload_values', True),
153                                beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
154        self.data   = HDFSource(self.name, data_key, dim_names=['shot_id'],
155                                beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
156
157    def _repr_rows(self):
158        rows = super()._repr_rows()
159        rows += [
160            ('Timing key', self.timing.hdf_key),
161            ('Data key',   self.data.hdf_key),
162        ]
163        return rows
164
165    def load(self, *, daq_run=None):
166        timing = self.timing.load(daq_run=daq_run)
167        data   = self.data.load(daq_run=daq_run)
168
169        shot_num = int(timing[:,3].max())
170        return data[:, :shot_num]
171
172class Gotthard(HDFSource):
173    ''' Loader for the Gotthard spectromter. 
174    
175        Implements low-level, per-file background subtraction as per specified in the configuration.
176        The background is computed as the average of the lines in the `bkg_rois` argument, and is optionally 
177        scaled by the average of the pixels specified in the `scale_rois` argument. The background is then 
178        subtracted from the image. 
179
180        Note that supplying data_roi and pixel_roi will have a significant impact on the performance, as the
181            they will reduce the amount of data that need to be processed. Always use these arguments if you 
182            only need a subset of the data.
183
184        Args:
185            name (str): Name of the data source
186            hdf_key (str): HDF key for the Gotthard images, default: "/FL2/Support Infrastructure/Gotthard/images"
187
188            bkg_rois (list): List of background ROIs, each ROI is a tuple of (start, end) pixel indices.
189                corresponds to the rows of the image where no signal is expected. The average value
190                of these pixels will be used to compute the background.
191
192            scale_rois (list): List of scaling ROIs, each ROI is a tuple of (start, end) pixel indices.
193                corresponds to the columns of the image where no signal is expected. The average value
194                of these pixels will be used to scale the background before subtraction.
195
196            data_roi (tuple): Location of the data rows. The ROI is a tuple of (start, end) pixel indices.
197                If given, only the rows in this ROI will be returned, and the dimensions will be renamed 
198                to 'shot_id' and '<name>_pixels', so that it can be aligned to other shot-resolved data.
199                If not given, all data will be returned, and the dimensions will be named '<name>_rows' 
200                and '<name>_pixels'.
201
202            pixel_roi (tuple): Location of the relevant data in the pixel axis. The ROI is a tuple of (start, end) 
203                pixel indices. If given, only the pixels in this ROI will be computed.
204
205        Example:
206            bg_rois = [(0, 4), (90, 100)]
207            scale_rois = [(2, 200), (1200, 1280)]
208            data_roi = (4, 90)
209
210    '''
211
212
213
214    def __init__(self,  name, hdf_key='/FL2/Support Infrastructure/Gotthard/images', *args,
215                        bkg_rois, scale_rois=None, data_roi=None, pixel_roi=None, **kwargs):
216        
217        super().__init__(name, hdf_key, *args, **kwargs)
218
219        if data_roi is not None:
220            self.dim_names = ['shot_id', f'{self.name}_pixels']
221        else:
222            self.dim_names = [f'{self.name}_rows', f'{self.name}_pixels']
223
224        self.bkg_rois = [slice(start, end) for start, end in bkg_rois]
225        self.scale_rois = [slice(start, end) for start, end in (scale_rois or [])]
226        self.data_roi = slice(data_roi[0], data_roi[1]) if data_roi else slice(None, None)
227        self.pixel_roi = slice(pixel_roi[0], pixel_roi[1]) if pixel_roi else slice(None, None)
228
229        self._preload_key_vals.append([self.data_roi, self.bkg_rois, self.scale_rois])
230
231    def _repr_rows(self):
232        rows = super()._repr_rows()
233        rows += [
234            ('Background ROIs', self.bkg_rois),
235            ('Scale ROIs', self.scale_rois),
236            ('Data ROI', self.data_roi),
237            ('Pixel ROI', self.pixel_roi),
238        ]
239        return rows
240
241
242    def _load_from_file(self, file_data):  #Intercept data shape and change it
243        # Data shape is (train_id, rows, pixels). 
244
245        # Compute data_roi explicitely and calculate new_shape if we need to
246        data_roi = slice(self.data_roi.start or 0, self.data_roi.stop or file_data.data_shape[1])
247        pixel_roi = slice(self.pixel_roi.start or 0, self.pixel_roi.stop or file_data.data_shape[2])
248
249        new_shape = file_data.data_shape[0], (data_roi.stop - data_roi.start), (pixel_roi.stop - pixel_roi.start)
250
251        # Compute bkg and scale rois explicitely
252        bkg_rois = [slice(roi.start or 0, roi.stop or file_data.data_shape[1]) for roi in self.bkg_rois]
253        scale_rois = [slice(roi.start or 0, roi.stop or file_data.data_shape[2]) for roi in self.scale_rois]
254
255        return super()._load_from_file(file_data._replace(data_shape=new_shape),
256                                       bkg_rois=bkg_rois, scale_rois=scale_rois,
257                                       data_roi=data_roi, pixel_roi=pixel_roi,
258                                       dtype=file_data.dtype)
259
260    @staticmethod
261    @dask.delayed(pure=True)
262    def _load_key(hdf_key, fname, bkg_rois: list, scale_rois: list, 
263                                  data_roi: slice, pixel_roi: slice, 
264                                  dtype: np.dtype): 
265
266        data = h5.File(fname)[hdf_key]['value'][:]  # Data shape is (train_id, rows, pixels)
267        
268        if np.issubdtype(dtype, np.integer):
269            data = data.astype(np.float32)  # Background subtraction will change int to float
270
271        # Compute background
272        bkg_mask = np.zeros(data.shape[1], dtype=bool)
273        for roi in bkg_rois:
274            bkg_mask[roi] = True
275
276        bkg = data[:, bkg_mask].mean(axis=(0, 1), keepdims=True)
277
278        # Apply data_roi
279        data = data[:, data_roi]
280
281        # Scale background if scale_rois are specified
282        if scale_rois:
283            # We need to do this before applying pixel_roi, 
284            # as the scale rois are not necessarily inside of pixel_roi
285
286            scale_mask = np.zeros(data.shape[2], dtype=bool)
287            for roi in scale_rois:
288                scale_mask[roi] = True
289
290            bkg_scale = bkg.mean(where=scale_mask[None, None, :])
291            images_scale = data.mean(axis=2, where=scale_mask[None, None, :], 
292                                     keepdims=True)
293
294        data = data[:, :, pixel_roi]
295        bkg  = bkg[:, :, pixel_roi]
296
297        if scale_rois:
298            data -= images_scale * bkg / bkg_scale
299        else:
300            data -= bkg
301
302        if np.issubdtype(dtype, np.integer):
303            return data.round()
304
305        return data.astype(dtype)
class Timestamp(fab.datasources.HDFSource.HDFSource):
14class Timestamp(HDFSource):
15    ''' Loads the (indicative) timestamps for each pulse train
16    
17        Provides the timestamp of each FLASH pulse train. Be aware that the values 
18        might not be accurate enough to be used for synchronization with other data
19        sources that are not based on the HDF5 files provided by FLASH.
20    Args:
21        date_dtype (bool): If True, the timestamps are converted to a datetime64[s] dtype.
22            default: True
23        Other arguments: see `fab.datasources.HDFSource`
24    '''
25    def __init__(self, name='timestamp', 
26                       hdf_key = "/zraw/FLASH.DIAG/TIMINGINFO/TIME1.BUNCH_FIRST_INDEX.2/dGroup", *args,
27                       preload_values=True, date_dtype=True, **kwargs):
28
29        super().__init__(name, hdf_key, *args, preload_values=preload_values, **kwargs)
30
31        if date_dtype:
32            self.dtype = 'datetime64[s]'
33        else:
34            self.dtype = 'float64'
35
36        self._preload_key_vals.append(self.dtype)
37
38    @staticmethod
39    @dask.delayed
40    def _load_key(hdf_key, fname):         #Override loading to get the 'time' field instead of 'value'
41        return h5.File(fname)[hdf_key]['time'][:]
42
43    def _load_from_file(self, file_data):  #Intercept data shape and take only lenght
44        newshape = (file_data.data_shape[0], )
45        return super()._load_from_file(file_data._replace(data_shape=newshape))
46
47    def _load(self, *args, **kwargs):      #Intercept data and cast to chosen dtype
48        return super()._load(*args, **kwargs).astype(self.dtype)

Loads the (indicative) timestamps for each pulse train

Provides the timestamp of each FLASH pulse train. Be aware that the values 
might not be accurate enough to be used for synchronization with other data
sources that are not based on the HDF5 files provided by FLASH.
Arguments:
  • date_dtype (bool): If True, the timestamps are converted to a datetime64[s] dtype. default: True
  • Other arguments: see fab.datasources.HDFSource
Timestamp( name='timestamp', hdf_key='/zraw/FLASH.DIAG/TIMINGINFO/TIME1.BUNCH_FIRST_INDEX.2/dGroup', *args, preload_values=True, date_dtype=True, **kwargs)
25    def __init__(self, name='timestamp', 
26                       hdf_key = "/zraw/FLASH.DIAG/TIMINGINFO/TIME1.BUNCH_FIRST_INDEX.2/dGroup", *args,
27                       preload_values=True, date_dtype=True, **kwargs):
28
29        super().__init__(name, hdf_key, *args, preload_values=preload_values, **kwargs)
30
31        if date_dtype:
32            self.dtype = 'datetime64[s]'
33        else:
34            self.dtype = 'float64'
35
36        self._preload_key_vals.append(self.dtype)

Base init for a data source.

Arguments:
  • name: a human readable name for the data source.
  • fillna_method (optional): a string specifying what filling method should be used to fill missing values if the dataset needs to be reindexed. This will happen when the datasource is combined with other sources in an Instrument object that will require all source to have the same train_id index. It should be either 'ffill' for forward filling, or one of the valid method for xr.interpolate_na. Using methods other than 'ffill' on large arrays might lead to extremely high memory usage.
class GMD(fab.datasources.basesources.DataSource):
 76class GMD(DataSource):
 77    """ Ad-hoc loader for the GMD data for gmd monitors (pulse resolved)
 78    
 79        Loads pulse resolved GMD data and calibrates it using the average GMD data.
 80        If a calibration key is provided, the data is units of uJ.
 81
 82        Args:
 83            name (str): Name of the data source
 84            data_key (str): HDF key for the pulse-resolved GMD data, 
 85                eg: "/FL2/Photon Diagnostic/GMD/Pulse resolved energy/energy hall"
 86            calibration_key (str): HDF key pointing average GMD data for calibration
 87                eg: "/FL2/Photon Diagnostic/GMD/Average energy/energy hall"
 88                Set this to "" to disable calibration. Skipping calibration will
 89                increase loading performance. If you do not need absolute values
 90                for the GMD, you can safely skip calibration.
 91            block_size (int): Number of shots to average over for calibration
 92    """
 93
 94    def __init__(self, *args, data_key: str, calibration_key: str = None, block_size = 2000, 
 95                                             beamtime = None, idx_path = None, hdf_path = None, **kwargs):
 96        super().__init__(*args, **kwargs)
 97        self.fast = _FastGMD(f"_{self.name}_fast", data_key, beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
 98        self.block_size = block_size
 99        
100        match calibration_key:
101            case "":
102                self.slow = None
103
104            case None:
105                logger.warn('GMD data will not be calibrated. Please provide an average_key argument or set it to "" to disable this warning.')
106                self.slow = None
107
108            case _:
109                self.slow = HDFSource(f"_{self.name}_slow", calibration_key, preload_values=kwargs.get('preload_values', None))
110
111
112    def _repr_rows(self):
113        rows = super()._repr_rows()
114        rows += [
115            ('Data key',        self.fast.hdf_key),
116            ('Calibration key', self.slow.hdf_key if self.slow else 'disabled'),
117        ]
118        if self.slow:
119            rows += [('Calibration block size', self.block_size)]
120        return rows
121
122    def load(self, *, daq_run=None):
123        fast = self.fast.load(daq_run=daq_run)
124
125        #Calibrate fast data using slow data average
126        if self.slow:
127            slow = self.slow.load(daq_run=daq_run).reindex_like(fast).ffill(dim='train_id')
128
129            slow_avg = slow.rolling(train_id = self.block_size, min_periods=2).mean()
130            fast_avg = fast.rolling(train_id = self.block_size, min_periods=2).mean().mean(dim='shot_id')
131            ratio = (slow_avg/fast_avg)
132            fast = fast * ratio
133
134        return fast.rename(self.name)

Ad-hoc loader for the GMD data for gmd monitors (pulse resolved)

Loads pulse resolved GMD data and calibrates it using the average GMD data. If a calibration key is provided, the data is units of uJ.

Arguments:
  • name (str): Name of the data source
  • data_key (str): HDF key for the pulse-resolved GMD data, eg: "/FL2/Photon Diagnostic/GMD/Pulse resolved energy/energy hall"
  • calibration_key (str): HDF key pointing average GMD data for calibration eg: "/FL2/Photon Diagnostic/GMD/Average energy/energy hall" Set this to "" to disable calibration. Skipping calibration will increase loading performance. If you do not need absolute values for the GMD, you can safely skip calibration.
  • block_size (int): Number of shots to average over for calibration
GMD( *args, data_key: str, calibration_key: str = None, block_size=2000, beamtime=None, idx_path=None, hdf_path=None, **kwargs)
 94    def __init__(self, *args, data_key: str, calibration_key: str = None, block_size = 2000, 
 95                                             beamtime = None, idx_path = None, hdf_path = None, **kwargs):
 96        super().__init__(*args, **kwargs)
 97        self.fast = _FastGMD(f"_{self.name}_fast", data_key, beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
 98        self.block_size = block_size
 99        
100        match calibration_key:
101            case "":
102                self.slow = None
103
104            case None:
105                logger.warn('GMD data will not be calibrated. Please provide an average_key argument or set it to "" to disable this warning.')
106                self.slow = None
107
108            case _:
109                self.slow = HDFSource(f"_{self.name}_slow", calibration_key, preload_values=kwargs.get('preload_values', None))

Base init for a data source.

Arguments:
  • name: a human readable name for the data source.
  • fillna_method (optional): a string specifying what filling method should be used to fill missing values if the dataset needs to be reindexed. This will happen when the datasource is combined with other sources in an Instrument object that will require all source to have the same train_id index. It should be either 'ffill' for forward filling, or one of the valid method for xr.interpolate_na. Using methods other than 'ffill' on large arrays might lead to extremely high memory usage.
fast
block_size
def load(self, *, daq_run=None):
122    def load(self, *, daq_run=None):
123        fast = self.fast.load(daq_run=daq_run)
124
125        #Calibrate fast data using slow data average
126        if self.slow:
127            slow = self.slow.load(daq_run=daq_run).reindex_like(fast).ffill(dim='train_id')
128
129            slow_avg = slow.rolling(train_id = self.block_size, min_periods=2).mean()
130            fast_avg = fast.rolling(train_id = self.block_size, min_periods=2).mean().mean(dim='shot_id')
131            ratio = (slow_avg/fast_avg)
132            fast = fast * ratio
133
134        return fast.rename(self.name)

Loads thata from the datasource

Returns: xr.DataArray: the loaded data, possibly represented by a lazy dask.array. It must contain a dimension named 'train_id'

class BAM(fab.datasources.basesources.DataSource):
136class BAM(DataSource):
137    ''' Ad-hoc loader for the BAM data from bunch arrival monitors
138    
139    Cleans up the raw HDF data for BAM data and only loads valid data
140    in a two-dimensional array with shape (train_id, shot_id).
141
142    Args:
143        name (str): Name of the data source
144        timing_key (str): HDF key where to load the number of shots per pulse train
145            e.g. `/zraw/FLASH.DIAG/TIMINGINFO/TIME1.BUNCH_FIRST_INDEX.2/dGroup`
146        data_key (str): HDF key for actual BAM data, e.g.
147            `/zraw/FLASH.SDIAG/BAM.DAQ/FL2.SEED5.ARRIVAL_TIME.ABSOLUTE.SA2.COMP/dGroup`
148        fillna_method: see `fab.datasources.DataSource`
149    '''
150    def __init__(self, *args, timing_key, data_key,                        
151                              beamtime = None, idx_path = None, hdf_path = None, **kwargs):
152        super().__init__(*args, **kwargs)
153        self.timing = HDFSource(f"_{self.name}_timing", timing_key, preload_values=kwargs.get('preload_values', True),
154                                beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
155        self.data   = HDFSource(self.name, data_key, dim_names=['shot_id'],
156                                beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
157
158    def _repr_rows(self):
159        rows = super()._repr_rows()
160        rows += [
161            ('Timing key', self.timing.hdf_key),
162            ('Data key',   self.data.hdf_key),
163        ]
164        return rows
165
166    def load(self, *, daq_run=None):
167        timing = self.timing.load(daq_run=daq_run)
168        data   = self.data.load(daq_run=daq_run)
169
170        shot_num = int(timing[:,3].max())
171        return data[:, :shot_num]

Ad-hoc loader for the BAM data from bunch arrival monitors

Cleans up the raw HDF data for BAM data and only loads valid data in a two-dimensional array with shape (train_id, shot_id).

Arguments:
  • name (str): Name of the data source
  • timing_key (str): HDF key where to load the number of shots per pulse train e.g. /zraw/FLASH.DIAG/TIMINGINFO/TIME1.BUNCH_FIRST_INDEX.2/dGroup
  • data_key (str): HDF key for actual BAM data, e.g. /zraw/FLASH.SDIAG/BAM.DAQ/FL2.SEED5.ARRIVAL_TIME.ABSOLUTE.SA2.COMP/dGroup
  • fillna_method: see fab.datasources.DataSource
BAM( *args, timing_key, data_key, beamtime=None, idx_path=None, hdf_path=None, **kwargs)
150    def __init__(self, *args, timing_key, data_key,                        
151                              beamtime = None, idx_path = None, hdf_path = None, **kwargs):
152        super().__init__(*args, **kwargs)
153        self.timing = HDFSource(f"_{self.name}_timing", timing_key, preload_values=kwargs.get('preload_values', True),
154                                beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)
155        self.data   = HDFSource(self.name, data_key, dim_names=['shot_id'],
156                                beamtime=beamtime, hdf_path=hdf_path, idx_path=idx_path)

Base init for a data source.

Arguments:
  • name: a human readable name for the data source.
  • fillna_method (optional): a string specifying what filling method should be used to fill missing values if the dataset needs to be reindexed. This will happen when the datasource is combined with other sources in an Instrument object that will require all source to have the same train_id index. It should be either 'ffill' for forward filling, or one of the valid method for xr.interpolate_na. Using methods other than 'ffill' on large arrays might lead to extremely high memory usage.
timing
data
def load(self, *, daq_run=None):
166    def load(self, *, daq_run=None):
167        timing = self.timing.load(daq_run=daq_run)
168        data   = self.data.load(daq_run=daq_run)
169
170        shot_num = int(timing[:,3].max())
171        return data[:, :shot_num]

Loads thata from the datasource

Returns: xr.DataArray: the loaded data, possibly represented by a lazy dask.array. It must contain a dimension named 'train_id'

class Gotthard(fab.datasources.HDFSource.HDFSource):
173class Gotthard(HDFSource):
174    ''' Loader for the Gotthard spectromter. 
175    
176        Implements low-level, per-file background subtraction as per specified in the configuration.
177        The background is computed as the average of the lines in the `bkg_rois` argument, and is optionally 
178        scaled by the average of the pixels specified in the `scale_rois` argument. The background is then 
179        subtracted from the image. 
180
181        Note that supplying data_roi and pixel_roi will have a significant impact on the performance, as the
182            they will reduce the amount of data that need to be processed. Always use these arguments if you 
183            only need a subset of the data.
184
185        Args:
186            name (str): Name of the data source
187            hdf_key (str): HDF key for the Gotthard images, default: "/FL2/Support Infrastructure/Gotthard/images"
188
189            bkg_rois (list): List of background ROIs, each ROI is a tuple of (start, end) pixel indices.
190                corresponds to the rows of the image where no signal is expected. The average value
191                of these pixels will be used to compute the background.
192
193            scale_rois (list): List of scaling ROIs, each ROI is a tuple of (start, end) pixel indices.
194                corresponds to the columns of the image where no signal is expected. The average value
195                of these pixels will be used to scale the background before subtraction.
196
197            data_roi (tuple): Location of the data rows. The ROI is a tuple of (start, end) pixel indices.
198                If given, only the rows in this ROI will be returned, and the dimensions will be renamed 
199                to 'shot_id' and '<name>_pixels', so that it can be aligned to other shot-resolved data.
200                If not given, all data will be returned, and the dimensions will be named '<name>_rows' 
201                and '<name>_pixels'.
202
203            pixel_roi (tuple): Location of the relevant data in the pixel axis. The ROI is a tuple of (start, end) 
204                pixel indices. If given, only the pixels in this ROI will be computed.
205
206        Example:
207            bg_rois = [(0, 4), (90, 100)]
208            scale_rois = [(2, 200), (1200, 1280)]
209            data_roi = (4, 90)
210
211    '''
212
213
214
215    def __init__(self,  name, hdf_key='/FL2/Support Infrastructure/Gotthard/images', *args,
216                        bkg_rois, scale_rois=None, data_roi=None, pixel_roi=None, **kwargs):
217        
218        super().__init__(name, hdf_key, *args, **kwargs)
219
220        if data_roi is not None:
221            self.dim_names = ['shot_id', f'{self.name}_pixels']
222        else:
223            self.dim_names = [f'{self.name}_rows', f'{self.name}_pixels']
224
225        self.bkg_rois = [slice(start, end) for start, end in bkg_rois]
226        self.scale_rois = [slice(start, end) for start, end in (scale_rois or [])]
227        self.data_roi = slice(data_roi[0], data_roi[1]) if data_roi else slice(None, None)
228        self.pixel_roi = slice(pixel_roi[0], pixel_roi[1]) if pixel_roi else slice(None, None)
229
230        self._preload_key_vals.append([self.data_roi, self.bkg_rois, self.scale_rois])
231
232    def _repr_rows(self):
233        rows = super()._repr_rows()
234        rows += [
235            ('Background ROIs', self.bkg_rois),
236            ('Scale ROIs', self.scale_rois),
237            ('Data ROI', self.data_roi),
238            ('Pixel ROI', self.pixel_roi),
239        ]
240        return rows
241
242
243    def _load_from_file(self, file_data):  #Intercept data shape and change it
244        # Data shape is (train_id, rows, pixels). 
245
246        # Compute data_roi explicitely and calculate new_shape if we need to
247        data_roi = slice(self.data_roi.start or 0, self.data_roi.stop or file_data.data_shape[1])
248        pixel_roi = slice(self.pixel_roi.start or 0, self.pixel_roi.stop or file_data.data_shape[2])
249
250        new_shape = file_data.data_shape[0], (data_roi.stop - data_roi.start), (pixel_roi.stop - pixel_roi.start)
251
252        # Compute bkg and scale rois explicitely
253        bkg_rois = [slice(roi.start or 0, roi.stop or file_data.data_shape[1]) for roi in self.bkg_rois]
254        scale_rois = [slice(roi.start or 0, roi.stop or file_data.data_shape[2]) for roi in self.scale_rois]
255
256        return super()._load_from_file(file_data._replace(data_shape=new_shape),
257                                       bkg_rois=bkg_rois, scale_rois=scale_rois,
258                                       data_roi=data_roi, pixel_roi=pixel_roi,
259                                       dtype=file_data.dtype)
260
261    @staticmethod
262    @dask.delayed(pure=True)
263    def _load_key(hdf_key, fname, bkg_rois: list, scale_rois: list, 
264                                  data_roi: slice, pixel_roi: slice, 
265                                  dtype: np.dtype): 
266
267        data = h5.File(fname)[hdf_key]['value'][:]  # Data shape is (train_id, rows, pixels)
268        
269        if np.issubdtype(dtype, np.integer):
270            data = data.astype(np.float32)  # Background subtraction will change int to float
271
272        # Compute background
273        bkg_mask = np.zeros(data.shape[1], dtype=bool)
274        for roi in bkg_rois:
275            bkg_mask[roi] = True
276
277        bkg = data[:, bkg_mask].mean(axis=(0, 1), keepdims=True)
278
279        # Apply data_roi
280        data = data[:, data_roi]
281
282        # Scale background if scale_rois are specified
283        if scale_rois:
284            # We need to do this before applying pixel_roi, 
285            # as the scale rois are not necessarily inside of pixel_roi
286
287            scale_mask = np.zeros(data.shape[2], dtype=bool)
288            for roi in scale_rois:
289                scale_mask[roi] = True
290
291            bkg_scale = bkg.mean(where=scale_mask[None, None, :])
292            images_scale = data.mean(axis=2, where=scale_mask[None, None, :], 
293                                     keepdims=True)
294
295        data = data[:, :, pixel_roi]
296        bkg  = bkg[:, :, pixel_roi]
297
298        if scale_rois:
299            data -= images_scale * bkg / bkg_scale
300        else:
301            data -= bkg
302
303        if np.issubdtype(dtype, np.integer):
304            return data.round()
305
306        return data.astype(dtype)

Loader for the Gotthard spectromter.

Implements low-level, per-file background subtraction as per specified in the configuration. The background is computed as the average of the lines in the bkg_rois argument, and is optionally scaled by the average of the pixels specified in the scale_rois argument. The background is then subtracted from the image.

Note that supplying data_roi and pixel_roi will have a significant impact on the performance, as the they will reduce the amount of data that need to be processed. Always use these arguments if you only need a subset of the data.

Arguments:
  • name (str): Name of the data source
  • hdf_key (str): HDF key for the Gotthard images, default: "/FL2/Support Infrastructure/Gotthard/images"
  • bkg_rois (list): List of background ROIs, each ROI is a tuple of (start, end) pixel indices. corresponds to the rows of the image where no signal is expected. The average value of these pixels will be used to compute the background.
  • scale_rois (list): List of scaling ROIs, each ROI is a tuple of (start, end) pixel indices. corresponds to the columns of the image where no signal is expected. The average value of these pixels will be used to scale the background before subtraction.
  • data_roi (tuple): Location of the data rows. The ROI is a tuple of (start, end) pixel indices. If given, only the rows in this ROI will be returned, and the dimensions will be renamed to 'shot_id' and '_pixels', so that it can be aligned to other shot-resolved data. If not given, all data will be returned, and the dimensions will be named '_rows' and '_pixels'.
  • pixel_roi (tuple): Location of the relevant data in the pixel axis. The ROI is a tuple of (start, end) pixel indices. If given, only the pixels in this ROI will be computed.
Example:

bg_rois = [(0, 4), (90, 100)] scale_rois = [(2, 200), (1200, 1280)] data_roi = (4, 90)

Gotthard( name, hdf_key='/FL2/Support Infrastructure/Gotthard/images', *args, bkg_rois, scale_rois=None, data_roi=None, pixel_roi=None, **kwargs)
215    def __init__(self,  name, hdf_key='/FL2/Support Infrastructure/Gotthard/images', *args,
216                        bkg_rois, scale_rois=None, data_roi=None, pixel_roi=None, **kwargs):
217        
218        super().__init__(name, hdf_key, *args, **kwargs)
219
220        if data_roi is not None:
221            self.dim_names = ['shot_id', f'{self.name}_pixels']
222        else:
223            self.dim_names = [f'{self.name}_rows', f'{self.name}_pixels']
224
225        self.bkg_rois = [slice(start, end) for start, end in bkg_rois]
226        self.scale_rois = [slice(start, end) for start, end in (scale_rois or [])]
227        self.data_roi = slice(data_roi[0], data_roi[1]) if data_roi else slice(None, None)
228        self.pixel_roi = slice(pixel_roi[0], pixel_roi[1]) if pixel_roi else slice(None, None)
229
230        self._preload_key_vals.append([self.data_roi, self.bkg_rois, self.scale_rois])

Base init for a data source.

Arguments:
  • name: a human readable name for the data source.
  • fillna_method (optional): a string specifying what filling method should be used to fill missing values if the dataset needs to be reindexed. This will happen when the datasource is combined with other sources in an Instrument object that will require all source to have the same train_id index. It should be either 'ffill' for forward filling, or one of the valid method for xr.interpolate_na. Using methods other than 'ffill' on large arrays might lead to extremely high memory usage.
bkg_rois
scale_rois
data_roi
pixel_roi