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

OpenCOMPES / sed / 5843074189

pending completion
5843074189

Pull #131

github

web-flow
Merge 7a312a3a6 into 2e065638d
Pull Request #131: Default config and documentation

51 of 51 new or added lines in 4 files covered. (100.0%)

2962 of 4033 relevant lines covered (73.44%)

2.2 hits per line

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

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

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

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

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

35
N_CPU = psutil.cpu_count()
3✔
36

37

38
class SedProcessor:
3✔
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__(
3✔
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)
3✔
88
        num_cores = self._config.get("binning", {}).get("num_cores", N_CPU - 1)
3✔
89
        if num_cores >= N_CPU:
3✔
90
            num_cores = N_CPU - 1
3✔
91
        self._config["binning"]["num_cores"] = num_cores
3✔
92

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

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

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

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

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

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

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

123
        self.use_copy_tool = self._config.get("core", {}).get(
3✔
124
            "use_copy_tool",
125
            False,
126
        )
127
        if self.use_copy_tool:
3✔
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:
3✔
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):
3✔
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:
3✔
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
3✔
171
    def config(self) -> Dict[Any, Any]:
3✔
172
        """Getter attribute for the config dictionary
173

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

179
    @config.setter
3✔
180
    def config(self, config: Union[dict, str]):
3✔
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
3✔
194
    def dimensions(self) -> list:
3✔
195
        """Getter attribute for the dimensions.
196

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

202
    @dimensions.setter
3✔
203
    def dimensions(self, dims: list):
3✔
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
3✔
213
    def coordinates(self) -> dict:
3✔
214
        """Getter attribute for the coordinates dict.
215

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

221
    @coordinates.setter
3✔
222
    def coordinates(self, coords: dict):
3✔
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]]:
3✔
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:
3✔
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):
3✔
255
            return path
3✔
256

257
        return path
×
258

259
    def load(
3✔
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:
3✔
287
            metadata = {}
3✔
288
        if dataframe is not None:
3✔
289
            self._dataframe = dataframe
×
290
        elif runs is not None:
3✔
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:
3✔
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:
3✔
319
            dataframe, metadata = self.loader.read_dataframe(
3✔
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
3✔
332
        self._files = self.loader.files
3✔
333

334
        for key in metadata:
3✔
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(
3✔
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(
3✔
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)
3✔
382
        self.mc.select_slicer(plane=plane, width=width, apply=apply)
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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(
3✔
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
    ):
904
        """2. step of the energy calibration workflow: Find a peak within a given range
905
        for the indicated reference trace, and tries to find the same peak for all
906
        other traces. Uses fast_dtw to align curves, which might not be too good if the
907
        shape of curves changes qualitatively. Ideally, choose a reference trace in the
908
        middle of the set, and don't choose the range too narrow around the peak.
909
        Alternatively, a list of ranges for all traces can be provided.
910

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

955
    # 3. Fit the energy calibration relation
956
    def calibrate_energy_axis(
3✔
957
        self,
958
        ref_id: int,
959
        ref_energy: float,
960
        method: str = None,
961
        energy_scale: str = None,
962
        **kwds,
963
    ):
964
        """3. Step of the energy calibration workflow: Calculate the calibration
965
        function for the energy axis, and apply it to the dataframe. Two
966
        approximations are implemented, a (normally 3rd order) polynomial
967
        approximation, and a d^2/(t-t0)^2 relation.
968

969
        Args:
970
            ref_id (int): id of the trace at the bias where the reference energy is
971
                given.
972
            ref_energy (float): Absolute energy of the detected feature at the bias
973
                of ref_id
974
            method (str, optional): Method for determining the energy calibration.
975

976
                - **'lmfit'**: Energy calibration using lmfit and 1/t^2 form.
977
                - **'lstsq'**, **'lsqr'**: Energy calibration using polynomial form.
978

979
                Defaults to config["energy"]["calibration_method"]
980
            energy_scale (str, optional): Direction of increasing energy scale.
981

982
                - **'kinetic'**: increasing energy with decreasing TOF.
983
                - **'binding'**: increasing energy with increasing TOF.
984

985
                Defaults to config["energy"]["energy_scale"]
986
        """
