• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

OpenCOMPES / sed / 6022150883

30 Aug 2023 07:55AM UTC coverage: 73.981% (+0.05%) from 73.931%
6022150883

Pull #131

github

rettigl
update docs
Pull Request #131: Default config and documentation

82 of 82 new or added lines in 7 files covered. (100.0%)

3048 of 4120 relevant lines covered (73.98%)

0.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

34.83
/sed/core/processor.py
1
"""This module contains the core class for the sed package
2

3
"""
4
import pathlib
1✔
5
from typing import Any
1✔
6
from typing import cast
1✔
7
from typing import Dict
1✔
8
from typing import List
1✔
9
from typing import Sequence
1✔
10
from typing import Tuple
1✔
11
from typing import Union
1✔
12

13
import dask.dataframe as ddf
1✔
14
import matplotlib.pyplot as plt
1✔
15
import numpy as np
1✔
16
import pandas as pd
1✔
17
import psutil
1✔
18
import xarray as xr
1✔
19

20
from sed.binning import bin_dataframe
1✔
21
from sed.calibrator import DelayCalibrator
1✔
22
from sed.calibrator import EnergyCalibrator
1✔
23
from sed.calibrator import MomentumCorrector
1✔
24
from sed.core.config import parse_config
1✔
25
from sed.core.config import save_config
1✔
26
from sed.core.dfops import apply_jitter
1✔
27
from sed.core.metadata import MetaHandler
1✔
28
from sed.diagnostics import grid_histogram
1✔
29
from sed.io import to_h5
1✔
30
from sed.io import to_nexus
1✔
31
from sed.io import to_tiff
1✔
32
from sed.loader import CopyTool
1✔
33
from sed.loader import get_loader
1✔
34

35
N_CPU = psutil.cpu_count()
1✔
36

37

38
class SedProcessor:
1✔
39
    """Processor class of sed. Contains wrapper functions defining a work flow for data
40
    correction, calibration and binning.
41

42
    Args:
43
        metadata (dict, optional): Dict of external Metadata. Defaults to None.
44
        config (Union[dict, str], optional): Config dictionary or config file name.
45
            Defaults to None.
46
        dataframe (Union[pd.DataFrame, ddf.DataFrame], optional): dataframe to load
47
            into the class. Defaults to None.
48
        files (List[str], optional): List of files to pass to the loader defined in
49
            the config. Defaults to None.
50
        folder (str, optional): Folder containing files to pass to the loader
51
            defined in the config. Defaults to None.
52
        collect_metadata (bool): Option to collect metadata from files.
53
            Defaults to False.
54
        **kwds: Keyword arguments passed to the reader.
55
    """
56

57
    def __init__(
1✔
58
        self,
59
        metadata: dict = None,
60
        config: Union[dict, str] = None,
61
        dataframe: Union[pd.DataFrame, ddf.DataFrame] = None,
62
        files: List[str] = None,
63
        folder: str = None,
64
        runs: Sequence[str] = None,
65
        collect_metadata: bool = False,
66
        **kwds,
67
    ):
68
        """Processor class of sed. Contains wrapper functions defining a work flow
69
        for data correction, calibration, and binning.
70

71
        Args:
72
            metadata (dict, optional): Dict of external Metadata. Defaults to None.
73
            config (Union[dict, str], optional): Config dictionary or config file name.
74
                Defaults to None.
75
            dataframe (Union[pd.DataFrame, ddf.DataFrame], optional): dataframe to load
76
                into the class. Defaults to None.
77
            files (List[str], optional): List of files to pass to the loader defined in
78
                the config. Defaults to None.
79
            folder (str, optional): Folder containing files to pass to the loader
80
                defined in the config. Defaults to None.
81
            runs (Sequence[str], optional): List of run identifiers to pass to the loader
82
                defined in the config. Defaults to None.
83
            collect_metadata (bool): Option to collect metadata from files.
84
                Defaults to False.
85
            **kwds: Keyword arguments passed to the reader.
86
        """
87
        self._config = parse_config(config, **kwds)
1✔
88
        num_cores = self._config.get("binning", {}).get("num_cores", N_CPU - 1)
1✔
89
        if num_cores >= N_CPU:
1✔
90
            num_cores = N_CPU - 1
1✔
91
        self._config["binning"]["num_cores"] = num_cores
1✔
92

93
        self._dataframe: Union[pd.DataFrame, ddf.DataFrame] = None
1✔
94
        self._files: List[str] = []
1✔
95

96
        self._binned: xr.DataArray = None
1✔
97
        self._pre_binned: xr.DataArray = None
1✔
98

99
        self._dimensions: List[str] = []
1✔
100
        self._coordinates: Dict[Any, Any] = {}
1✔
101
        self.axis: Dict[Any, Any] = {}
1✔
102
        self._attributes = MetaHandler(meta=metadata)
1✔
103

104
        loader_name = self._config["core"]["loader"]
1✔
105
        self.loader = get_loader(
1✔
106
            loader_name=loader_name,
107
            config=self._config,
108
        )
109

110
        self.ec = EnergyCalibrator(
1✔
111
            loader=self.loader,
112
            config=self._config,
113
        )
114

115
        self.mc = MomentumCorrector(
1✔
116
            config=self._config,
117
        )
118

119
        self.dc = DelayCalibrator(
1✔
120
            config=self._config,
121
        )
122

123
        self.use_copy_tool = self._config.get("core", {}).get(
1✔
124
            "use_copy_tool",
125
            False,
126
        )
127
        if self.use_copy_tool:
1✔
128
            try:
×
129
                self.ct = CopyTool(
×
130
                    source=self._config["core"]["copy_tool_source"],
131
                    dest=self._config["core"]["copy_tool_dest"],
132
                    **self._config["core"].get("copy_tool_kwds", {}),
133
                )
134
            except KeyError:
×
135
                self.use_copy_tool = False
×
136

137
        # Load data if provided:
138
        if dataframe is not None or files is not None or folder is not None or runs is not None:
1✔
139
            self.load(
×
140
                dataframe=dataframe,
141
                metadata=metadata,
142
                files=files,
143
                folder=folder,
144
                runs=runs,
145
                collect_metadata=collect_metadata,
146
                **kwds,
147
            )
148

149
    def __repr__(self):
1✔
150
        if self._dataframe is None:
×
151
            df_str = "Data Frame: No Data loaded"
×
152
        else:
153
            df_str = self._dataframe.__repr__()
×
154
        coordinates_str = f"Coordinates: {self._coordinates}"
×
155
        dimensions_str = f"Dimensions: {self._dimensions}"
×
156
        pretty_str = df_str + "\n" + coordinates_str + "\n" + dimensions_str
×
157
        return pretty_str
×
158

159
    def __getitem__(self, val: str) -> pd.DataFrame:
1✔
160
        """Accessor to the underlying data structure.
161

162
        Args:
163
            val (str): Name of the dataframe column to retrieve.
164

165
        Returns:
166
            pd.DataFrame: Selected dataframe column.
167
        """
168
        return self._dataframe[val]
×
169

170
    @property
1✔
171
    def config(self) -> Dict[Any, Any]:
1✔
172
        """Getter attribute for the config dictionary
173

174
        Returns:
175
            Dict: The config dictionary.
176
        """
177
        return self._config
×
178

179
    @config.setter
1✔
180
    def config(self, config: Union[dict, str]):
1✔
181
        """Setter function for the config dictionary.
182

183
        Args:
184
            config (Union[dict, str]): Config dictionary or path of config file
185
                to load.
186
        """
187
        self._config = parse_config(config)
×
188
        num_cores = self._config.get("binning", {}).get("num_cores", N_CPU - 1)
×
189
        if num_cores >= N_CPU:
×
190
            num_cores = N_CPU - 1
×
191
        self._config["binning"]["num_cores"] = num_cores
×
192

193
    @property
1✔
194
    def dimensions(self) -> list:
1✔
195
        """Getter attribute for the dimensions.
196

197
        Returns:
198
            list: List of dimensions.
199
        """
200
        return self._dimensions
×
201

202
    @dimensions.setter
1✔
203
    def dimensions(self, dims: list):
1✔
204
        """Setter function for the dimensions.
205

206
        Args:
207
            dims (list): List of dimensions to set.
208
        """
209
        assert isinstance(dims, list)
×
210
        self._dimensions = dims
×
211

212
    @property
1✔
213
    def coordinates(self) -> dict:
1✔
214
        """Getter attribute for the coordinates dict.
215

216
        Returns:
217
            dict: Dictionary of coordinates.
218
        """
219
        return self._coordinates
×
220

221
    @coordinates.setter
1✔
222
    def coordinates(self, coords: dict):
1✔
223
        """Setter function for the coordinates dict
224

225
        Args:
226
            coords (dict): Dictionary of coordinates.
227
        """
228
        assert isinstance(coords, dict)
×
229
        self._coordinates = {}
×
230
        for k, v in coords.items():
×
231
            self._coordinates[k] = xr.DataArray(v)
×
232

233
    def cpy(self, path: Union[str, List[str]]) -> Union[str, List[str]]:
1✔
234
        """Function to mirror a list of files or a folder from a network drive to a
235
        local storage. Returns either the original or the copied path to the given
236
        path. The option to use this functionality is set by
237
        config["core"]["use_copy_tool"].
238

239
        Args:
240
            path (Union[str, List[str]]): Source path or path list.
241

242
        Returns:
243
            Union[str, List[str]]: Source or destination path or path list.
244
        """
245
        if self.use_copy_tool:
1✔
246
            if isinstance(path, list):
×
247
                path_out = []
×
248
                for file in path:
×
249
                    path_out.append(self.ct.copy(file))
×
250
                return path_out
×
251

252
            return self.ct.copy(path)
×
253

254
        if isinstance(path, list):
1✔
255
            return path
1✔
256

257
        return path
×
258

259
    def load(
1✔
260
        self,
261
        dataframe: Union[pd.DataFrame, ddf.DataFrame] = None,
262
        metadata: dict = None,
263
        files: List[str] = None,
264
        folder: str = None,
265
        runs: Sequence[str] = None,
266
        collect_metadata: bool = False,
267
        **kwds,
268
    ):
269
        """Load tabular data of single events into the dataframe object in the class.
270

271
        Args:
272
            dataframe (Union[pd.DataFrame, ddf.DataFrame], optional): data in tabular
273
                format. Accepts anything which can be interpreted by pd.DataFrame as
274
                an input. Defaults to None.
275
            metadata (dict, optional): Dict of external Metadata. Defaults to None.
276
            files (List[str], optional): List of file paths to pass to the loader.
277
                Defaults to None.
278
            runs (Sequence[str], optional): List of run identifiers to pass to the
279
                loader. Defaults to None.
280
            folder (str, optional): Folder path to pass to the loader.
281
                Defaults to None.
282

283
        Raises:
284
            ValueError: Raised if no valid input is provided.
285
        """
286
        if metadata is None:
1✔
287
            metadata = {}
1✔
288
        if dataframe is not None:
1✔
289
            self._dataframe = dataframe
×
290
        elif runs is not None:
1✔
291
            # If runs are provided, we only use the copy tool if also folder is provided.
292
            # In that case, we copy the whole provided base folder tree, and pass the copied
293
            # version to the loader as base folder to look for the runs.
294
            if folder is not None:
×
295
                dataframe, metadata = self.loader.read_dataframe(
×
296
                    folders=cast(str, self.cpy(folder)),
297
                    runs=runs,
298
                    metadata=metadata,
299
                    collect_metadata=collect_metadata,
300
                    **kwds,
301
                )
302
            else:
303
                dataframe, metadata = self.loader.read_dataframe(
×
304
                    runs=runs,
305
                    metadata=metadata,
306
                    collect_metadata=collect_metadata,
307
                    **kwds,
308
                )
309

310
        elif folder is not None:
1✔
311
            dataframe, metadata = self.loader.read_dataframe(
×
312
                folders=cast(str, self.cpy(folder)),
313
                metadata=metadata,
314
                collect_metadata=collect_metadata,
315
                **kwds,
316
            )
317

318
        elif files is not None:
1✔
319
            dataframe, metadata = self.loader.read_dataframe(
1✔
320
                files=cast(List[str], self.cpy(files)),
321
                metadata=metadata,
322
                collect_metadata=collect_metadata,
323
                **kwds,
324
            )
325

326
        else:
327
            raise ValueError(
×
328
                "Either 'dataframe', 'files', 'folder', or 'runs' needs to be provided!",
329
            )
330

331
        self._dataframe = dataframe
1✔
332
        self._files = self.loader.files
1✔
333

334
        for key in metadata:
1✔
335
            self._attributes.add(
×
336
                entry=metadata[key],
337
                name=key,
338
                duplicate_policy="merge",
339
            )
340

341
    # Momentum calibration workflow
342
    # 1. Bin raw detector data for distortion correction
343
    def bin_and_load_momentum_calibration(
1✔
344
        self,
345
        df_partitions: int = 100,
346
        axes: List[str] = None,
347
        bins: List[int] = None,
348
        ranges: Sequence[Tuple[float, float]] = None,
349
        plane: int = 0,
350
        width: int = 5,
351
        apply: bool = False,
352
        **kwds,
353
    ):
354
        """1st step of momentum correction work flow. Function to do an initial binning
355
        of the dataframe loaded to the class, slice a plane from it using an
356
        interactive view, and load it into the momentum corrector class.
357

358
        Args:
359
            df_partitions (int, optional): Number of dataframe partitions to use for
360
                the initial binning. Defaults to 100.
361
            axes (List[str], optional): Axes to bin.
362
                Defaults to config["momentum"]["axes"].
363
            bins (List[int], optional): Bin numbers to use for binning.
364
                Defaults to config["momentum"]["bins"].
365
            ranges (List[Tuple], optional): Ranges to use for binning.
366
                Defaults to config["momentum"]["ranges"].
367
            plane (int, optional): Initial value for the plane slider. Defaults to 0.
368
            width (int, optional): Initial value for the width slider. Defaults to 5.
369
            apply (bool, optional): Option to directly apply the values and select the
370
                slice. Defaults to False.
371
            **kwds: Keyword argument passed to the pre_binning function.
372
        """
373
        self._pre_binned = self.pre_binning(
1✔
374
            df_partitions=df_partitions,
375
            axes=axes,
376
            bins=bins,
377
            ranges=ranges,
378
            **kwds,
379
        )
380

381
        self.mc.load_data(data=self._pre_binned)
1✔
382
        self.mc.select_slicer(plane=plane, width=width, apply=apply)
1✔
383

384
    # 2. Generate the spline warp correction from momentum features.
385
    # Either autoselect features, or input features from view above.
386
    def define_features(
1✔
387
        self,
388
        features: np.ndarray = None,
389
        rotation_symmetry: int = 6,
390
        auto_detect: bool = False,
391
        include_center: bool = True,
392
        apply: bool = False,
393
        **kwds,
394
    ):