987
        if method is None:
×
988
            method = self._config["energy"]["calibration_method"]
×
989

990
        if energy_scale is None:
×
991
            energy_scale = self._config["energy"]["energy_scale"]
×
992

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

1038
    # 3a. Save energy calibration parameters to config file.
1039
    def save_energy_calibration(
3✔
1040
        self,
1041
        filename: str = None,
1042
        overwrite: bool = False,
1043
    ):
1044
        """Save the generated energy calibration parameters to the folder config file.
1045

1046
        Args:
1047
            filename (str, optional): Filename of the config dictionary to save to.
1048
                Defaults to "sed_config.yaml" in the current folder.
1049
            overwrite (bool, optional): Option to overwrite the present dictionary.
1050
                Defaults to False.
1051
        """
1052
        if filename is None:
×
1053
            filename = "sed_config.yaml"
×
1054
        calibration = {}
×
1055
        try:
×
1056
            for (key, value) in self.ec.calibration.items():
×
1057
                if key in ["axis", "refid"]:
×
1058
                    continue
×
1059
                if key == "energy_scale":
×
1060
                    calibration[key] = value
×
1061
                else:
1062
                    calibration[key] = float(value)
×
1063
        except AttributeError as exc:
×
1064
            raise AttributeError(
×
1065
                "Energy calibration parameters not found, need to generate parameters first!",
1066
            ) from exc
1067

1068
        config = {"energy": {"calibration": calibration}}
×
1069
        save_config(config, filename, overwrite)
×
1070

1071
    # 4. Apply energy calibration to the dataframe
1072
    def append_energy_axis(
3✔
1073
        self,
1074
        calibration: dict = None,
1075
        preview: bool = False,
1076
        **kwds,
1077
    ):
1078
        """4. step of the energy calibration workflow: Apply the calibration function
1079
        to to the dataframe. Two approximations are implemented, a (normally 3rd order)
1080
        polynomial approximation, and a d^2/(t-t0)^2 relation. a calibration dictionary
1081
        can be provided.
1082

1083
        Args:
1084
            calibration (dict, optional): Calibration dict containing calibration
1085
                parameters. Overrides calibration from class or config.
1086
                Defaults to None.
1087
            preview (bool): Option to preview the first elements of the data frame.
1088
            **kwds:
1089
                Keyword args passed to ``EnergyCalibrator.append_energy_axis``.
1090
        """
1091
        if self._dataframe is not None:
×
1092
            print("Adding energy column to dataframe:")
×
1093
            self._dataframe, metadata = self.ec.append_energy_axis(
×
1094
                df=self._dataframe,
1095
                calibration=calibration,
1096
                **kwds,
1097
            )
1098

1099
            # Add Metadata
1100
            self._attributes.add(
×
1101
                metadata,
1102
                "energy_calibration",
1103
                duplicate_policy="merge",
1104
            )
1105
            if preview:
×
1106
                print(self._dataframe.head(10))
×
1107
            else:
1108
                print(self._dataframe)
×
1109

1110
    # Delay calibration function
1111
    def calibrate_delay_axis(
3✔
1112
        self,
1113
        delay_range: Tuple[float, float] = None,
1114
        datafile: str = None,
1115
        preview: bool = False,
1116
        **kwds,
1117
    ):
1118
        """Append delay column to dataframe. Either provide delay ranges, or read
1119
        them from a file.
1120

1121
        Args:
1122
            delay_range (Tuple[float, float], optional): The scanned delay range in
1123
                picoseconds. Defaults to None.
1124
            datafile (str, optional): The file from which to read the delay ranges.
1125
                Defaults to None.
1126
            preview (bool): Option to preview the first elements of the data frame.
1127
            **kwds: Keyword args passed to ``DelayCalibrator.append_delay_axis``.
1128
        """
1129
        if self._dataframe is not None:
×
1130
            print("Adding delay column to dataframe:")
×
1131

1132
            if delay_range is not None:
×
1133
                self._dataframe, metadata = self.dc.append_delay_axis(
×
1134
                    self._dataframe,
1135
                    delay_range=delay_range,
1136
                    **kwds,
1137
                )
1138
            else:
1139
                if datafile is None:
×
1140
                    try:
×
1141
                        datafile = self._files[0]
×
1142
                    except IndexError:
×
1143
                        print(
×
1144
                            "No datafile available, specify eihter",
1145
                            " 'datafile' or 'delay_range'",
1146
                        )
1147
                        raise
×
1148

1149
                self._dataframe, metadata = self.dc.append_delay_axis(
×
1150
                    self._dataframe,
1151
                    datafile=datafile,
1152
                    **kwds,
1153
                )
1154

1155
            # Add Metadata
1156
            self._attributes.add(
×
1157
                metadata,
1158
                "delay_calibration",
1159
                duplicate_policy="merge",
1160
            )
1161
            if preview:
×
1162
                print(self._dataframe.head(10))
×
1163
            else:
1164
                print(self._dataframe)
×
1165

1166
    def add_jitter(self, cols: Sequence[str] = None):
3✔
1167
        """Add jitter to the selected dataframe columns.
1168

1169
        Args:
1170
            cols (Sequence[str], optional): The colums onto which to apply jitter.
1171
                Defaults to config["dataframe"]["jitter_cols"].
1172
        """
1173
        if cols is None:
×
1174
            cols = self._config["dataframe"].get(
×
1175
                "jitter_cols",
1176
                self._dataframe.columns,
1177
            )  # jitter all columns
1178

1179
        self._dataframe = self._dataframe.map_partitions(
×
1180
            apply_jitter,
1181
            cols=cols,
1182
            cols_jittered=cols,
1183
        )
1184
        metadata = []
×
1185
        for col in cols:
×
1186
            metadata.append(col)
×
1187
        self._attributes.add(metadata, "jittering", duplicate_policy="append")
×
1188

1189
    def pre_binning(
3✔
1190
        self,
1191
        df_partitions: int = 100,
1192
        axes: List[str] = None,
1193
        bins: List[int] = None,
1194
        ranges: Sequence[Tuple[float, float]] = None,
1195
        **kwds,
1196
    ) -> xr.DataArray:
1197
        """Function to do an initial binning of the dataframe loaded to the class.
1198

1199
        Args:
1200
            df_partitions (int, optional): Number of dataframe partitions to use for
1201
                the initial binning. Defaults to 100.
1202
            axes (List[str], optional): Axes to bin.
1203
                Defaults to config["momentum"]["axes"].
1204
            bins (List[int], optional): Bin numbers to use for binning.
1205
                Defaults to config["momentum"]["bins"].
1206
            ranges (List[Tuple], optional): Ranges to use for binning.
1207
                Defaults to config["momentum"]["ranges"].
1208
            **kwds: Keyword argument passed to ``compute``.
1209

1210
        Returns:
1211
            xr.DataArray: pre-binned data-array.
1212
        """
1213
        if axes is None:
3✔
1214
            axes = self._config["momentum"]["axes"]
3✔
1215
        for loc, axis in enumerate(axes):
3✔
1216
            if axis.startswith("@"):
3✔
1217
                axes[loc] = self._config["dataframe"].get(axis.strip("@"))
3✔
1218

1219
        if bins is None:
3✔
1220
            bins = self._config["momentum"]["bins"]
3✔
1221
        if ranges is None:
3✔
1222
            ranges_ = list(self._config["momentum"]["ranges"])
3✔
1223
            ranges_[2] = np.asarray(ranges_[2]) / 2 ** (
3✔
1224
                self._config["dataframe"]["tof_binning"] - 1
1225
            )
1226
            ranges = [cast(Tuple[float, float], tuple(v)) for v in ranges_]
3✔
1227

1228
        assert self._dataframe is not None, "dataframe needs to be loaded first!"
3✔
1229

1230
        return self.compute(
3✔
1231
            bins=bins,
1232
            axes=axes,
1233
            ranges=ranges,
1234
            df_partitions=df_partitions,
1235
            **kwds,
1236
        )
1237

1238
    def compute(
3✔
1239
        self,
1240
        bins: Union[
1241
            int,
1242
            dict,
1243
            tuple,
1244
            List[int],
1245
            List[np.ndarray],
1246
            List[tuple],
1247
        ] = 100,
1248
        axes: Union[str, Sequence[str]] = None,
1249
        ranges: Sequence[Tuple[float, float]] = None,
1250
        **kwds,
1251
    ) -> xr.DataArray:
1252
        """Compute the histogram along the given dimensions.
1253

1254
        Args:
1255
            bins (int, dict, tuple, List[int], List[np.ndarray], List[tuple], optional):
1256
                Definition of the bins. Can be any of the following cases:
1257

1258
                - an integer describing the number of bins in on all dimensions
1259
                - a tuple of 3 numbers describing start, end and step of the binning
1260
                  range
1261
                - a np.arrays defining the binning edges
1262
                - a list (NOT a tuple) of any of the above (int, tuple or np.ndarray)
1263
                - a dictionary made of the axes as keys and any of the above as values.
1264

1265
                This takes priority over the axes and range arguments. Defaults to 100.
1266
            axes (Union[str, Sequence[str]], optional): The names of the axes (columns)
1267
                on which to calculate the histogram. The order will be the order of the
1268
                dimensions in the resulting array. Defaults to None.
1269
            ranges (Sequence[Tuple[float, float]], optional): list of tuples containing
1270
                the start and end point of the binning range. Defaults to None.
1271
            **kwds: Keyword arguments:
1272

1273
                - **hist_mode**: Histogram calculation method. "numpy" or "numba". See
1274
                  ``bin_dataframe`` for details. Defaults to
1275
                  config["binning"]["hist_mode"].
1276
                - **mode**: Defines how the results from each partition are combined.
1277
                  "fast", "lean" or "legacy". See ``bin_dataframe`` for details.
1278
                  Defaults to config["binning"]["mode"].
1279
                - **pbar**: Option to show the tqdm progress bar. Defaults to
1280
                  config["binning"]["pbar"].
1281
                - **n_cores**: Number of CPU cores to use for parallelization.
1282
                  Defaults to config["binning"]["num_cores"] or N_CPU-1.
1283
                - **threads_per_worker**: Limit the number of threads that
1284
                  multiprocessing can spawn per binning thread. Defaults to
1285
                  config["binning"]["threads_per_worker"].
1286
                - **threadpool_api**: The API to use for multiprocessing. "blas",
1287
                  "openmp" or None. See ``threadpool_limit`` for details. Defaults to
1288
                  config["binning"]["threadpool_API"].
1289
                - **df_partitions**: A list of dataframe partitions. Defaults to all
1290
                  partitions.
1291

1292
                Additional kwds are passed to ``bin_dataframe``.
1293

1294
        Raises:
1295
            AssertError: Rises when no dataframe has been loaded.
1296

1297
        Returns:
1298
            xr.DataArray: The result of the n-dimensional binning represented in an
1299
            xarray object, combining the data with the axes.
1300
        """
1301
        assert self._dataframe is not None, "dataframe needs to be loaded first!"
3✔
1302

1303
        hist_mode = kwds.pop("hist_mode", self._config["binning"]["hist_mode"])
3✔
1304
        mode = kwds.pop("mode", self._config["binning"]["mode"])
3✔
1305
        pbar = kwds.pop("pbar", self._config["binning"]["pbar"])
3✔
1306
        num_cores = kwds.pop("num_cores", self._config["binning"]["num_cores"])
3✔
1307
        threads_per_worker = kwds.pop(
3✔
1308
            "threads_per_worker",
1309
            self._config["binning"]["threads_per_worker"],
1310
        )
1311
        threadpool_api = kwds.pop(
3✔
1312
            "threadpool_API",
1313
            self._config["binning"]["threadpool_API"],
1314
        )
1315
        df_partitions = kwds.pop("df_partitions", None)
3✔
1316
        if df_partitions is not None:
3✔
1317
            dataframe = self._dataframe.partitions[
3✔
1318
                0 : min(df_partitions, self._dataframe.npartitions)
1319
            ]
1320
        else:
1321
            dataframe = self._dataframe
×
1322

1323
        self._binned = bin_dataframe(
3✔
1324
            df=dataframe,
1325
            bins=bins,
1326
            axes=axes,
1327
            ranges=ranges,
1328
            hist_mode=hist_mode,
1329
            mode=mode,
1330
            pbar=pbar,
1331
            n_cores=num_cores,
1332
            threads_per_worker=threads_per_worker,
1333
            threadpool_api=threadpool_api,
1334
            **kwds,
1335
        )