395
        """2. Step of the distortion correction workflow: Define feature points in
396
        momentum space. They can be either manually selected using a GUI tool, be
397
        ptovided as list of feature points, or auto-generated using a
398
        feature-detection algorithm.
399

400
        Args:
401
            features (np.ndarray, optional): np.ndarray of features. Defaults to None.
402
            rotation_symmetry (int, optional): Number of rotational symmetry axes.
403
                Defaults to 6.
404
            auto_detect (bool, optional): Whether to auto-detect the features.
405
                Defaults to False.
406
            include_center (bool, optional): Option to include a point at the center
407
                in the feature list. Defaults to True.
408
            ***kwds: Keyword arguments for MomentumCorrector.feature_extract() and
409
                MomentumCorrector.feature_select()
410
        """
411
        if auto_detect:  # automatic feature selection
×
412
            sigma = kwds.pop("sigma", self._config["momentum"]["sigma"])
×
413
            fwhm = kwds.pop("fwhm", self._config["momentum"]["fwhm"])
×
414
            sigma_radius = kwds.pop(
×
415
                "sigma_radius",
416
                self._config["momentum"]["sigma_radius"],
417
            )
418
            self.mc.feature_extract(
×
419
                sigma=sigma,
420
                fwhm=fwhm,
421
                sigma_radius=sigma_radius,
422
                rotsym=rotation_symmetry,
423
                **kwds,
424
            )
425
            features = self.mc.peaks
×
426

427
        self.mc.feature_select(
×
428
            rotsym=rotation_symmetry,
429
            include_center=include_center,
430
            features=features,
431
            apply=apply,
432
            **kwds,
433
        )
434

435
    # 3. Generate the spline warp correction from momentum features.
436
    # If no features have been selected before, use class defaults.
437
    def generate_splinewarp(
1✔
438
        self,
439
        include_center: bool = True,
440
        **kwds,
441
    ):
442
        """3. Step of the distortion correction workflow: Generate the correction
443
        function restoring the symmetry in the image using a splinewarp algortihm.
444

445
        Args:
446
            include_center (bool, optional): Option to include the position of the
447
                center point in the correction. Defaults to True.
448
            **kwds: Keyword arguments for MomentumCorrector.spline_warp_estimate().
449
        """
450
        self.mc.spline_warp_estimate(include_center=include_center, **kwds)
×
451

452
        if self.mc.slice is not None:
×
453
            print("Original slice with reference features")
×
454
            self.mc.view(annotated=True, backend="bokeh", crosshair=True)
×
455

456
            print("Corrected slice with target features")
×
457
            self.mc.view(
×
458
                image=self.mc.slice_corrected,
459
                annotated=True,
460
                points={"feats": self.mc.ptargs},
461
                backend="bokeh",
462
                crosshair=True,
463
            )
464

465
            print("Original slice with target features")
×
466
            self.mc.view(
×
467
                image=self.mc.slice,
468
                points={"feats": self.mc.ptargs},
469
                annotated=True,
470
                backend="bokeh",
471
            )
472

473
    # 3a. Save spline-warp parameters to config file.
474
    def save_splinewarp(
1✔
475
        self,
476
        filename: str = None,
477
        overwrite: bool = False,
478
    ):
479
        """Save the generated spline-warp parameters to the folder config file.
480

481
        Args:
482
            filename (str, optional): Filename of the config dictionary to save to.
483
                Defaults to "sed_config.yaml" in the current folder.
484
            overwrite (bool, optional): Option to overwrite the present dictionary.
485
                Defaults to False.
486
        """
487
        if filename is None:
×
488
            filename = "sed_config.yaml"
×
489
        points = []
×
490
        try:
×
491
            for point in self.mc.pouter_ord:
×
492
                points.append([float(i) for i in point])
×
493
            if self.mc.pcent:
×
494
                points.append([float(i) for i in self.mc.pcent])
×
495
        except AttributeError as exc:
×
496
            raise AttributeError(
×
497
                "Momentum correction parameters not found, need to generate parameters first!",
498
            ) from exc
499
        config = {
×
500
            "momentum": {
501
                "correction": {"rotation_symmetry": self.mc.rotsym, "feature_points": points},
502
            },
503
        }
504
        save_config(config, filename, overwrite)
×
505

506
    # 4. Pose corrections. Provide interactive interface for correcting
507
    # scaling, shift and rotation
508
    def pose_adjustment(
1✔
509
        self,
510
        scale: float = 1,
511
        xtrans: float = 0,
512
        ytrans: float = 0,
513
        angle: float = 0,
514
        apply: bool = False,
515
        use_correction: bool = True,
516
    ):
517
        """3. step of the distortion correction workflow: Generate an interactive panel
518
        to adjust affine transformations that are applied to the image. Applies first
519
        a scaling, next an x/y translation, and last a rotation around the center of
520
        the image.
521

522
        Args:
523
            scale (float, optional): Initial value of the scaling slider.
524
                Defaults to 1.
525
            xtrans (float, optional): Initial value of the xtrans slider.
526
                Defaults to 0.
527
            ytrans (float, optional): Initial value of the ytrans slider.
528
                Defaults to 0.
529
            angle (float, optional): Initial value of the angle slider.
530
                Defaults to 0.
531
            apply (bool, optional): Option to directly apply the provided
532
                transformations. Defaults to False.
533
            use_correction (bool, option): Whether to use the spline warp correction
534
                or not. Defaults to True.
535
        """
536
        # Generate homomorphy as default if no distortion correction has been applied
537
        if self.mc.slice_corrected is None:
×
538
            if self.mc.slice is None:
×
539
                raise ValueError(
×
540
                    "No slice for corrections and transformations loaded!",
541
                )
542
            self.mc.slice_corrected = self.mc.slice
×
543

544
        if self.mc.cdeform_field is None or self.mc.rdeform_field is None:
×
545
            # Generate default distortion correction
546
            self.mc.add_features()
×
547
            self.mc.spline_warp_estimate()
×
548

549
        if not use_correction:
×
550
            self.mc.reset_deformation()
×
551

552
        self.mc.pose_adjustment(
×
553
            scale=scale,
554
            xtrans=xtrans,
555
            ytrans=ytrans,
556
            angle=angle,
557
            apply=apply,
558
        )
559

560
    # 5. Apply the momentum correction to the dataframe
561
    def apply_momentum_correction(
1✔
562
        self,
563
        preview: bool = False,
564
    ):
565
        """Applies the distortion correction and pose adjustment (optional)
566
        to the dataframe.
567

568
        Args:
569
            rdeform_field (np.ndarray, optional): Row deformation field.
570
                Defaults to None.
571
            cdeform_field (np.ndarray, optional): Column deformation field.
572
                Defaults to None.
573
            inv_dfield (np.ndarray, optional): Inverse deformation field.
574
                Defaults to None.
575
            preview (bool): Option to preview the first elements of the data frame.
576
        """
577
        if self._dataframe is not None:
×
578
            print("Adding corrected X/Y columns to dataframe:")
×
579
            self._dataframe, metadata = self.mc.apply_corrections(
×
580
                df=self._dataframe,
581
            )
582
            # Add Metadata
583
            self._attributes.add(
×
584
                metadata,
585
                "momentum_correction",
586
                duplicate_policy="merge",
587
            )
588
            if preview:
×
589
                print(self._dataframe.head(10))
×
590
            else:
591
                print(self._dataframe)
×
592

593
    # Momentum calibration work flow
594
    # 1. Calculate momentum calibration
595
    def calibrate_momentum_axes(
1✔
596
        self,
597
        point_a: Union[np.ndarray, List[int]] = None,
598
        point_b: Union[np.ndarray, List[int]] = None,
599
        k_distance: float = None,
600
        k_coord_a: Union[np.ndarray, List[float]] = None,
601
        k_coord_b: Union[np.ndarray, List[float]] = np.array([0.0, 0.0]),
602
        equiscale: bool = True,
603
        apply=False,
604
    ):