1336

1337
        for dim in self._binned.dims:
3✔
1338
            try:
3✔
1339
                self._binned[dim].attrs["unit"] = self._config["dataframe"]["units"][dim]
3✔
1340
            except KeyError:
×
1341
                pass
×
1342

1343
        self._binned.attrs["units"] = "counts"
3✔
1344
        self._binned.attrs["long_name"] = "photoelectron counts"
3✔
1345
        self._binned.attrs["metadata"] = self._attributes.metadata
3✔
1346

1347
        return self._binned
3✔
1348

1349
    def view_event_histogram(
3✔
1350
        self,
1351
        dfpid: int,
1352
        ncol: int = 2,
1353
        bins: Sequence[int] = None,
1354
        axes: Sequence[str] = None,
1355
        ranges: Sequence[Tuple[float, float]] = None,
1356
        backend: str = "bokeh",
1357
        legend: bool = True,
1358
        histkwds: dict = None,
1359
        legkwds: dict = None,
1360
        **kwds,
1361
    ):
1362
        """Plot individual histograms of specified dimensions (axes) from a substituent
1363
        dataframe partition.
1364

1365
        Args:
1366
            dfpid (int): Number of the data frame partition to look at.
1367
            ncol (int, optional): Number of columns in the plot grid. Defaults to 2.
1368
            bins (Sequence[int], optional): Number of bins to use for the speicified
1369
                axes. Defaults to config["histogram"]["bins"].
1370
            axes (Sequence[str], optional): Names of the axes to display.
1371
                Defaults to config["histogram"]["axes"].
1372
            ranges (Sequence[Tuple[float, float]], optional): Value ranges of all
1373
                specified axes. Defaults toconfig["histogram"]["ranges"].
1374
            backend (str, optional): Backend of the plotting library
1375
                ('matplotlib' or 'bokeh'). Defaults to "bokeh".
1376
            legend (bool, optional): Option to include a legend in the histogram plots.
1377
                Defaults to True.
1378
            histkwds (dict, optional): Keyword arguments for histograms
1379
                (see ``matplotlib.pyplot.hist()``). Defaults to {}.
1380
            legkwds (dict, optional): Keyword arguments for legend
1381
                (see ``matplotlib.pyplot.legend()``). Defaults to {}.
1382
            **kwds: Extra keyword arguments passed to
1383
                ``sed.diagnostics.grid_histogram()``.
1384

1385
        Raises:
1386
            TypeError: Raises when the input values are not of the correct type.
1387
        """
1388
        if bins is None:
×
1389
            bins = self._config["histogram"]["bins"]
×
1390
        if axes is None:
×
1391
            axes = self._config["histogram"]["axes"]
×
1392
        axes = list(axes)
×
1393
        for loc, axis in enumerate(axes):
×
1394
            if axis.startswith("@"):
×
1395
                axes[loc] = self._config["dataframe"].get(axis.strip("@"))
×
1396
        if ranges is None:
×
1397
            ranges = list(self._config["histogram"]["ranges"])
×
1398
            ranges[2] = np.asarray(ranges[2]) / 2 ** (
×
1399
                self._config["dataframe"]["tof_binning"] - 1
1400
            )
1401
            ranges[3] = np.asarray(ranges[3]) / 2 ** (
×
1402
                self._config["dataframe"]["adc_binning"] - 1
1403
            )
1404

1405
        input_types = map(type, [axes, bins, ranges])
×
1406
        allowed_types = [list, tuple]
×
1407

1408
        df = self._dataframe
×
1409

1410
        if not set(input_types).issubset(allowed_types):
×
1411
            raise TypeError(
×
1412
                "Inputs of axes, bins, ranges need to be list or tuple!",
1413
            )
1414

1415
        # Read out the values for the specified groups
1416
        group_dict_dd = {}
×
1417
        dfpart = df.get_partition(dfpid)
×
1418
        cols = dfpart.columns
×
1419
        for ax in axes:
×
1420
            group_dict_dd[ax] = dfpart.values[:, cols.get_loc(ax)]
×
1421
        group_dict = ddf.compute(group_dict_dd)[0]
×
1422

1423
        # Plot multiple histograms in a grid
1424
        grid_histogram(
×
1425
            group_dict,
1426
            ncol=ncol,
1427
            rvs=axes,
1428
            rvbins=bins,
1429
            rvranges=ranges,
1430
            backend=backend,
1431
            legend=legend,
1432
            histkwds=histkwds,
1433
            legkwds=legkwds,
1434
            **kwds,
1435
        )
1436

1437
    def save(
3✔
1438
        self,
1439
        faddr: str,
1440
        **kwds,
1441
    ):
1442
        """Saves the binned data to the provided path and filename.
1443

1444
        Args:
1445
            faddr (str): Path and name of the file to write. Its extension determines
1446
                the file type to write. Valid file types are:
1447

1448
                - "*.tiff", "*.tif": Saves a TIFF stack.
1449
                - "*.h5", "*.hdf5": Saves an HDF5 file.
1450
                - "*.nxs", "*.nexus": Saves a NeXus file.
1451

1452
            **kwds: Keyword argumens, which are passed to the writer functions:
1453
                For TIFF writing:
1454

1455
                - **alias_dict**: Dictionary of dimension aliases to use.
1456

1457
                For HDF5 writing:
1458

1459
                - **mode**: hdf5 read/write mode. Defaults to "w".
1460

1461
                For NeXus:
1462

1463
                - **reader**: Name of the nexustools reader to use.
1464
                  Defaults to config["nexus"]["reader"]
1465
                - **definiton**: NeXus application definition to use for saving.
1466
                  Must be supported by the used ``reader``. Defaults to
1467
                  config["nexus"]["definition"]
1468
                - **input_files**: A list of input files to pass to the reader.
1469
                  Defaults to config["nexus"]["input_files"]
1470
        """
1471
        if self._binned is None:
×
1472
            raise NameError("Need to bin data first!")
×
1473

1474
        extension = pathlib.Path(faddr).suffix
×
1475

1476
        if extension in (".tif", ".tiff"):
×
1477
            to_tiff(
×
1478
                data=self._binned,
1479
                faddr=faddr,
1480
                **kwds,
1481
            )
1482
        elif extension in (".h5", ".hdf5"):
×
1483
            to_h5(
×
1484
                data=self._binned,
1485
                faddr=faddr,
1486
                **kwds,
1487
            )
1488
        elif extension in (".nxs", ".nexus"):
×
1489
            reader = kwds.pop("reader", self._config["nexus"]["reader"])
×
1490
            definition = kwds.pop(
×
1491
                "definition",
1492
                self._config["nexus"]["definition"],
1493
            )
1494
            input_files = kwds.pop(
×
1495
                "input_files",
1496
                self._config["nexus"]["input_files"],
1497
            )
1498
            if isinstance(input_files, str):
×
1499
                input_files = [input_files]
×
1500

1501
            to_nexus(
×
1502
                data=self._binned,
1503
                faddr=faddr,
1504
                reader=reader,
1505
                definition=definition,
1506
                input_files=input_files,
1507
                **kwds,
1508
            )
1509

1510
        else:
1511
            raise NotImplementedError(
×
1512
                f"Unrecognized file format: {extension}.",
1513
            )
1514

1515
    def add_dimension(self, name: str, axis_range: Tuple):
3✔
1516
        """Add a dimension axis.
1517

1518
        Args:
1519
            name (str): name of the axis
1520
            axis_range (Tuple): range for the axis.
1521

1522
        Raises:
1523
            ValueError: Raised if an axis with that name already exists.
1524
        """
1525
        if name in self._coordinates:
×
1526
            raise ValueError(f"Axis {name} already exists")
×
1527

1528
        self.axis[name] = self.make_axis(axis_range)
×
1529

1530
    def make_axis(self, axis_range: Tuple) -> np.ndarray:
3✔
1531
        """Function to make an axis.
1532

1533
        Args:
1534
            axis_range (Tuple): range for the new axis.
1535
        """
1536

1537
        # TODO: What shall this function do?
1538
        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