605
        """1. step of the momentum calibration workflow. Calibrate momentum
606
        axes using either provided pixel coordinates of a high-symmetry point and its
607
        distance to the BZ center, or the k-coordinates of two points in the BZ
608
        (depending on the equiscale option). Opens an interactive panel for selecting
609
        the points.
610

611
        Args:
612
            point_a (Union[np.ndarray, List[int]]): Pixel coordinates of the first
613
                point used for momentum calibration.
614
            point_b (Union[np.ndarray, List[int]], optional): Pixel coordinates of the
615
                second point used for momentum calibration.
616
                Defaults to config["momentum"]["center_pixel"].
617
            k_distance (float, optional): Momentum distance between point a and b.
618
                Needs to be provided if no specific k-koordinates for the two points
619
                are given. Defaults to None.
620
            k_coord_a (Union[np.ndarray, List[float]], optional): Momentum coordinate
621
                of the first point used for calibration. Used if equiscale is False.
622
                Defaults to None.
623
            k_coord_b (Union[np.ndarray, List[float]], optional): Momentum coordinate
624
                of the second point used for calibration. Defaults to [0.0, 0.0].
625
            equiscale (bool, optional): Option to apply different scales to kx and ky.
626
                If True, the distance between points a and b, and the absolute
627
                position of point a are used for defining the scale. If False, the
628
                scale is calculated from the k-positions of both points a and b.
629
                Defaults to True.
630
            apply (bool, optional): Option to directly store the momentum calibration
631
                in the class. Defaults to False.
632
        """
633
        if point_b is None:
×
634
            point_b = self._config["momentum"]["center_pixel"]
×
635

636
        self.mc.select_k_range(
×
637
            point_a=point_a,
638
            point_b=point_b,
639
            k_distance=k_distance,
640
            k_coord_a=k_coord_a,
641
            k_coord_b=k_coord_b,
642
            equiscale=equiscale,
643
            apply=apply,
644
        )
645

646
    # 1a. Save momentum calibration parameters to config file.
647
    def save_momentum_calibration(
1✔
648
        self,
649
        filename: str = None,
650
        overwrite: bool = False,
651
    ):
652
        """Save the generated momentum calibration parameters to the folder config file.
653

654
        Args:
655
            filename (str, optional): Filename of the config dictionary to save to.
656
                Defaults to "sed_config.yaml" in the current folder.
657
            overwrite (bool, optional): Option to overwrite the present dictionary.
658
                Defaults to False.
659
        """
660
        if filename is None:
×
661
            filename = "sed_config.yaml"
×
662
        calibration = {}
×
663
        try:
×
664
            for key in [
×
665
                "kx_scale",
666
                "ky_scale",
667
                "x_center",
668
                "y_center",
669
                "rstart",
670
                "cstart",
671
                "rstep",
672
                "cstep",
673
            ]:
674
                calibration[key] = float(self.mc.calibration[key])
×
675
        except KeyError as exc:
×
676
            raise KeyError(
×
677
                "Momentum calibration parameters not found, need to generate parameters first!",
678
            ) from exc
679

680
        config = {"momentum": {"calibration": calibration}}
×
681
        save_config(config, filename, overwrite)
×
682

683
    # 2. Apply correction and calibration to the dataframe
684
    def apply_momentum_calibration(
1✔
685
        self,
686
        calibration: dict = None,
687
        preview: bool = False,
688
    ):
689
        """2. step of the momentum calibration work flow: Apply the momentum
690
        calibration stored in the class to the dataframe. If corrected X/Y axis exist,
691
        these are used.
692

693
        Args:
694
            calibration (dict, optional): Optional dictionary with calibration data to
695
                use. Defaults to None.
696
            preview (bool): Option to preview the first elements of the data frame.
697
        """
698
        if self._dataframe is not None:
×
699

700
            print("Adding kx/ky columns to dataframe:")
×
701
            self._dataframe, metadata = self.mc.append_k_axis(
×
702
                df=self._dataframe,
703
                calibration=calibration,
704
            )
705

706
            # Add Metadata
707
            self._attributes.add(
×
708
                metadata,
709
                "momentum_calibration",
710
                duplicate_policy="merge",
711
            )
712
            if preview:
×
713
                print(self._dataframe.head(10))
×
714
            else:
715
                print(self._dataframe)
×
716

717
    # Energy correction workflow
718
    # 1. Adjust the energy correction parameters
719
    def adjust_energy_correction(
1✔
720
        self,
721
        correction_type: str = None,
722
        amplitude: float = None,
723
        center: Tuple[float, float] = None,
724
        apply=False,
725
        **kwds,
726
    ):
727
        """1. step of the energy crrection workflow: Opens an interactive plot to
728
        adjust the parameters for the TOF/energy correction. Also pre-bins the data if
729
        they are not present yet.
730

731
        Args:
732
            correction_type (str, optional): Type of correction to apply to the TOF
733
                axis. Valid values are:
734

735
                - 'spherical'
736
                - 'Lorentzian'
737
                - 'Gaussian'
738
                - 'Lorentzian_asymmetric'
739

740
                Defaults to config["energy"]["correction_type"].
741
            amplitude (float, optional): Amplitude of the correction.
742
                Defaults to config["energy"]["correction"]["amplitude"].
743
            center (Tuple[float, float], optional): Center X/Y coordinates for the
744
                correction. Defaults to config["energy"]["correction"]["center"].
745
            apply (bool, optional): Option to directly apply the provided or default
746
                correction parameters. Defaults to False.
747
        """
748
        if self._pre_binned is None:
×
749
            print(
×
750
                "Pre-binned data not present, binning using defaults from config...",
751
            )
752
            self._pre_binned = self.pre_binning()
×
753

754
        self.ec.adjust_energy_correction(
×
755
            self._pre_binned,
756
            correction_type=correction_type,
757
            amplitude=amplitude,
758
            center=center,
759
            apply=apply,
760
            **kwds,
761
        )
762

763
    # 1a. Save energy correction parameters to config file.
764
    def save_energy_correction(
1✔
765
        self,
766
        filename: str = None,
767
        overwrite: bool = False,
768
    ):
769
        """Save the generated energy correction parameters to the folder config file.
770

771
        Args:
772
            filename (str, optional): Filename of the config dictionary to save to.
773
                Defaults to "sed_config.yaml" in the current folder.
774
            overwrite (bool, optional): Option to overwrite the present dictionary.
775
                Defaults to False.
776
        """
777
        if filename is None:
×
778
            filename = "sed_config.yaml"
×
779
        correction = {}
×
780
        try:
×
781
            for key in self.ec.correction.keys():
×
782
                if key == "correction_type":
×
783
                    correction[key] = self.ec.correction[key]
×
784
                elif key == "center":
×
785
                    correction[key] = [float(i) for i in self.ec.correction[key]]
×
786
                else:
787
                    correction[key] = float(self.ec.correction[key])
×
788
        except AttributeError as exc:
×
789
            raise AttributeError(
×
790
                "Energy correction parameters not found, need to generate parameters first!",
791
            ) from exc
792

793
        config = {"energy": {"correction": correction}}
×
794
        save_config(config, filename, overwrite)
×
795

796
    # 2. Apply energy correction to dataframe
797
    def apply_energy_correction(
1✔
798
        self,
799
        correction: dict = None,
800
        preview: bool = False,
801
        **kwds,
802
    ):
803
        """2. step of the energy correction workflow: Apply the enery correction
804
        parameters stored in the class to the dataframe.
805

806
        Args:
807
            correction (dict, optional): Dictionary containing the correction
808
                parameters. Defaults to config["energy"]["calibration"].
809
            preview (bool): Option to preview the first elements of the data frame.
810
            **kwds:
811
                Keyword args passed to ``EnergyCalibrator.apply_energy_correction``.
812
            preview (bool): Option to preview the first elements of the data frame.
813
            **kwds:
814
                Keyword args passed to ``EnergyCalibrator.apply_energy_correction``.
815
        """
816
        if self._dataframe is not None:
×
817
            print("Applying energy correction to dataframe...")
×
818
            self._dataframe, metadata = self.ec.apply_energy_correction(
×
819
                df=self._dataframe,
820
                correction=correction,
821
                **kwds,
822
            )
823

824
            # Add Metadata
825
            self._attributes.add(
×
826
                metadata,
827
                "energy_correction",
828
            )
829
            if preview:
×
830
                print(self._dataframe.head(10))
×
831
            else:
832
                print(self._dataframe)
×
833

834
    # Energy calibrator workflow
835
    # 1. Load and normalize data
836
    def load_bias_series(
1✔
837
        self,
838
        data_files: List[str],
839
        axes: List[str] = None,
840
        bins: List = None,
841
        ranges: Sequence[Tuple[float, float]] = None,
842
        biases: np.ndarray = None,
843
        bias_key: str = None,
844
        normalize: bool = None,
845
        span: int = None,
846
        order: int = None,
847
    ):
848
        """1. step of the energy calibration workflow: Load and bin data from
849
        single-event files.
850

851
        Args:
852
            data_files (List[str]): list of file paths to bin
853
            axes (List[str], optional): bin axes.
854
                Defaults to config["dataframe"]["tof_column"].
855
            bins (List, optional): number of bins.
856
                Defaults to config["energy"]["bins"].
857
            ranges (Sequence[Tuple[float, float]], optional): bin ranges.
858
                Defaults to config["energy"]["ranges"].
859
            biases (np.ndarray, optional): Bias voltages used. If missing, bias
860
                voltages are extracted from the data files.
861
            bias_key (str, optional): hdf5 path where bias values are stored.
862
                Defaults to config["energy"]["bias_key"].
863
            normalize (bool, optional): Option to normalize traces.
864
                Defaults to config["energy"]["normalize"].
865
            span (int, optional): span smoothing parameters of the LOESS method
866
                (see ``scipy.signal.savgol_filter()``).
867
                Defaults to config["energy"]["normalize_span"].
868
            order (int, optional): order smoothing parameters of the LOESS method
869
                (see ``scipy.signal.savgol_filter()``).
870
                Defaults to config["energy"]["normalize_order"].
871
        """
872
        self.ec.bin_data(
×
873
            data_files=cast(List[str], self.cpy(data_files)),
874
            axes=axes,
875
            bins=bins,
876
            ranges=ranges,
877
            biases=biases,
878
            bias_key=bias_key,
879
        )
880
        if (normalize is not None and normalize is True) or (
×
881
            normalize is None and self._config["energy"]["normalize"]
882
        ):
883
            if span is None:
×
884
                span = self._config["energy"]["normalize_span"]
×
885
            if order is None:
×
886
                order = self._config["energy"]["normalize_order"]
×
887
            self.ec.normalize(smooth=True, span=span, order=order)
×
888
        self.ec.view(
×
889
            traces=self.ec.traces_normed,
890
            xaxis=self.ec.tof,
891
            backend="bokeh",
892
        )
893

894
    # 2. extract ranges and get peak positions
895
    def find_bias_peaks(
1✔
896
        self,
897
        ranges: Union[List[Tuple], Tuple],
898
        ref_id: int = 0,
899
        infer_others: bool = True,
900
        mode: str = "replace",
901
        radius: int = None,
902
        peak_window: int = None,
903
        apply: bool = False,
904
    ):
905
        """2. step of the energy calibration workflow: Find a peak within a given range
906
        for the indicated reference trace, and tries to find the same peak for all
907
        other traces. Uses fast_dtw to align curves, which might not be too good if the
908
        shape of curves changes qualitatively. Ideally, choose a reference trace in the
909
        middle of the set, and don't choose the range too narrow around the peak.
910
        Alternatively, a list of ranges for all traces can be provided.
911

912
        Args:
913
            ranges (Union[List[Tuple], Tuple]): Tuple of TOF values indicating a range.
914
                Alternatively, a list of ranges for all traces can be given.
915
            refid (int, optional): The id of the trace the range refers to.
916
                Defaults to 0.
917
            infer_others (bool, optional): Whether to determine the range for the other
918
                traces. Defaults to True.
919
            mode (str, optional): Whether to "add" or "replace" existing ranges.
920
                Defaults to "replace".
921
            radius (int, optional): Radius parameter for fast_dtw.
922
                Defaults to config["energy"]["fastdtw_radius"].
923
            peak_window (int, optional): Peak_window parameter for the peak detection
924
                algorthm. amount of points that have to have to behave monotoneously
925
                around a peak. Defaults to config["energy"]["peak_window"].
926
            apply (bool, optional): Option to directly apply the provided parameters.
927
                Defaults to False.
928
        """
929
        if radius is None:
×
930
            radius = self._config["energy"]["fastdtw_radius"]
×
931
        if peak_window is None:
×
932
            peak_window = self._config["energy"]["peak_window"]
×
933
        if not infer_others:
×
934
            self.ec.add_ranges(
×
935
                ranges=ranges,
936
                ref_id=ref_id,
937
                infer_others=infer_others,
938
                mode=mode,
939
                radius=radius,
940
            )
941
            print(self.ec.featranges)
×
942
            try:
×
943
                self.ec.feature_extract(peak_window=peak_window)
×
944
                self.ec.view(
×
945
                    traces=self.ec.traces_normed,
946
                    segs=self.ec.featranges,
947
                    xaxis=self.ec.tof,
948
                    peaks=self.ec.peaks,
949
                    backend="bokeh",
950
                )
951
            except IndexError:
×
952
                print("Could not determine all peaks!")
×
953
                raise
×
954
        else:
955
            # New adjustment tool
956
            assert isinstance(ranges, tuple)
×
957
            self.ec.adjust_ranges(
×
958
                ranges=ranges,
959
                ref_id=ref_id,
960
                traces=self.ec.traces_normed,
961
                infer_others=infer_others,
962
                radius=radius,
963
                peak_window=peak_window,
964
                apply=apply,
965
            )
966

967
    # 3. Fit the energy calibration relation
968
    def calibrate_energy_axis(
1✔
969
        self,
970
        ref_id: int,
971
        ref_energy: float,
972
        method: str = None,
973
        energy_scale: str = None,
974
        **kwds,
975
    ):
976
        """3. Step of the energy calibration workflow: Calculate the calibration
977
        function for the energy axis, and apply it to the dataframe. Two
978
        approximations are implemented, a (normally 3rd order) polynomial
979
        approximation, and a d^2/(t-t0)^2 relation.
980

981
        Args:
982
            ref_id (int): id of the trace at the bias where the reference energy is
983
                given.
984
            ref_energy (float): Absolute energy of the detected feature at the bias
985
                of ref_id
986
            method (str, optional): Method for determining the energy calibration.
987

988
                - **'lmfit'**: Energy calibration using lmfit and 1/t^2 form.
989
                - **'lstsq'**, **'lsqr'**: Energy calibration using polynomial form.
990

991
                Defaults to config["energy"]["calibration_method"]
992
            energy_scale (str, optional): Direction of increasing energy scale.
993

994
                - **'kinetic'**: increasing energy with decreasing TOF.
995
                - **'binding'**: increasing energy with increasing TOF.
996

997
                Defaults to config["energy"]["energy_scale"]
998
        """
999
        if method is None:
×
1000
            method = self._config["energy"]["calibration_method"]
×
1001

1002
        if energy_scale is None:
×
1003
            energy_scale = self._config["energy"]["energy_scale"]
×
1004

1005
        self.ec.calibrate(
×
1006
            ref_id=ref_id,
1007
            ref_energy=ref_energy,
1008
            method=method,
1009
            energy_scale=energy_scale,
1010
            **kwds,
1011
        )
1012
        print("Quality of Calibration:")
×
1013
        self.ec.view(
×
1014
            traces=self.ec.traces_normed,
1015
            xaxis=self.ec.calibration["axis"],
1016
            align=True,
1017
            energy_scale=energy_scale,
1018
            backend="bokeh",
1019
        )
1020
        print("E/TOF relationship:")
×
1021
        self.ec.view(
×
1022
            traces=self.ec.calibration["axis"][None, :],
1023
            xaxis=self.ec.tof,
1024
            backend="matplotlib",
1025
            show_legend=False,
1026
        )
1027
        if energy_scale == "kinetic":
×
1028
            plt.scatter(
×
1029
                self.ec.peaks[:, 0],
1030
                -(self.ec.biases - self.ec.biases[ref_id]) + ref_energy,
1031
                s=50,
1032
                c="k",
1033
            )
1034
        elif energy_scale == "binding":
×
1035
            plt.scatter(
×
1036
                self.ec.peaks[:, 0],
1037
                self.ec.biases - self.ec.biases[ref_id] + ref_energy,
1038
                s=50,
1039
                c="k",
1040
            )
1041
        else:
1042
            raise ValueError(
×
1043
                'energy_scale needs to be either "binding" or "kinetic"',
1044
                f", got {energy_scale}.",
1045
            )
1046
        plt.xlabel("Time-of-flight", fontsize=15)
×
1047
        plt.ylabel("Energy (eV)", fontsize=15)
×
1048
        plt.show()
×
1049

1050
    # 3a. Save energy calibration parameters to config file.
1051
    def save_energy_calibration(
1✔
1052
        self,
1053
        filename: str = None,
1054
        overwrite: bool = False,
1055
    ):
1056
        """Save the generated energy calibration parameters to the folder config file.
1057

1058
        Args:
1059
            filename (str, optional): Filename of the config dictionary to save to.
1060
                Defaults to "sed_config.yaml" in the current folder.
1061
            overwrite (bool, optional): Option to overwrite the present dictionary.
1062
                Defaults to False.
1063
        """
1064
        if filename is None:
×
1065
            filename = "sed_config.yaml"
×
1066
        calibration = {}
×
1067
        try:
×
1068
            for (key, value) in self.ec.calibration.items():
×
1069
                if key in ["axis", "refid"]:
×
1070
                    continue
×
1071
                if key == "energy_scale":
×
1072
                    calibration[key] = value
×
1073
                else:
1074
                    calibration[key] = float(value)
×
1075
        except AttributeError as exc:
×
1076
            raise AttributeError(
×
1077
                "Energy calibration parameters not found, need to generate parameters first!",
1078
            ) from exc
1079

1080
        config = {"energy": {"calibration": calibration}}
×
1081
        save_config(config, filename, overwrite)
×
1082

1083
    # 4. Apply energy calibration to the dataframe
1084
    def append_energy_axis(
1✔
1085
        self,
1086
        calibration: dict = None,
1087
        preview: bool = False,
1088
        **kwds,
1089
    ):
1090
        """4. step of the energy calibration workflow: Apply the calibration function
1091
        to to the dataframe. Two approximations are implemented, a (normally 3rd order)
1092
        polynomial approximation, and a d^2/(t-t0)^2 relation. a calibration dictionary
1093
        can be provided.
1094

1095
        Args:
1096
            calibration (dict, optional): Calibration dict containing calibration
1097
                parameters. Overrides calibration from class or config.
1098
                Defaults to None.
1099
            preview (bool): Option to preview the first elements of the data frame.
1100
            **kwds:
1101
                Keyword args passed to ``EnergyCalibrator.append_energy_axis``.
1102
        """
1103
        if self._dataframe is not None:
×
1104
            print("Adding energy column to dataframe:")
×
1105
            self._dataframe, metadata = self.ec.append_energy_axis(
×
1106
                df=self._dataframe,
1107
                calibration=calibration,
1108
                **kwds,
1109
            )
1110

1111
            # Add Metadata
1112
            self._attributes.add(
×
1113
                metadata,
1114
                "energy_calibration",
1115
                duplicate_policy="merge",
1116
            )
1117
            if preview:
×
1118
                print(self._dataframe.head(10))
×
1119
            else:
1120
                print(self._dataframe)
×
1121

1122
    # Delay calibration function
1123
    def calibrate_delay_axis(
1✔
1124
        self,
1125
        delay_range: Tuple[float, float] = None,
1126
        datafile: str = None,
1127
        preview: bool = False,
1128
        **kwds,
1129
    ):
1130
        """Append delay column to dataframe. Either provide delay ranges, or read
1131
        them from a file.
1132

1133
        Args:
1134
            delay_range (Tuple[float, float], optional): The scanned delay range in
1135
                picoseconds. Defaults to None.
1136
            datafile (str, optional): The file from which to read the delay ranges.
1137
                Defaults to None.
1138
            preview (bool): Option to preview the first elements of the data frame.
1139
            **kwds: Keyword args passed to ``DelayCalibrator.append_delay_axis``.
1140
        """
1141
        if self._dataframe is not None:
×
1142
            print("Adding delay column to dataframe:")
×
1143

1144
            if delay_range is not None:
×
1145
                self._dataframe, metadata = self.dc.append_delay_axis(
×
1146
                    self._dataframe,
1147
                    delay_range=delay_range,
1148
                    **kwds,
1149
                )
1150
            else:
1151
                if datafile is None:
×
1152
                    try:
×
1153
                        datafile = self._files[0]
×
1154
                    except IndexError:
×
1155
                        print(
×
1156
                            "No datafile available, specify eihter",
1157
                            " 'datafile' or 'delay_range'",
1158
                        )
1159
                        raise
×
1160

1161
                self._dataframe, metadata = self.dc.append_delay_axis(
×
1162
                    self._dataframe,
1163
                    datafile=datafile,
1164
                    **kwds,
1165
                )
1166

1167
            # Add Metadata
1168
            self._attributes.add(
×
1169
                metadata,
1170
                "delay_calibration",
1171
                duplicate_policy="merge",
1172
            )
1173
            if preview:
×
1174
                print(self._dataframe.head(10))
×
1175
            else:
1176
                print(self._dataframe)
×
1177

1178
    def add_jitter(self, cols: Sequence[str] = None):
1✔
1179
        """Add jitter to the selected dataframe columns.
1180

1181
        Args:
1182
            cols (Sequence[str], optional): The colums onto which to apply jitter.
1183
                Defaults to config["dataframe"]["jitter_cols"].
1184
        """
1185
        if cols is None:
×
1186
            cols = self._config["dataframe"].get(
×
1187
                "jitter_cols",
1188
                self._dataframe.columns,
1189
            )  # jitter all columns
1190

1191
        self._dataframe = self._dataframe.map_partitions(
×
1192
            apply_jitter,
1193
            cols=cols,
1194
            cols_jittered=cols,
1195
        )
1196
        metadata = []
×
1197
        for col in cols:
×
1198
            metadata.append(col)
×
1199
        self._attributes.add(metadata, "jittering", duplicate_policy="append")
×
1200

1201
    def pre_binning(
1✔
1202
        self,
1203
        df_partitions: int = 100,
1204
        axes: List[str] = None,
1205
        bins: List[int] = None,
1206
        ranges: Sequence[Tuple[float, float]] = None,
1207
        **kwds,
1208
    ) -> xr.DataArray:
1209
        """Function to do an initial binning of the dataframe loaded to the class.
1210

1211
        Args:
1212
            df_partitions (int, optional): Number of dataframe partitions to use for
1213
                the initial binning. Defaults to 100.
1214
            axes (List[str], optional): Axes to bin.
1215
                Defaults to config["momentum"]["axes"].
1216
            bins (List[int], optional): Bin numbers to use for binning.
1217
                Defaults to config["momentum"]["bins"].
1218
            ranges (List[Tuple], optional): Ranges to use for binning.
1219
                Defaults to config["momentum"]["ranges"].
1220
            **kwds: Keyword argument passed to ``compute``.
1221

1222
        Returns:
1223
            xr.DataArray: pre-binned data-array.
1224
        """
1225
        if axes is None:
1✔
1226
            axes = self._config["momentum"]["axes"]
1✔
1227
        for loc, axis in enumerate(axes):
1✔
1228
            if axis.startswith("@"):
1✔
1229
                axes[loc] = self._config["dataframe"].get(axis.strip("@"))
1✔
1230

1231
        if bins is None:
1✔
1232
            bins = self._config["momentum"]["bins"]
1✔
1233
        if ranges is None:
1✔
1234
            ranges_ = list(self._config["momentum"]["ranges"])
1✔
1235
            ranges_[2] = np.asarray(ranges_[2]) / 2 ** (
1✔
1236
                self._config["dataframe"]["tof_binning"] - 1
1237
            )
1238
            ranges = [cast(Tuple[float, float], tuple(v)) for v in ranges_]
1✔
1239

1240
        assert self._dataframe is not None, "dataframe needs to be loaded first!"
1✔
1241

1242
        return self.compute(
1✔
1243
            bins=bins,
1244
            axes=axes,
1245
            ranges=ranges,
1246
            df_partitions=df_partitions,
1247
            **kwds,
1248
        )
1249

1250
    def compute(
1✔
1251
        self,
1252
        bins: Union[
1253
            int,
1254
            dict,
1255
            tuple,
1256
            List[int],
1257
            List[np.ndarray],
1258
            List[tuple],
1259
        ] = 100,
1260
        axes: Union[str, Sequence[str]] = None,
1261
        ranges: Sequence[Tuple[float, float]] = None,
1262
        **kwds,
1263
    ) -> xr.DataArray:
1264
        """Compute the histogram along the given dimensions.
1265

1266
        Args:
1267
            bins (int, dict, tuple, List[int], List[np.ndarray], List[tuple], optional):
1268
                Definition of the bins. Can be any of the following cases:
1269

1270
                - an integer describing the number of bins in on all dimensions
1271
                - a tuple of 3 numbers describing start, end and step of the binning
1272
                  range
1273
                - a np.arrays defining the binning edges
1274
                - a list (NOT a tuple) of any of the above (int, tuple or np.ndarray)
1275
                - a dictionary made of the axes as keys and any of the above as values.
1276

1277
                This takes priority over the axes and range arguments. Defaults to 100.
1278
            axes (Union[str, Sequence[str]], optional): The names of the axes (columns)
1279
                on which to calculate the histogram. The order will be the order of the
1280
                dimensions in the resulting array. Defaults to None.
1281
            ranges (Sequence[Tuple[float, float]], optional): list of tuples containing
1282
                the start and end point of the binning range. Defaults to None.
1283
            **kwds: Keyword arguments:
1284

1285
                - **hist_mode**: Histogram calculation method. "numpy" or "numba". See
1286
                  ``bin_dataframe`` for details. Defaults to
1287
                  config["binning"]["hist_mode"].
1288
                - **mode**: Defines how the results from each partition are combined.
1289
                  "fast", "lean" or "legacy". See ``bin_dataframe`` for details.
1290
                  Defaults to config["binning"]["mode"].
1291
                - **pbar**: Option to show the tqdm progress bar. Defaults to
1292
                  config["binning"]["pbar"].
1293
                - **n_cores**: Number of CPU cores to use for parallelization.
1294
                  Defaults to config["binning"]["num_cores"] or N_CPU-1.
1295
                - **threads_per_worker**: Limit the number of threads that
1296
                  multiprocessing can spawn per binning thread. Defaults to
1297
                  config["binning"]["threads_per_worker"].
1298
                - **threadpool_api**: The API to use for multiprocessing. "blas",
1299
                  "openmp" or None. See ``threadpool_limit`` for details. Defaults to
1300
                  config["binning"]["threadpool_API"].
1301
                - **df_partitions**: A list of dataframe partitions. Defaults to all
1302
                  partitions.
1303

1304
                Additional kwds are passed to ``bin_dataframe``.
1305

1306
        Raises:
1307
            AssertError: Rises when no dataframe has been loaded.
1308

1309
        Returns:
1310
            xr.DataArray: The result of the n-dimensional binning represented in an
1311
            xarray object, combining the data with the axes.
1312
        """
1313
        assert self._dataframe is not None, "dataframe needs to be loaded first!"
1✔
1314

1315
        hist_mode = kwds.pop("hist_mode", self._config["binning"]["hist_mode"])
1✔
1316
        mode = kwds.pop("mode", self._config["binning"]["mode"])
1✔
1317
        pbar = kwds.pop("pbar", self._config["binning"]["pbar"])
1✔
1318
        num_cores = kwds.pop("num_cores", self._config["binning"]["num_cores"])
1✔
1319
        threads_per_worker = kwds.pop(
1✔
1320
            "threads_per_worker",
1321
            self._config["binning"]["threads_per_worker"],
1322
        )
1323
        threadpool_api = kwds.pop(
1✔
1324
            "threadpool_API",
1325
            self._config["binning"]["threadpool_API"],
1326
        )
1327
        df_partitions = kwds.pop("df_partitions", None)
1✔
1328
        if df_partitions is not None:
1✔
1329
            dataframe = self._dataframe.partitions[
1✔
1330
                0 : min(df_partitions, self._dataframe.npartitions)
1331
            ]
1332
        else:
1333
            dataframe = self._dataframe
×
1334

1335
        self._binned = bin_dataframe(
1✔
1336
            df=dataframe,
1337
            bins=bins,
1338
            axes=axes,
1339
            ranges=ranges,
1340
            hist_mode=hist_mode,
1341
            mode=mode,
1342
            pbar=pbar,
1343
            n_cores=num_cores,
1344
            threads_per_worker=threads_per_worker,
1345
            threadpool_api=threadpool_api,
1346
            **kwds,
1347
        )
1348

1349
        for dim in self._binned.dims:
1✔
1350
            try:
1✔
1351
                self._binned[dim].attrs["unit"] = self._config["dataframe"]["units"][dim]
1✔
1352
            except KeyError:
×
1353
                pass
×
1354

1355
        self._binned.attrs["units"] = "counts"
1✔
1356
        self._binned.attrs["long_name"] = "photoelectron counts"
1✔
1357
        self._binned.attrs["metadata"] = self._attributes.metadata
1✔
1358

1359
        return self._binned
1✔
1360

1361
    def view_event_histogram(
1✔
1362
        self,
1363
        dfpid: int,
1364
        ncol: int = 2,
1365
        bins: Sequence[int] = None,
1366
        axes: Sequence[str] = None,
1367
        ranges: Sequence[Tuple[float, float]] = None,
1368
        backend: str = "bokeh",
1369
        legend: bool = True,
1370
        histkwds: dict = None,
1371
        legkwds: dict = None,
1372
        **kwds,
1373
    ):
1374
        """Plot individual histograms of specified dimensions (axes) from a substituent
1375
        dataframe partition.
1376

1377
        Args:
1378
            dfpid (int): Number of the data frame partition to look at.
1379
            ncol (int, optional): Number of columns in the plot grid. Defaults to 2.
1380
            bins (Sequence[int], optional): Number of bins to use for the speicified
1381
                axes. Defaults to config["histogram"]["bins"].
1382
            axes (Sequence[str], optional): Names of the axes to display.
1383
                Defaults to config["histogram"]["axes"].
1384
            ranges (Sequence[Tuple[float, float]], optional): Value ranges of all
1385
                specified axes. Defaults toconfig["histogram"]["ranges"].
1386
            backend (str, optional): Backend of the plotting library
1387
                ('matplotlib' or 'bokeh'). Defaults to "bokeh".
1388
            legend (bool, optional): Option to include a legend in the histogram plots.
1389
                Defaults to True.
1390
            histkwds (dict, optional): Keyword arguments for histograms
1391
                (see ``matplotlib.pyplot.hist()``). Defaults to {}.
1392
            legkwds (dict, optional): Keyword arguments for legend
1393
                (see ``matplotlib.pyplot.legend()``). Defaults to {}.
1394
            **kwds: Extra keyword arguments passed to
1395
                ``sed.diagnostics.grid_histogram()``.
1396

1397
        Raises:
1398
            TypeError: Raises when the input values are not of the correct type.
1399
        """
1400
        if bins is None:
×
1401
            bins = self._config["histogram"]["bins"]
×
1402
        if axes is None:
×
1403
            axes = self._config["histogram"]["axes"]
×
1404
        axes = list(axes)
×
1405
        for loc, axis in enumerate(axes):
×
1406
            if axis.startswith("@"):
×
1407
                axes[loc] = self._config["dataframe"].get(axis.strip("@"))
×
1408
        if ranges is None:
×
1409
            ranges = list(self._config["histogram"]["ranges"])
×
1410
            ranges[2] = np.asarray(ranges[2]) / 2 ** (self._config["dataframe"]["tof_binning"] - 1)
×
1411
            ranges[3] = np.asarray(ranges[3]) / 2 ** (self._config["dataframe"]["adc_binning"] - 1)
×
1412

1413
        input_types = map(type, [axes, bins, ranges])
×
1414
        allowed_types = [list, tuple]
×
1415

1416
        df = self._dataframe
×
1417

1418
        if not set(input_types).issubset(allowed_types):
×
1419
            raise TypeError(
×
1420
                "Inputs of axes, bins, ranges need to be list or tuple!",
1421
            )
1422

1423
        # Read out the values for the specified groups
1424
        group_dict_dd = {}
×
1425
        dfpart = df.get_partition(dfpid)
×
1426
        cols = dfpart.columns
×
1427
        for ax in axes:
×
1428
            group_dict_dd[ax] = dfpart.values[:, cols.get_loc(ax)]
×
1429
        group_dict = ddf.compute(group_dict_dd)[0]
×
1430

1431
        # Plot multiple histograms in a grid
1432
        grid_histogram(
×
1433
            group_dict,
1434
            ncol=ncol,
1435
            rvs=axes,
1436
            rvbins=bins,
1437
            rvranges=ranges,
1438
            backend=backend,
1439
            legend=legend,
1440
            histkwds=histkwds,
1441
            legkwds=legkwds,
1442
            **kwds,
1443
        )
1444

1445
    def save(
1✔
1446
        self,
1447
        faddr: str,
1448
        **kwds,
1449
    ):
1450
        """Saves the binned data to the provided path and filename.
1451

1452
        Args:
1453
            faddr (str): Path and name of the file to write. Its extension determines
1454
                the file type to write. Valid file types are:
1455

1456
                - "*.tiff", "*.tif": Saves a TIFF stack.
1457
                - "*.h5", "*.hdf5": Saves an HDF5 file.
1458
                - "*.nxs", "*.nexus": Saves a NeXus file.
1459

1460
            **kwds: Keyword argumens, which are passed to the writer functions:
1461
                For TIFF writing:
1462

1463
                - **alias_dict**: Dictionary of dimension aliases to use.
1464

1465
                For HDF5 writing:
1466

1467
                - **mode**: hdf5 read/write mode. Defaults to "w".
1468

1469
                For NeXus:
1470

1471
                - **reader**: Name of the nexustools reader to use.
1472
                  Defaults to config["nexus"]["reader"]
1473
                - **definiton**: NeXus application definition to use for saving.
1474
                  Must be supported by the used ``reader``. Defaults to
1475
                  config["nexus"]["definition"]
1476
                - **input_files**: A list of input files to pass to the reader.
1477
                  Defaults to config["nexus"]["input_files"]
1478
        """
1479
        if self._binned is None:
×
1480
            raise NameError("Need to bin data first!")
×
1481

1482
        extension = pathlib.Path(faddr).suffix
×
1483

1484
        if extension in (".tif", ".tiff"):
×
1485
            to_tiff(
×
1486
                data=self._binned,
1487
                faddr=faddr,
1488
                **kwds,
1489
            )
1490
        elif extension in (".h5", ".hdf5"):
×
1491
            to_h5(
×
1492
                data=self._binned,
1493
                faddr=faddr,
1494
                **kwds,
1495
            )
1496
        elif extension in (".nxs", ".nexus"):
×
1497
            try:
×
1498
                reader = kwds.pop("reader", self._config["nexus"]["reader"])
×
1499
                definition = kwds.pop(
×
1500
                    "definition",
1501
                    self._config["nexus"]["definition"],
1502
                )
1503
                input_files = kwds.pop(
×
1504
                    "input_files",
1505
                    self._config["nexus"]["input_files"],
1506
                )
1507
            except KeyError as exc:
×
1508
                raise ValueError(
×
1509
                    "The nexus reader, definition and input files need to be provide!",
1510
                ) from exc
1511

1512
            if isinstance(input_files, str):
×
1513
                input_files = [input_files]
×
1514

1515
            to_nexus(
×
1516
                data=self._binned,
1517
                faddr=faddr,
1518
                reader=reader,
1519
                definition=definition,
1520
                input_files=input_files,
1521
                **kwds,
1522
            )
1523

1524
        else:
1525
            raise NotImplementedError(
×
1526
                f"Unrecognized file format: {extension}.",
1527
            )
1528

1529
    def add_dimension(self, name: str, axis_range: Tuple):
1✔
1530
        """Add a dimension axis.
1531

1532
        Args:
1533
            name (str): name of the axis
1534
            axis_range (Tuple): range for the axis.
1535

1536
        Raises:
1537
            ValueError: Raised if an axis with that name already exists.
1538
        """
1539
        if name in self._coordinates:
×
1540
            raise ValueError(f"Axis {name} already exists")
×
1541

1542
        self.axis[name] = self.make_axis(axis_range)
×
1543

1544
    def make_axis(self, axis_range: Tuple) -> np.ndarray:
1✔
1545
        """Function to make an axis.
1546

1547
        Args:
1548
            axis_range (Tuple): range for the new axis.
1549
        """
1550

1551
        # TODO: What shall this function do?
1552
        return np.arange(*axis_range)
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc