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

OpenCOMPES / sed / 9756941681

02 Jul 2024 07:42AM UTC coverage: 92.425% (-0.04%) from 92.462%
9756941681

Pull #451

github

rettigl
move num_cores to "core" and use it globally
Pull Request #451: Tof binning as actual binning values

19 of 20 new or added lines in 5 files covered. (95.0%)

3 existing lines in 1 file now uncovered.

6869 of 7432 relevant lines covered (92.42%)

0.92 hits per line

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

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

3
"""
4
from __future__ import annotations
1✔
5

6
import pathlib
1✔
7
from collections.abc import Sequence
1✔
8
from datetime import datetime
1✔
9
from typing import Any
1✔
10
from typing import cast
1✔
11

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

19
from sed.binning import bin_dataframe
1✔
20
from sed.binning.binning import normalization_histogram_from_timed_dataframe
1✔
21
from sed.binning.binning import normalization_histogram_from_timestamps
1✔
22
from sed.calibrator import DelayCalibrator
1✔
23
from sed.calibrator import EnergyCalibrator
1✔
24
from sed.calibrator import MomentumCorrector
1✔
25
from sed.core.config import parse_config
1✔
26
from sed.core.config import save_config
1✔
27
from sed.core.dfops import add_time_stamped_data
1✔
28
from sed.core.dfops import apply_filter
1✔
29
from sed.core.dfops import apply_jitter
1✔
30
from sed.core.metadata import MetaHandler
1✔
31
from sed.diagnostics import grid_histogram
1✔
32
from sed.io import to_h5
1✔
33
from sed.io import to_nexus
1✔
34
from sed.io import to_tiff
1✔
35
from sed.loader import CopyTool
1✔
36
from sed.loader import get_loader
1✔
37
from sed.loader.mpes.loader import get_archiver_data
1✔
38
from sed.loader.mpes.loader import MpesLoader
1✔
39

40
N_CPU = psutil.cpu_count()
1✔
41

42

43
class SedProcessor:
1✔
44
    """Processor class of sed. Contains wrapper functions defining a work flow for data
45
    correction, calibration and binning.
46

47
    Args:
48
        metadata (dict, optional): Dict of external Metadata. Defaults to None.
49
        config (dict | str, optional): Config dictionary or config file name.
50
            Defaults to None.
51
        dataframe (pd.DataFrame | ddf.DataFrame, optional): dataframe to load
52
            into the class. Defaults to None.
53
        files (list[str], optional): List of files to pass to the loader defined in
54
            the config. Defaults to None.
55
        folder (str, optional): Folder containing files to pass to the loader
56
            defined in the config. Defaults to None.
57
        runs (Sequence[str], optional): List of run identifiers to pass to the loader
58
            defined in the config. Defaults to None.
59
        collect_metadata (bool): Option to collect metadata from files.
60
            Defaults to False.
61
        verbose (bool, optional): Option to print out diagnostic information.
62
            Defaults to config["core"]["verbose"] or False.
63
        **kwds: Keyword arguments passed to the reader.
64
    """
65

66
    def __init__(
1✔
67
        self,
68
        metadata: dict = None,
69
        config: dict | str = None,
70
        dataframe: pd.DataFrame | ddf.DataFrame = None,
71
        files: list[str] = None,
72
        folder: str = None,
73
        runs: Sequence[str] = None,
74
        collect_metadata: bool = False,
75
        verbose: bool = None,
76
        **kwds,
77
    ):
78
        """Processor class of sed. Contains wrapper functions defining a work flow
79
        for data correction, calibration, and binning.
80

81
        Args:
82
            metadata (dict, optional): Dict of external Metadata. Defaults to None.
83
            config (dict | str, optional): Config dictionary or config file name.
84
                Defaults to None.
85
            dataframe (pd.DataFrame | ddf.DataFrame, optional): dataframe to load
86
                into the class. Defaults to None.
87
            files (list[str], optional): List of files to pass to the loader defined in
88
                the config. Defaults to None.
89
            folder (str, optional): Folder containing files to pass to the loader
90
                defined in the config. Defaults to None.
91
            runs (Sequence[str], optional): List of run identifiers to pass to the loader
92
                defined in the config. Defaults to None.
93
            collect_metadata (bool, optional): Option to collect metadata from files.
94
                Defaults to False.
95
            verbose (bool, optional): Option to print out diagnostic information.
96
                Defaults to config["core"]["verbose"] or False.
97
            **kwds: Keyword arguments passed to parse_config and to the reader.
98
        """
99
        config_kwds = {
1✔
100
            key: value for key, value in kwds.items() if key in parse_config.__code__.co_varnames
101
        }
102
        for key in config_kwds.keys():
1✔
103
            del kwds[key]
1✔
104
        self._config = parse_config(config, **config_kwds)
1✔
105
        num_cores = self._config["core"].get("num_cores", N_CPU - 1)
1✔
106
        if num_cores >= N_CPU:
1✔
107
            num_cores = N_CPU - 1
1✔
108
        self._config["core"]["num_cores"] = num_cores
1✔
109

110
        if verbose is None:
1✔
111
            self.verbose = self._config["core"].get("verbose", False)
1✔
112
        else:
113
            self.verbose = verbose
1✔
114

115
        self._dataframe: pd.DataFrame | ddf.DataFrame = None
1✔
116
        self._timed_dataframe: pd.DataFrame | ddf.DataFrame = None
1✔
117
        self._files: list[str] = []
1✔
118

119
        self._binned: xr.DataArray = None
1✔
120
        self._pre_binned: xr.DataArray = None
1✔
121
        self._normalization_histogram: xr.DataArray = None
1✔
122
        self._normalized: xr.DataArray = None
1✔
123

124
        self._attributes = MetaHandler(meta=metadata)
1✔
125

126
        loader_name = self._config["core"]["loader"]
1✔
127
        self.loader = get_loader(
1✔
128
            loader_name=loader_name,
129
            config=self._config,
130
        )
131

132
        self.ec = EnergyCalibrator(
1✔
133
            loader=get_loader(
134
                loader_name=loader_name,
135
                config=self._config,
136
            ),
137
            config=self._config,
138
        )
139

140
        self.mc = MomentumCorrector(
1✔
141
            config=self._config,
142
        )
143

144
        self.dc = DelayCalibrator(
1✔
145
            config=self._config,
146
        )
147

148
        self.use_copy_tool = self._config.get("core", {}).get(
1✔
149
            "use_copy_tool",
150
            False,
151
        )
152
        if self.use_copy_tool:
1✔
153
            try:
1✔
154
                self.ct = CopyTool(
1✔
155
                    source=self._config["core"]["copy_tool_source"],
156
                    dest=self._config["core"]["copy_tool_dest"],
157
                    num_cores=self._config["core"]["num_cores"],
158
                    **self._config["core"].get("copy_tool_kwds", {}),
159
                )
160
            except KeyError:
1✔
161
                self.use_copy_tool = False
1✔
162

163
        # Load data if provided:
164
        if dataframe is not None or files is not None or folder is not None or runs is not None:
1✔
165
            self.load(
1✔
166
                dataframe=dataframe,
167
                metadata=metadata,
168
                files=files,
169
                folder=folder,
170
                runs=runs,
171
                collect_metadata=collect_metadata,
172
                **kwds,
173
            )
174

175
    def __repr__(self):
1✔
176
        if self._dataframe is None:
1✔
177
            df_str = "Dataframe: No Data loaded"
1✔
178
        else:
179
            df_str = self._dataframe.__repr__()
1✔
180
        pretty_str = df_str + "\n" + "Metadata: " + "\n" + self._attributes.__repr__()
1✔
181
        return pretty_str
1✔
182

183
    def _repr_html_(self):
1✔
184
        html = "<div>"
×
185

186
        if self._dataframe is None:
×
187
            df_html = "Dataframe: No Data loaded"
×
188
        else:
189
            df_html = self._dataframe._repr_html_()
×
190

191
        html += f"<details><summary>Dataframe</summary>{df_html}</details>"
×
192

193
        # Add expandable section for attributes
194
        html += "<details><summary>Metadata</summary>"
×
195
        html += "<div style='padding-left: 10px;'>"
×
196
        html += self._attributes._repr_html_()
×
197
        html += "</div></details>"
×
198

199
        html += "</div>"
×
200

201
        return html
×
202

203
    ## Suggestion:
204
    # @property
205
    # def overview_panel(self):
206
    #     """Provides an overview panel with plots of different data attributes."""
207
    #     self.view_event_histogram(dfpid=2, backend="matplotlib")
208

209
    @property
1✔
210
    def dataframe(self) -> pd.DataFrame | ddf.DataFrame:
1✔
211
        """Accessor to the underlying dataframe.
212

213
        Returns:
214
            pd.DataFrame | ddf.DataFrame: Dataframe object.
215
        """
216
        return self._dataframe
1✔
217

218
    @dataframe.setter
1✔
219
    def dataframe(self, dataframe: pd.DataFrame | ddf.DataFrame):
1✔
220
        """Setter for the underlying dataframe.
221

222
        Args:
223
            dataframe (pd.DataFrame | ddf.DataFrame): The dataframe object to set.
224
        """
225
        if not isinstance(dataframe, (pd.DataFrame, ddf.DataFrame)) or not isinstance(
1✔
226
            dataframe,
227
            self._dataframe.__class__,
228
        ):
229
            raise ValueError(
1✔
230
                "'dataframe' has to be a Pandas or Dask dataframe and has to be of the same kind "
231
                "as the dataframe loaded into the SedProcessor!.\n"
232
                f"Loaded type: {self._dataframe.__class__}, provided type: {dataframe}.",
233
            )
234
        self._dataframe = dataframe
1✔
235

236
    @property
1✔
237
    def timed_dataframe(self) -> pd.DataFrame | ddf.DataFrame:
1✔
238
        """Accessor to the underlying timed_dataframe.
239

240
        Returns:
241
            pd.DataFrame | ddf.DataFrame: Timed Dataframe object.
242
        """
243
        return self._timed_dataframe
1✔
244

245
    @timed_dataframe.setter
1✔
246
    def timed_dataframe(self, timed_dataframe: pd.DataFrame | ddf.DataFrame):
1✔
247
        """Setter for the underlying timed dataframe.
248

249
        Args:
250
            timed_dataframe (pd.DataFrame | ddf.DataFrame): The timed dataframe object to set
251
        """
252
        if not isinstance(timed_dataframe, (pd.DataFrame, ddf.DataFrame)) or not isinstance(
×
253
            timed_dataframe,
254
            self._timed_dataframe.__class__,
255
        ):
256
            raise ValueError(
×
257
                "'timed_dataframe' has to be a Pandas or Dask dataframe and has to be of the same "
258
                "kind as the dataframe loaded into the SedProcessor!.\n"
259
                f"Loaded type: {self._timed_dataframe.__class__}, "
260
                f"provided type: {timed_dataframe}.",
261
            )
262
        self._timed_dataframe = timed_dataframe
×
263

264
    @property
1✔
265
    def attributes(self) -> MetaHandler:
1✔
266
        """Accessor to the metadata dict.
267

268
        Returns:
269
            MetaHandler: The metadata object
270
        """
271
        return self._attributes
1✔
272

273
    def add_attribute(self, attributes: dict, name: str, **kwds):
1✔
274
        """Function to add element to the attributes dict.
275

276
        Args:
277
            attributes (dict): The attributes dictionary object to add.
278
            name (str): Key under which to add the dictionary to the attributes.
279
        """
280
        self._attributes.add(
1✔
281
            entry=attributes,
282
            name=name,
283
            **kwds,
284
        )
285

286
    @property
1✔
287
    def config(self) -> dict[Any, Any]:
1✔
288
        """Getter attribute for the config dictionary
289

290
        Returns:
291
            dict: The config dictionary.
292
        """
293
        return self._config
1✔
294

295
    @property
1✔
296
    def files(self) -> list[str]:
1✔
297
        """Getter attribute for the list of files
298

299
        Returns:
300
            list[str]: The list of loaded files
301
        """
302
        return self._files
1✔
303

304
    @property
1✔
305
    def binned(self) -> xr.DataArray:
1✔
306
        """Getter attribute for the binned data array
307

308
        Returns:
309
            xr.DataArray: The binned data array
310
        """
311
        if self._binned is None:
1✔
312
            raise ValueError("No binned data available, need to compute histogram first!")
×
313
        return self._binned
1✔
314

315
    @property
1✔
316
    def normalized(self) -> xr.DataArray:
1✔
317
        """Getter attribute for the normalized data array
318

319
        Returns:
320
            xr.DataArray: The normalized data array
321
        """
322
        if self._normalized is None:
1✔
323
            raise ValueError(
×
324
                "No normalized data available, compute data with normalization enabled!",
325
            )
326
        return self._normalized
1✔
327

328
    @property
1✔
329
    def normalization_histogram(self) -> xr.DataArray:
1✔
330
        """Getter attribute for the normalization histogram
331

332
        Returns:
333
            xr.DataArray: The normalization histogram
334
        """
335
        if self._normalization_histogram is None:
1✔
336
            raise ValueError("No normalization histogram available, generate histogram first!")
×
337
        return self._normalization_histogram
1✔
338

339
    def cpy(self, path: str | list[str]) -> str | list[str]:
1✔
340
        """Function to mirror a list of files or a folder from a network drive to a
341
        local storage. Returns either the original or the copied path to the given
342
        path. The option to use this functionality is set by
343
        config["core"]["use_copy_tool"].
344

345
        Args:
346
            path (str | list[str]): Source path or path list.
347

348
        Returns:
349
            str | list[str]: Source or destination path or path list.
350
        """
351
        if self.use_copy_tool:
1✔
352
            if isinstance(path, list):
1✔
353
                path_out = []
1✔
354
                for file in path:
1✔
355
                    path_out.append(self.ct.copy(file))
1✔
356
                return path_out
1✔
357

358
            return self.ct.copy(path)
×
359

360
        if isinstance(path, list):
1✔
361
            return path
1✔
362

363
        return path
1✔
364

365
    def load(
1✔
366
        self,
367
        dataframe: pd.DataFrame | ddf.DataFrame = None,
368
        metadata: dict = None,
369
        files: list[str] = None,
370
        folder: str = None,
371
        runs: Sequence[str] = None,
372
        collect_metadata: bool = False,
373
        **kwds,
374
    ):
375
        """Load tabular data of single events into the dataframe object in the class.
376

377
        Args:
378
            dataframe (pd.DataFrame | ddf.DataFrame, optional): data in tabular
379
                format. Accepts anything which can be interpreted by pd.DataFrame as
380
                an input. Defaults to None.
381
            metadata (dict, optional): Dict of external Metadata. Defaults to None.
382
            files (list[str], optional): List of file paths to pass to the loader.
383
                Defaults to None.
384
            runs (Sequence[str], optional): List of run identifiers to pass to the
385
                loader. Defaults to None.
386
            folder (str, optional): Folder path to pass to the loader.
387
                Defaults to None.
388
            collect_metadata (bool, optional): Option for collecting metadata in the reader.
389
            **kwds: Keyword parameters passed to the reader.
390

391
        Raises:
392
            ValueError: Raised if no valid input is provided.
393
        """
394
        if metadata is None:
1✔
395
            metadata = {}
1✔
396
        if dataframe is not None:
1✔
397
            timed_dataframe = kwds.pop("timed_dataframe", None)
1✔
398
        elif runs is not None:
1✔
399
            # If runs are provided, we only use the copy tool if also folder is provided.
400
            # In that case, we copy the whole provided base folder tree, and pass the copied
401
            # version to the loader as base folder to look for the runs.
402
            if folder is not None:
1✔
403
                dataframe, timed_dataframe, metadata = self.loader.read_dataframe(
1✔
404
                    folders=cast(str, self.cpy(folder)),
405
                    runs=runs,
406
                    metadata=metadata,
407
                    collect_metadata=collect_metadata,
408
                    **kwds,
409
                )
410
            else:
411
                dataframe, timed_dataframe, metadata = self.loader.read_dataframe(
×
412
                    runs=runs,
413
                    metadata=metadata,
414
                    collect_metadata=collect_metadata,
415
                    **kwds,
416
                )
417

418
        elif folder is not None:
1✔
419
            dataframe, timed_dataframe, metadata = self.loader.read_dataframe(
1✔
420
                folders=cast(str, self.cpy(folder)),
421
                metadata=metadata,
422
                collect_metadata=collect_metadata,
423
                **kwds,
424
            )
425
        elif files is not None:
1✔
426
            dataframe, timed_dataframe, metadata = self.loader.read_dataframe(
1✔
427
                files=cast(list[str], self.cpy(files)),
428
                metadata=metadata,
429
                collect_metadata=collect_metadata,
430
                **kwds,
431
            )
432
        else:
433
            raise ValueError(
1✔
434
                "Either 'dataframe', 'files', 'folder', or 'runs' needs to be provided!",
435
            )
436

437
        self._dataframe = dataframe
1✔
438
        self._timed_dataframe = timed_dataframe
1✔
439
        self._files = self.loader.files
1✔
440

441
        for key in metadata:
1✔
442
            self._attributes.add(
1✔
443
                entry=metadata[key],
444
                name=key,
445
                duplicate_policy="merge",
446
            )
447

448
    def filter_column(
1✔
449
        self,
450
        column: str,
451
        min_value: float = -np.inf,
452
        max_value: float = np.inf,
453
    ) -> None:
454
        """Filter values in a column which are outside of a given range
455

456
        Args:
457
            column (str): Name of the column to filter
458
            min_value (float, optional): Minimum value to keep. Defaults to None.
459
            max_value (float, optional): Maximum value to keep. Defaults to None.
460
        """
461
        if column != "index" and column not in self._dataframe.columns:
1✔
462
            raise KeyError(f"Column {column} not found in dataframe!")
1✔
463
        if min_value >= max_value:
1✔
464
            raise ValueError("min_value has to be smaller than max_value!")
1✔
465
        if self._dataframe is not None:
1✔
466
            self._dataframe = apply_filter(
1✔
467
                self._dataframe,
468
                col=column,
469
                lower_bound=min_value,
470
                upper_bound=max_value,
471
            )
472
        if self._timed_dataframe is not None and column in self._timed_dataframe.columns:
1✔
473
            self._timed_dataframe = apply_filter(
1✔
474
                self._timed_dataframe,
475
                column,
476
                lower_bound=min_value,
477
                upper_bound=max_value,
478
            )
479
        metadata = {
1✔
480
            "filter": {
481
                "column": column,
482
                "min_value": min_value,
483
                "max_value": max_value,
484
            },
485
        }
486
        self._attributes.add(metadata, "filter", duplicate_policy="merge")
1✔
487

488
    # Momentum calibration workflow
489
    # 1. Bin raw detector data for distortion correction
490
    def bin_and_load_momentum_calibration(
1✔
491
        self,
492
        df_partitions: int | Sequence[int] = 100,
493
        axes: list[str] = None,
494
        bins: list[int] = None,
495
        ranges: Sequence[tuple[float, float]] = None,
496
        plane: int = 0,
497
        width: int = 5,
498
        apply: bool = False,
499
        **kwds,
500
    ):
501
        """1st step of momentum correction work flow. Function to do an initial binning
502
        of the dataframe loaded to the class, slice a plane from it using an
503
        interactive view, and load it into the momentum corrector class.
504

505
        Args:
506
            df_partitions (int | Sequence[int], optional): Number of dataframe partitions
507
                to use for the initial binning. Defaults to 100.
508
            axes (list[str], optional): Axes to bin.
509
                Defaults to config["momentum"]["axes"].
510
            bins (list[int], optional): Bin numbers to use for binning.
511
                Defaults to config["momentum"]["bins"].
512
            ranges (Sequence[tuple[float, float]], optional): Ranges to use for binning.
513
                Defaults to config["momentum"]["ranges"].
514
            plane (int, optional): Initial value for the plane slider. Defaults to 0.
515
            width (int, optional): Initial value for the width slider. Defaults to 5.
516
            apply (bool, optional): Option to directly apply the values and select the
517
                slice. Defaults to False.
518
            **kwds: Keyword argument passed to the pre_binning function.
519
        """
520
        self._pre_binned = self.pre_binning(
1✔
521
            df_partitions=df_partitions,
522
            axes=axes,
523
            bins=bins,
524
            ranges=ranges,
525
            **kwds,
526
        )
527

528
        self.mc.load_data(data=self._pre_binned)
1✔
529
        self.mc.select_slicer(plane=plane, width=width, apply=apply)
1✔
530

531
    # 2. Generate the spline warp correction from momentum features.
532
    # Either autoselect features, or input features from view above.
533
    def define_features(
1✔
534
        self,
535
        features: np.ndarray = None,
536
        rotation_symmetry: int = 6,
537
        auto_detect: bool = False,
538
        include_center: bool = True,
539
        apply: bool = False,
540
        **kwds,
541
    ):
542
        """2. Step of the distortion correction workflow: Define feature points in
543
        momentum space. They can be either manually selected using a GUI tool, be
544
        provided as list of feature points, or auto-generated using a
545
        feature-detection algorithm.
546

547
        Args:
548
            features (np.ndarray, optional): np.ndarray of features. Defaults to None.
549
            rotation_symmetry (int, optional): Number of rotational symmetry axes.
550
                Defaults to 6.
551
            auto_detect (bool, optional): Whether to auto-detect the features.
552
                Defaults to False.
553
            include_center (bool, optional): Option to include a point at the center
554
                in the feature list. Defaults to True.
555
            apply (bool, optional): Option to directly apply the values and select the
556
                slice. Defaults to False.
557
            **kwds: Keyword arguments for ``MomentumCorrector.feature_extract()`` and
558
                ``MomentumCorrector.feature_select()``.
559
        """
560
        if auto_detect:  # automatic feature selection
1✔
561
            sigma = kwds.pop("sigma", self._config["momentum"]["sigma"])
×
562
            fwhm = kwds.pop("fwhm", self._config["momentum"]["fwhm"])
×
563
            sigma_radius = kwds.pop(
×
564
                "sigma_radius",
565
                self._config["momentum"]["sigma_radius"],
566
            )
567
            self.mc.feature_extract(
×
568
                sigma=sigma,
569
                fwhm=fwhm,
570
                sigma_radius=sigma_radius,
571
                rotsym=rotation_symmetry,
572
                **kwds,
573
            )
574
            features = self.mc.peaks
×
575

576
        self.mc.feature_select(
1✔
577
            rotsym=rotation_symmetry,
578
            include_center=include_center,
579
            features=features,
580
            apply=apply,
581
            **kwds,
582
        )
583

584
    # 3. Generate the spline warp correction from momentum features.
585
    # If no features have been selected before, use class defaults.
586
    def generate_splinewarp(
1✔
587
        self,
588
        use_center: bool = None,
589
        verbose: bool = None,
590
        **kwds,
591
    ):
592
        """3. Step of the distortion correction workflow: Generate the correction
593
        function restoring the symmetry in the image using a splinewarp algorithm.
594

595
        Args:
596
            use_center (bool, optional): Option to use the position of the
597
                center point in the correction. Default is read from config, or set to True.
598
            verbose (bool, optional): Option to print out diagnostic information.
599
                Defaults to config["core"]["verbose"].
600
            **kwds: Keyword arguments for MomentumCorrector.spline_warp_estimate().
601
        """
602
        if verbose is None:
1✔
603
            verbose = self.verbose
1✔
604

605
        self.mc.spline_warp_estimate(use_center=use_center, verbose=verbose, **kwds)
1✔
606

607
        if self.mc.slice is not None and verbose:
1✔
608
            print("Original slice with reference features")
1✔
609
            self.mc.view(annotated=True, backend="bokeh", crosshair=True)
1✔
610

611
            print("Corrected slice with target features")
1✔
612
            self.mc.view(
1✔
613
                image=self.mc.slice_corrected,
614
                annotated=True,
615
                points={"feats": self.mc.ptargs},
616
                backend="bokeh",
617
                crosshair=True,
618
            )
619

620
            print("Original slice with target features")
1✔
621
            self.mc.view(
1✔
622
                image=self.mc.slice,
623
                points={"feats": self.mc.ptargs},
624
                annotated=True,
625
                backend="bokeh",
626
            )
627

628
    # 3a. Save spline-warp parameters to config file.
629
    def save_splinewarp(
1✔
630
        self,
631
        filename: str = None,
632
        overwrite: bool = False,
633
    ):
634
        """Save the generated spline-warp parameters to the folder config file.
635

636
        Args:
637
            filename (str, optional): Filename of the config dictionary to save to.
638
                Defaults to "sed_config.yaml" in the current folder.
639
            overwrite (bool, optional): Option to overwrite the present dictionary.
640
                Defaults to False.
641
        """
642
        if filename is None:
1✔
643
            filename = "sed_config.yaml"
×
644
        if len(self.mc.correction) == 0:
1✔
645
            raise ValueError("No momentum correction parameters to save!")
×
646
        correction = {}
1✔
647
        for key, value in self.mc.correction.items():
1✔
648
            if key in ["reference_points", "target_points", "cdeform_field", "rdeform_field"]:
1✔
649
                continue
1✔
650
            if key in ["use_center", "rotation_symmetry"]:
1✔
651
                correction[key] = value
1✔
652
            elif key in ["center_point", "ascale"]:
1✔
653
                correction[key] = [float(i) for i in value]
1✔
654
            elif key in ["outer_points", "feature_points"]:
1✔
655
                correction[key] = []
1✔
656
                for point in value:
1✔
657
                    correction[key].append([float(i) for i in point])
1✔
658
            else:
659
                correction[key] = float(value)
1✔
660

661
        if "creation_date" not in correction:
1✔
662
            correction["creation_date"] = datetime.now().timestamp()
×
663

664
        config = {
1✔
665
            "momentum": {
666
                "correction": correction,
667
            },
668
        }
669
        save_config(config, filename, overwrite)
1✔
670
        print(f'Saved momentum correction parameters to "{filename}".')
1✔
671

672
    # 4. Pose corrections. Provide interactive interface for correcting
673
    # scaling, shift and rotation
674
    def pose_adjustment(
1✔
675
        self,
676
        transformations: dict[str, Any] = None,
677
        apply: bool = False,
678
        use_correction: bool = True,
679
        reset: bool = True,
680
        verbose: bool = None,
681
        **kwds,
682
    ):
683
        """3. step of the distortion correction workflow: Generate an interactive panel
684
        to adjust affine transformations that are applied to the image. Applies first
685
        a scaling, next an x/y translation, and last a rotation around the center of
686
        the image.
687

688
        Args:
689
            transformations (dict[str, Any], optional): Dictionary with transformations.
690
                Defaults to self.transformations or config["momentum"]["transformations"].
691
            apply (bool, optional): Option to directly apply the provided
692
                transformations. Defaults to False.
693
            use_correction (bool, option): Whether to use the spline warp correction
694
                or not. Defaults to True.
695
            reset (bool, optional): Option to reset the correction before transformation.
696
                Defaults to True.
697
            verbose (bool, optional): Option to print out diagnostic information.
698
                Defaults to config["core"]["verbose"].
699
            **kwds: Keyword parameters defining defaults for the transformations:
700

701
                - **scale** (float): Initial value of the scaling slider.
702
                - **xtrans** (float): Initial value of the xtrans slider.
703
                - **ytrans** (float): Initial value of the ytrans slider.
704
                - **angle** (float): Initial value of the angle slider.
705
        """
706
        if verbose is None:
1✔
707
            verbose = self.verbose
1✔
708

709
        # Generate homography as default if no distortion correction has been applied
710
        if self.mc.slice_corrected is None:
1✔
711
            if self.mc.slice is None:
1✔
712
                self.mc.slice = np.zeros(self._config["momentum"]["bins"][0:2])
1✔
713
            self.mc.slice_corrected = self.mc.slice
1✔
714

715
        if not use_correction:
1✔
716
            self.mc.reset_deformation()
1✔
717

718
        if self.mc.cdeform_field is None or self.mc.rdeform_field is None:
1✔
719
            # Generate distortion correction from config values
720
            self.mc.spline_warp_estimate(verbose=verbose)
×
721

722
        self.mc.pose_adjustment(
1✔
723
            transformations=transformations,
724
            apply=apply,
725
            reset=reset,
726
            verbose=verbose,
727
            **kwds,
728
        )
729

730
    # 4a. Save pose adjustment parameters to config file.
731
    def save_transformations(
1✔
732
        self,
733
        filename: str = None,
734
        overwrite: bool = False,
735
    ):
736
        """Save the pose adjustment parameters to the folder config file.
737

738
        Args:
739
            filename (str, optional): Filename of the config dictionary to save to.
740
                Defaults to "sed_config.yaml" in the current folder.
741
            overwrite (bool, optional): Option to overwrite the present dictionary.
742
                Defaults to False.
743
        """
744
        if filename is None:
1✔
745
            filename = "sed_config.yaml"
×
746
        if len(self.mc.transformations) == 0:
1✔
747
            raise ValueError("No momentum transformation parameters to save!")
×
748
        transformations = {}
1✔
749
        for key, value in self.mc.transformations.items():
1✔
750
            transformations[key] = float(value)
1✔
751

752
        if "creation_date" not in transformations:
1✔
753
            transformations["creation_date"] = datetime.now().timestamp()
×
754

755
        config = {
1✔
756
            "momentum": {
757
                "transformations": transformations,
758
            },
759
        }
760
        save_config(config, filename, overwrite)
1✔
761
        print(f'Saved momentum transformation parameters to "{filename}".')
1✔
762

763
    # 5. Apply the momentum correction to the dataframe
764
    def apply_momentum_correction(
1✔
765
        self,
766
        preview: bool = False,
767
        verbose: bool = None,
768
        **kwds,
769
    ):
770
        """Applies the distortion correction and pose adjustment (optional)
771
        to the dataframe.
772

773
        Args:
774
            preview (bool, optional): Option to preview the first elements of the data frame.
775
                Defaults to False.
776
            verbose (bool, optional): Option to print out diagnostic information.
777
                Defaults to config["core"]["verbose"].
778
            **kwds: Keyword parameters for ``MomentumCorrector.apply_correction``:
779

780
                - **rdeform_field** (np.ndarray, optional): Row deformation field.
781
                - **cdeform_field** (np.ndarray, optional): Column deformation field.
782
                - **inv_dfield** (np.ndarray, optional): Inverse deformation field.
783

784
        """
785
        if verbose is None:
1✔
786
            verbose = self.verbose
1✔
787

788
        x_column = self._config["dataframe"]["x_column"]
1✔
789
        y_column = self._config["dataframe"]["y_column"]
1✔
790

791
        if self._dataframe is not None:
1✔
792
            if verbose:
1✔
793
                print("Adding corrected X/Y columns to dataframe:")
1✔
794
            df, metadata = self.mc.apply_corrections(
1✔
795
                df=self._dataframe,
796
                verbose=verbose,
797
                **kwds,
798
            )
799
            if (
1✔
800
                self._timed_dataframe is not None
801
                and x_column in self._timed_dataframe.columns
802
                and y_column in self._timed_dataframe.columns
803
            ):
804
                tdf, _ = self.mc.apply_corrections(
1✔
805
                    self._timed_dataframe,
806
                    verbose=False,
807
                    **kwds,
808
                )
809

810
            # Add Metadata
811
            self._attributes.add(
1✔
812
                metadata,
813
                "momentum_correction",
814
                duplicate_policy="merge",
815
            )
816
            self._dataframe = df
1✔
817
            if (
1✔
818
                self._timed_dataframe is not None
819
                and x_column in self._timed_dataframe.columns
820
                and y_column in self._timed_dataframe.columns
821
            ):
822
                self._timed_dataframe = tdf
1✔
823
        else:
824
            raise ValueError("No dataframe loaded!")
×
825
        if preview:
1✔
826
            print(self._dataframe.head(10))
×
827
        else:
828
            if self.verbose:
1✔
829
                print(self._dataframe)
1✔
830

831
    # Momentum calibration work flow
832
    # 1. Calculate momentum calibration
833
    def calibrate_momentum_axes(
1✔
834
        self,
835
        point_a: np.ndarray | list[int] = None,
836
        point_b: np.ndarray | list[int] = None,
837
        k_distance: float = None,
838
        k_coord_a: np.ndarray | list[float] = None,
839
        k_coord_b: np.ndarray | list[float] = np.array([0.0, 0.0]),
840
        equiscale: bool = True,
841
        apply=False,
842
    ):
843
        """1. step of the momentum calibration workflow. Calibrate momentum
844
        axes using either provided pixel coordinates of a high-symmetry point and its
845
        distance to the BZ center, or the k-coordinates of two points in the BZ
846
        (depending on the equiscale option). Opens an interactive panel for selecting
847
        the points.
848

849
        Args:
850
            point_a (np.ndarray | list[int], optional): Pixel coordinates of the first
851
                point used for momentum calibration.
852
            point_b (np.ndarray | list[int], optional): Pixel coordinates of the
853
                second point used for momentum calibration.
854
                Defaults to config["momentum"]["center_pixel"].
855
            k_distance (float, optional): Momentum distance between point a and b.
856
                Needs to be provided if no specific k-coordinates for the two points
857
                are given. Defaults to None.
858
            k_coord_a (np.ndarray | list[float], optional): Momentum coordinate
859
                of the first point used for calibration. Used if equiscale is False.
860
                Defaults to None.
861
            k_coord_b (np.ndarray | list[float], optional): Momentum coordinate
862
                of the second point used for calibration. Defaults to [0.0, 0.0].
863
            equiscale (bool, optional): Option to apply different scales to kx and ky.
864
                If True, the distance between points a and b, and the absolute
865
                position of point a are used for defining the scale. If False, the
866
                scale is calculated from the k-positions of both points a and b.
867
                Defaults to True.
868
            apply (bool, optional): Option to directly store the momentum calibration
869
                in the class. Defaults to False.
870
        """
871
        if point_b is None:
1✔
872
            point_b = self._config["momentum"]["center_pixel"]
1✔
873

874
        self.mc.select_k_range(
1✔
875
            point_a=point_a,
876
            point_b=point_b,
877
            k_distance=k_distance,
878
            k_coord_a=k_coord_a,
879
            k_coord_b=k_coord_b,
880
            equiscale=equiscale,
881
            apply=apply,
882
        )
883

884
    # 1a. Save momentum calibration parameters to config file.
885
    def save_momentum_calibration(
1✔
886
        self,
887
        filename: str = None,
888
        overwrite: bool = False,
889
    ):
890
        """Save the generated momentum calibration parameters to the folder config file.
891

892
        Args:
893
            filename (str, optional): Filename of the config dictionary to save to.
894
                Defaults to "sed_config.yaml" in the current folder.
895
            overwrite (bool, optional): Option to overwrite the present dictionary.
896
                Defaults to False.
897
        """
898
        if filename is None:
1✔
899
            filename = "sed_config.yaml"
×
900
        if len(self.mc.calibration) == 0:
1✔
901
            raise ValueError("No momentum calibration parameters to save!")
×
902
        calibration = {}
1✔
903
        for key, value in self.mc.calibration.items():
1✔
904
            if key in ["kx_axis", "ky_axis", "grid", "extent"]:
1✔
905
                continue
1✔
906

907
            calibration[key] = float(value)
1✔
908

909
        if "creation_date" not in calibration:
1✔
910
            calibration["creation_date"] = datetime.now().timestamp()
×
911

912
        config = {"momentum": {"calibration": calibration}}
1✔
913
        save_config(config, filename, overwrite)
1✔
914
        print(f"Saved momentum calibration parameters to {filename}")
1✔
915

916
    # 2. Apply correction and calibration to the dataframe
917
    def apply_momentum_calibration(
1✔
918
        self,
919
        calibration: dict = None,
920
        preview: bool = False,
921
        verbose: bool = None,
922
        **kwds,
923
    ):
924
        """2. step of the momentum calibration work flow: Apply the momentum
925
        calibration stored in the class to the dataframe. If corrected X/Y axis exist,
926
        these are used.
927

928
        Args:
929
            calibration (dict, optional): Optional dictionary with calibration data to
930
                use. Defaults to None.
931
            preview (bool, optional): Option to preview the first elements of the data frame.
932
                Defaults to False.
933
            verbose (bool, optional): Option to print out diagnostic information.
934
                Defaults to config["core"]["verbose"].
935
            **kwds: Keyword args passed to ``DelayCalibrator.append_delay_axis``.
936
        """
937
        if verbose is None:
1✔
938
            verbose = self.verbose
1✔
939

940
        x_column = self._config["dataframe"]["x_column"]
1✔
941
        y_column = self._config["dataframe"]["y_column"]
1✔
942

943
        if self._dataframe is not None:
1✔
944
            if verbose:
1✔
945
                print("Adding kx/ky columns to dataframe:")
1✔
946
            df, metadata = self.mc.append_k_axis(
1✔
947
                df=self._dataframe,
948
                calibration=calibration,
949
                **kwds,
950
            )
951
            if (
1✔
952
                self._timed_dataframe is not None
953
                and x_column in self._timed_dataframe.columns
954
                and y_column in self._timed_dataframe.columns
955
            ):
956
                tdf, _ = self.mc.append_k_axis(
1✔
957
                    df=self._timed_dataframe,
958
                    calibration=calibration,
959
                    **kwds,
960
                )
961

962
            # Add Metadata
963
            self._attributes.add(
1✔
964
                metadata,
965
                "momentum_calibration",
966
                duplicate_policy="merge",
967
            )
968
            self._dataframe = df
1✔
969
            if (
1✔
970
                self._timed_dataframe is not None
971
                and x_column in self._timed_dataframe.columns
972
                and y_column in self._timed_dataframe.columns
973
            ):
974
                self._timed_dataframe = tdf
1✔
975
        else:
976
            raise ValueError("No dataframe loaded!")
×
977
        if preview:
1✔
978
            print(self._dataframe.head(10))
×
979
        else:
980
            if self.verbose:
1✔
981
                print(self._dataframe)
1✔
982

983
    # Energy correction workflow
984
    # 1. Adjust the energy correction parameters
985
    def adjust_energy_correction(
1✔
986
        self,
987
        correction_type: str = None,
988
        amplitude: float = None,
989
        center: tuple[float, float] = None,
990
        apply=False,
991
        **kwds,
992
    ):
993
        """1. step of the energy correction workflow: Opens an interactive plot to
994
        adjust the parameters for the TOF/energy correction. Also pre-bins the data if
995
        they are not present yet.
996

997
        Args:
998
            correction_type (str, optional): Type of correction to apply to the TOF
999
                axis. Valid values are:
1000

1001
                - 'spherical'
1002
                - 'Lorentzian'
1003
                - 'Gaussian'
1004
                - 'Lorentzian_asymmetric'
1005

1006
                Defaults to config["energy"]["correction_type"].
1007
            amplitude (float, optional): Amplitude of the correction.
1008
                Defaults to config["energy"]["correction"]["amplitude"].
1009
            center (tuple[float, float], optional): Center X/Y coordinates for the
1010
                correction. Defaults to config["energy"]["correction"]["center"].
1011
            apply (bool, optional): Option to directly apply the provided or default
1012
                correction parameters. Defaults to False.
1013
            **kwds: Keyword parameters passed to ``EnergyCalibrator.adjust_energy_correction()``.
1014
        """
1015
        if self._pre_binned is None:
1✔
1016
            print(
1✔
1017
                "Pre-binned data not present, binning using defaults from config...",
1018
            )
1019
            self._pre_binned = self.pre_binning()
1✔
1020

1021
        self.ec.adjust_energy_correction(
1✔
1022
            self._pre_binned,
1023
            correction_type=correction_type,
1024
            amplitude=amplitude,
1025
            center=center,
1026
            apply=apply,
1027
            **kwds,
1028
        )
1029

1030
    # 1a. Save energy correction parameters to config file.
1031
    def save_energy_correction(
1✔
1032
        self,
1033
        filename: str = None,
1034
        overwrite: bool = False,
1035
    ):
1036
        """Save the generated energy correction parameters to the folder config file.
1037

1038
        Args:
1039
            filename (str, optional): Filename of the config dictionary to save to.
1040
                Defaults to "sed_config.yaml" in the current folder.
1041
            overwrite (bool, optional): Option to overwrite the present dictionary.
1042
                Defaults to False.
1043
        """
1044
        if filename is None:
1✔
1045
            filename = "sed_config.yaml"
1✔
1046
        if len(self.ec.correction) == 0:
1✔
1047
            raise ValueError("No energy correction parameters to save!")
×
1048
        correction = {}
1✔
1049
        for key, val in self.ec.correction.items():
1✔
1050
            if key == "correction_type":
1✔
1051
                correction[key] = val
1✔
1052
            elif key == "center":
1✔
1053
                correction[key] = [float(i) for i in val]
1✔
1054
            else:
1055
                correction[key] = float(val)
1✔
1056

1057
        if "creation_date" not in correction:
1✔
1058
            correction["creation_date"] = datetime.now().timestamp()
×
1059

1060
        config = {"energy": {"correction": correction}}
1✔
1061
        save_config(config, filename, overwrite)
1✔
1062
        print(f"Saved energy correction parameters to {filename}")
1✔
1063

1064
    # 2. Apply energy correction to dataframe
1065
    def apply_energy_correction(
1✔
1066
        self,
1067
        correction: dict = None,
1068
        preview: bool = False,
1069
        verbose: bool = None,
1070
        **kwds,
1071
    ):
1072
        """2. step of the energy correction workflow: Apply the energy correction
1073
        parameters stored in the class to the dataframe.
1074

1075
        Args:
1076
            correction (dict, optional): Dictionary containing the correction
1077
                parameters. Defaults to config["energy"]["calibration"].
1078
            preview (bool, optional): Option to preview the first elements of the data frame.
1079
                Defaults to False.
1080
            verbose (bool, optional): Option to print out diagnostic information.
1081
                Defaults to config["core"]["verbose"].
1082
            **kwds:
1083
                Keyword args passed to ``EnergyCalibrator.apply_energy_correction()``.
1084
        """
1085
        if verbose is None:
1✔
1086
            verbose = self.verbose
1✔
1087

1088
        tof_column = self._config["dataframe"]["tof_column"]
1✔
1089

1090
        if self._dataframe is not None:
1✔
1091
            if verbose:
1✔
1092
                print("Applying energy correction to dataframe...")
1✔
1093
            df, metadata = self.ec.apply_energy_correction(
1✔
1094
                df=self._dataframe,
1095
                correction=correction,
1096
                verbose=verbose,
1097
                **kwds,
1098
            )
1099
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1100
                tdf, _ = self.ec.apply_energy_correction(
1✔
1101
                    df=self._timed_dataframe,
1102
                    correction=correction,
1103
                    verbose=False,
1104
                    **kwds,
1105
                )
1106

1107
            # Add Metadata
1108
            self._attributes.add(
1✔
1109
                metadata,
1110
                "energy_correction",
1111
            )
1112
            self._dataframe = df
1✔
1113
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1114
                self._timed_dataframe = tdf
1✔
1115
        else:
1116
            raise ValueError("No dataframe loaded!")
×
1117
        if preview:
1✔
1118
            print(self._dataframe.head(10))
×
1119
        else:
1120
            if verbose:
1✔
1121
                print(self._dataframe)
×
1122

1123
    # Energy calibrator workflow
1124
    # 1. Load and normalize data
1125
    def load_bias_series(
1✔
1126
        self,
1127
        binned_data: xr.DataArray | tuple[np.ndarray, np.ndarray, np.ndarray] = None,
1128
        data_files: list[str] = None,
1129
        axes: list[str] = None,
1130
        bins: list = None,
1131
        ranges: Sequence[tuple[float, float]] = None,
1132
        biases: np.ndarray = None,
1133
        bias_key: str = None,
1134
        normalize: bool = None,
1135
        span: int = None,
1136
        order: int = None,
1137
    ):
1138
        """1. step of the energy calibration workflow: Load and bin data from
1139
        single-event files, or load binned bias/TOF traces.
1140

1141
        Args:
1142
            binned_data (xr.DataArray | tuple[np.ndarray, np.ndarray, np.ndarray], optional):
1143
                Binned data If provided as DataArray, Needs to contain dimensions
1144
                config["dataframe"]["tof_column"] and config["dataframe"]["bias_column"]. If
1145
                provided as tuple, needs to contain elements tof, biases, traces.
1146
            data_files (list[str], optional): list of file paths to bin
1147
            axes (list[str], optional): bin axes.
1148
                Defaults to config["dataframe"]["tof_column"].
1149
            bins (list, optional): number of bins.
1150
                Defaults to config["energy"]["bins"].
1151
            ranges (Sequence[tuple[float, float]], optional): bin ranges.
1152
                Defaults to config["energy"]["ranges"].
1153
            biases (np.ndarray, optional): Bias voltages used. If missing, bias
1154
                voltages are extracted from the data files.
1155
            bias_key (str, optional): hdf5 path where bias values are stored.
1156
                Defaults to config["energy"]["bias_key"].
1157
            normalize (bool, optional): Option to normalize traces.
1158
                Defaults to config["energy"]["normalize"].
1159
            span (int, optional): span smoothing parameters of the LOESS method
1160
                (see ``scipy.signal.savgol_filter()``).
1161
                Defaults to config["energy"]["normalize_span"].
1162
            order (int, optional): order smoothing parameters of the LOESS method
1163
                (see ``scipy.signal.savgol_filter()``).
1164
                Defaults to config["energy"]["normalize_order"].
1165
        """
1166
        if binned_data is not None:
1✔
1167
            if isinstance(binned_data, xr.DataArray):
1✔
1168
                if (
1✔
1169
                    self._config["dataframe"]["tof_column"] not in binned_data.dims
1170
                    or self._config["dataframe"]["bias_column"] not in binned_data.dims
1171
                ):
1172
                    raise ValueError(
1✔
1173
                        "If binned_data is provided as an xarray, it needs to contain dimensions "
1174
                        f"'{self._config['dataframe']['tof_column']}' and "
1175
                        f"'{self._config['dataframe']['bias_column']}'!.",
1176
                    )
1177
                tof = binned_data.coords[self._config["dataframe"]["tof_column"]].values
1✔
1178
                biases = binned_data.coords[self._config["dataframe"]["bias_column"]].values
1✔
1179
                traces = binned_data.values[:, :]
1✔
1180
            else:
1181
                try:
1✔
1182
                    (tof, biases, traces) = binned_data
1✔
1183
                except ValueError as exc:
1✔
1184
                    raise ValueError(
1✔
1185
                        "If binned_data is provided as tuple, it needs to contain "
1186
                        "(tof, biases, traces)!",
1187
                    ) from exc
1188
            self.ec.load_data(biases=biases, traces=traces, tof=tof)
1✔
1189

1190
        elif data_files is not None:
1✔
1191
            self.ec.bin_data(
1✔
1192
                data_files=cast(list[str], self.cpy(data_files)),
1193
                axes=axes,
1194
                bins=bins,
1195
                ranges=ranges,
1196
                biases=biases,
1197
                bias_key=bias_key,
1198
            )
1199

1200
        else:
1201
            raise ValueError("Either binned_data or data_files needs to be provided!")
1✔
1202

1203
        if (normalize is not None and normalize is True) or (
1✔
1204
            normalize is None and self._config["energy"]["normalize"]
1205
        ):
1206
            if span is None:
1✔
1207
                span = self._config["energy"]["normalize_span"]
1✔
1208
            if order is None:
1✔
1209
                order = self._config["energy"]["normalize_order"]
1✔
1210
            self.ec.normalize(smooth=True, span=span, order=order)
1✔
1211
        self.ec.view(
1✔
1212
            traces=self.ec.traces_normed,
1213
            xaxis=self.ec.tof,
1214
            backend="bokeh",
1215
        )
1216

1217
    # 2. extract ranges and get peak positions
1218
    def find_bias_peaks(
1✔
1219
        self,
1220
        ranges: list[tuple] | tuple,
1221
        ref_id: int = 0,
1222
        infer_others: bool = True,
1223
        mode: str = "replace",
1224
        radius: int = None,
1225
        peak_window: int = None,
1226
        apply: bool = False,
1227
    ):
1228
        """2. step of the energy calibration workflow: Find a peak within a given range
1229
        for the indicated reference trace, and tries to find the same peak for all
1230
        other traces. Uses fast_dtw to align curves, which might not be too good if the
1231
        shape of curves changes qualitatively. Ideally, choose a reference trace in the
1232
        middle of the set, and don't choose the range too narrow around the peak.
1233
        Alternatively, a list of ranges for all traces can be provided.
1234

1235
        Args:
1236
            ranges (list[tuple] | tuple): Tuple of TOF values indicating a range.
1237
                Alternatively, a list of ranges for all traces can be given.
1238
            ref_id (int, optional): The id of the trace the range refers to.
1239
                Defaults to 0.
1240
            infer_others (bool, optional): Whether to determine the range for the other
1241
                traces. Defaults to True.
1242
            mode (str, optional): Whether to "add" or "replace" existing ranges.
1243
                Defaults to "replace".
1244
            radius (int, optional): Radius parameter for fast_dtw.
1245
                Defaults to config["energy"]["fastdtw_radius"].
1246
            peak_window (int, optional): Peak_window parameter for the peak detection
1247
                algorithm. amount of points that have to have to behave monotonously
1248
                around a peak. Defaults to config["energy"]["peak_window"].
1249
            apply (bool, optional): Option to directly apply the provided parameters.
1250
                Defaults to False.
1251
        """
1252
        if radius is None:
1✔
1253
            radius = self._config["energy"]["fastdtw_radius"]
1✔
1254
        if peak_window is None:
1✔
1255
            peak_window = self._config["energy"]["peak_window"]
1✔
1256
        if not infer_others:
1✔
1257
            self.ec.add_ranges(
1✔
1258
                ranges=ranges,
1259
                ref_id=ref_id,
1260
                infer_others=infer_others,
1261
                mode=mode,
1262
                radius=radius,
1263
            )
1264
            print(self.ec.featranges)
1✔
1265
            try:
1✔
1266
                self.ec.feature_extract(peak_window=peak_window)
1✔
1267
                self.ec.view(
1✔
1268
                    traces=self.ec.traces_normed,
1269
                    segs=self.ec.featranges,
1270
                    xaxis=self.ec.tof,
1271
                    peaks=self.ec.peaks,
1272
                    backend="bokeh",
1273
                )
1274
            except IndexError:
×
1275
                print("Could not determine all peaks!")
×
1276
                raise
×
1277
        else:
1278
            # New adjustment tool
1279
            assert isinstance(ranges, tuple)
1✔
1280
            self.ec.adjust_ranges(
1✔
1281
                ranges=ranges,
1282
                ref_id=ref_id,
1283
                traces=self.ec.traces_normed,
1284
                infer_others=infer_others,
1285
                radius=radius,
1286
                peak_window=peak_window,
1287
                apply=apply,
1288
            )
1289

1290
    # 3. Fit the energy calibration relation
1291
    def calibrate_energy_axis(
1✔
1292
        self,
1293
        ref_id: int,
1294
        ref_energy: float,
1295
        method: str = None,
1296
        energy_scale: str = None,
1297
        verbose: bool = None,
1298
        **kwds,
1299
    ):
1300
        """3. Step of the energy calibration workflow: Calculate the calibration
1301
        function for the energy axis, and apply it to the dataframe. Two
1302
        approximations are implemented, a (normally 3rd order) polynomial
1303
        approximation, and a d^2/(t-t0)^2 relation.
1304

1305
        Args:
1306
            ref_id (int): id of the trace at the bias where the reference energy is
1307
                given.
1308
            ref_energy (float): Absolute energy of the detected feature at the bias
1309
                of ref_id
1310
            method (str, optional): Method for determining the energy calibration.
1311

1312
                - **'lmfit'**: Energy calibration using lmfit and 1/t^2 form.
1313
                - **'lstsq'**, **'lsqr'**: Energy calibration using polynomial form.
1314

1315
                Defaults to config["energy"]["calibration_method"]
1316
            energy_scale (str, optional): Direction of increasing energy scale.
1317

1318
                - **'kinetic'**: increasing energy with decreasing TOF.
1319
                - **'binding'**: increasing energy with increasing TOF.
1320

1321
                Defaults to config["energy"]["energy_scale"]
1322
            verbose (bool, optional): Option to print out diagnostic information.
1323
                Defaults to config["core"]["verbose"].
1324
            **kwds**: Keyword parameters passed to ``EnergyCalibrator.calibrate()``.
1325
        """
1326
        if verbose is None:
1✔
1327
            verbose = self.verbose
1✔
1328

1329
        if method is None:
1✔
1330
            method = self._config["energy"]["calibration_method"]
1✔
1331

1332
        if energy_scale is None:
1✔
1333
            energy_scale = self._config["energy"]["energy_scale"]
1✔
1334

1335
        self.ec.calibrate(
1✔
1336
            ref_id=ref_id,
1337
            ref_energy=ref_energy,
1338
            method=method,
1339
            energy_scale=energy_scale,
1340
            verbose=verbose,
1341
            **kwds,
1342
        )
1343
        if verbose:
1✔
1344
            print("Quality of Calibration:")
1✔
1345
            self.ec.view(
1✔
1346
                traces=self.ec.traces_normed,
1347
                xaxis=self.ec.calibration["axis"],
1348
                align=True,
1349
                energy_scale=energy_scale,
1350
                backend="bokeh",
1351
            )
1352
            print("E/TOF relationship:")
1✔
1353
            self.ec.view(
1✔
1354
                traces=self.ec.calibration["axis"][None, :],
1355
                xaxis=self.ec.tof,
1356
                backend="matplotlib",
1357
                show_legend=False,
1358
            )
1359
            if energy_scale == "kinetic":
1✔
1360
                plt.scatter(
1✔
1361
                    self.ec.peaks[:, 0],
1362
                    -(self.ec.biases - self.ec.biases[ref_id]) + ref_energy,
1363
                    s=50,
1364
                    c="k",
1365
                )
1366
            elif energy_scale == "binding":
1✔
1367
                plt.scatter(
1✔
1368
                    self.ec.peaks[:, 0],
1369
                    self.ec.biases - self.ec.biases[ref_id] + ref_energy,
1370
                    s=50,
1371
                    c="k",
1372
                )
1373
            else:
1374
                raise ValueError(
×
1375
                    'energy_scale needs to be either "binding" or "kinetic"',
1376
                    f", got {energy_scale}.",
1377
                )
1378
            plt.xlabel("Time-of-flight", fontsize=15)
1✔
1379
            plt.ylabel("Energy (eV)", fontsize=15)
1✔
1380
            plt.show()
1✔
1381

1382
    # 3a. Save energy calibration parameters to config file.
1383
    def save_energy_calibration(
1✔
1384
        self,
1385
        filename: str = None,
1386
        overwrite: bool = False,
1387
    ):
1388
        """Save the generated energy calibration parameters to the folder config file.
1389

1390
        Args:
1391
            filename (str, optional): Filename of the config dictionary to save to.
1392
                Defaults to "sed_config.yaml" in the current folder.
1393
            overwrite (bool, optional): Option to overwrite the present dictionary.
1394
                Defaults to False.
1395
        """
1396
        if filename is None:
1✔
1397
            filename = "sed_config.yaml"
×
1398
        if len(self.ec.calibration) == 0:
1✔
1399
            raise ValueError("No energy calibration parameters to save!")
×
1400
        calibration = {}
1✔
1401
        for key, value in self.ec.calibration.items():
1✔
1402
            if key in ["axis", "refid", "Tmat", "bvec"]:
1✔
1403
                continue
1✔
1404
            if key == "energy_scale":
1✔
1405
                calibration[key] = value
1✔
1406
            elif key == "coeffs":
1✔
1407
                calibration[key] = [float(i) for i in value]
1✔
1408
            else:
1409
                calibration[key] = float(value)
1✔
1410

1411
        if "creation_date" not in calibration:
1✔
1412
            calibration["creation_date"] = datetime.now().timestamp()
×
1413

1414
        config = {"energy": {"calibration": calibration}}
1✔
1415
        save_config(config, filename, overwrite)
1✔
1416
        print(f'Saved energy calibration parameters to "{filename}".')
1✔
1417

1418
    # 4. Apply energy calibration to the dataframe
1419
    def append_energy_axis(
1✔
1420
        self,
1421
        calibration: dict = None,
1422
        preview: bool = False,
1423
        verbose: bool = None,
1424
        **kwds,
1425
    ):
1426
        """4. step of the energy calibration workflow: Apply the calibration function
1427
        to to the dataframe. Two approximations are implemented, a (normally 3rd order)
1428
        polynomial approximation, and a d^2/(t-t0)^2 relation. a calibration dictionary
1429
        can be provided.
1430

1431
        Args:
1432
            calibration (dict, optional): Calibration dict containing calibration
1433
                parameters. Overrides calibration from class or config.
1434
                Defaults to None.
1435
            preview (bool): Option to preview the first elements of the data frame.
1436
            verbose (bool, optional): Option to print out diagnostic information.
1437
                Defaults to config["core"]["verbose"].
1438
            **kwds:
1439
                Keyword args passed to ``EnergyCalibrator.append_energy_axis()``.
1440
        """
1441
        if verbose is None:
1✔
1442
            verbose = self.verbose
1✔
1443

1444
        tof_column = self._config["dataframe"]["tof_column"]
1✔
1445

1446
        if self._dataframe is not None:
1✔
1447
            if verbose:
1✔
1448
                print("Adding energy column to dataframe:")
1✔
1449
            df, metadata = self.ec.append_energy_axis(
1✔
1450
                df=self._dataframe,
1451
                calibration=calibration,
1452
                verbose=verbose,
1453
                **kwds,
1454
            )
1455
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1456
                tdf, _ = self.ec.append_energy_axis(
1✔
1457
                    df=self._timed_dataframe,
1458
                    calibration=calibration,
1459
                    verbose=False,
1460
                    **kwds,
1461
                )
1462

1463
            # Add Metadata
1464
            self._attributes.add(
1✔
1465
                metadata,
1466
                "energy_calibration",
1467
                duplicate_policy="merge",
1468
            )
1469
            self._dataframe = df
1✔
1470
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1471
                self._timed_dataframe = tdf
1✔
1472

1473
        else:
1474
            raise ValueError("No dataframe loaded!")
×
1475
        if preview:
1✔
1476
            print(self._dataframe.head(10))
×
1477
        else:
1478
            if verbose:
1✔
1479
                print(self._dataframe)
1✔
1480

1481
    def add_energy_offset(
1✔
1482
        self,
1483
        constant: float = None,
1484
        columns: str | Sequence[str] = None,
1485
        weights: float | Sequence[float] = None,
1486
        reductions: str | Sequence[str] = None,
1487
        preserve_mean: bool | Sequence[bool] = None,
1488
        preview: bool = False,
1489
        verbose: bool = None,
1490
    ) -> None:
1491
        """Shift the energy axis of the dataframe by a given amount.
1492

1493
        Args:
1494
            constant (float, optional): The constant to shift the energy axis by.
1495
            columns (str | Sequence[str], optional): Name of the column(s) to apply the shift from.
1496
            weights (float | Sequence[float], optional): weights to apply to the columns.
1497
                Can also be used to flip the sign (e.g. -1). Defaults to 1.
1498
            reductions (str | Sequence[str], optional): The reduction to apply to the column.
1499
                Should be an available method of dask.dataframe.Series. For example "mean". In this
1500
                case the function is applied to the column to generate a single value for the whole
1501
                dataset. If None, the shift is applied per-dataframe-row. Defaults to None.
1502
                Currently only "mean" is supported.
1503
            preserve_mean (bool | Sequence[bool], optional): Whether to subtract the mean of the
1504
                column before applying the shift. Defaults to False.
1505
            preview (bool, optional): Option to preview the first elements of the data frame.
1506
                Defaults to False.
1507
            verbose (bool, optional): Option to print out diagnostic information.
1508
                Defaults to config["core"]["verbose"].
1509

1510
        Raises:
1511
            ValueError: If the energy column is not in the dataframe.
1512
        """
1513
        if verbose is None:
1✔
1514
            verbose = self.verbose
1✔
1515

1516
        energy_column = self._config["dataframe"]["energy_column"]
1✔
1517
        if energy_column not in self._dataframe.columns:
1✔
1518
            raise ValueError(
1✔
1519
                f"Energy column {energy_column} not found in dataframe! "
1520
                "Run `append_energy_axis()` first.",
1521
            )
1522
        if self.dataframe is not None:
1✔
1523
            if verbose:
1✔
1524
                print("Adding energy offset to dataframe:")
1✔
1525
            df, metadata = self.ec.add_offsets(
1✔
1526
                df=self._dataframe,
1527
                constant=constant,
1528
                columns=columns,
1529
                energy_column=energy_column,
1530
                weights=weights,
1531
                reductions=reductions,
1532
                preserve_mean=preserve_mean,
1533
                verbose=verbose,
1534
            )
1535
            if self._timed_dataframe is not None and energy_column in self._timed_dataframe.columns:
1✔
1536
                tdf, _ = self.ec.add_offsets(
1✔
1537
                    df=self._timed_dataframe,
1538
                    constant=constant,
1539
                    columns=columns,
1540
                    energy_column=energy_column,
1541
                    weights=weights,
1542
                    reductions=reductions,
1543
                    preserve_mean=preserve_mean,
1544
                )
1545

1546
            self._attributes.add(
1✔
1547
                metadata,
1548
                "add_energy_offset",
1549
                # TODO: allow only appending when no offset along this column(s) was applied
1550
                # TODO: clear memory of modifications if the energy axis is recalculated
1551
                duplicate_policy="append",
1552
            )
1553
            self._dataframe = df
1✔
1554
            if self._timed_dataframe is not None and energy_column in self._timed_dataframe.columns:
1✔
1555
                self._timed_dataframe = tdf
1✔
1556
        else:
1557
            raise ValueError("No dataframe loaded!")
×
1558
        if preview:
1✔
1559
            print(self._dataframe.head(10))
×
1560
        elif verbose:
1✔
1561
            print(self._dataframe)
1✔
1562

1563
    def save_energy_offset(
1✔
1564
        self,
1565
        filename: str = None,
1566
        overwrite: bool = False,
1567
    ):
1568
        """Save the generated energy calibration parameters to the folder config file.
1569

1570
        Args:
1571
            filename (str, optional): Filename of the config dictionary to save to.
1572
                Defaults to "sed_config.yaml" in the current folder.
1573
            overwrite (bool, optional): Option to overwrite the present dictionary.
1574
                Defaults to False.
1575
        """
1576
        if filename is None:
×
1577
            filename = "sed_config.yaml"
×
1578
        if len(self.ec.offsets) == 0:
×
1579
            raise ValueError("No energy offset parameters to save!")
×
1580

1581
        if "creation_date" not in self.ec.offsets.keys():
×
1582
            self.ec.offsets["creation_date"] = datetime.now().timestamp()
×
1583

1584
        config = {"energy": {"offsets": self.ec.offsets}}
×
1585
        save_config(config, filename, overwrite)
×
1586
        print(f'Saved energy offset parameters to "{filename}".')
×
1587

1588
    def append_tof_ns_axis(
1✔
1589
        self,
1590
        preview: bool = False,
1591
        verbose: bool = None,
1592
        **kwds,
1593
    ):
1594
        """Convert time-of-flight channel steps to nanoseconds.
1595

1596
        Args:
1597
            tof_ns_column (str, optional): Name of the generated column containing the
1598
                time-of-flight in nanosecond.
1599
                Defaults to config["dataframe"]["tof_ns_column"].
1600
            preview (bool, optional): Option to preview the first elements of the data frame.
1601
                Defaults to False.
1602
            verbose (bool, optional): Option to print out diagnostic information.
1603
                Defaults to config["core"]["verbose"].
1604
            **kwds: additional arguments are passed to ``EnergyCalibrator.tof_step_to_ns()``.
1605

1606
        """
1607
        if verbose is None:
1✔
1608
            verbose = self.verbose
1✔
1609

1610
        tof_column = self._config["dataframe"]["tof_column"]
1✔
1611

1612
        if self._dataframe is not None:
1✔
1613
            if verbose:
1✔
1614
                print("Adding time-of-flight column in nanoseconds to dataframe:")
1✔
1615
            # TODO assert order of execution through metadata
1616

1617
            df, metadata = self.ec.append_tof_ns_axis(
1✔
1618
                df=self._dataframe,
1619
                **kwds,
1620
            )
1621
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1622
                tdf, _ = self.ec.append_tof_ns_axis(
1✔
1623
                    df=self._timed_dataframe,
1624
                    **kwds,
1625
                )
1626

1627
            self._attributes.add(
1✔
1628
                metadata,
1629
                "tof_ns_conversion",
1630
                duplicate_policy="overwrite",
1631
            )
1632
            self._dataframe = df
1✔
1633
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1634
                self._timed_dataframe = tdf
1✔
1635
        else:
1636
            raise ValueError("No dataframe loaded!")
×
1637
        if preview:
1✔
1638
            print(self._dataframe.head(10))
×
1639
        else:
1640
            if verbose:
1✔
1641
                print(self._dataframe)
1✔
1642

1643
    def align_dld_sectors(
1✔
1644
        self,
1645
        sector_delays: np.ndarray = None,
1646
        preview: bool = False,
1647
        verbose: bool = None,
1648
        **kwds,
1649
    ):
1650
        """Align the 8s sectors of the HEXTOF endstation.
1651

1652
        Args:
1653
            sector_delays (np.ndarray, optional): Array containing the sector delays. Defaults to
1654
                config["dataframe"]["sector_delays"].
1655
            preview (bool, optional): Option to preview the first elements of the data frame.
1656
                Defaults to False.
1657
            verbose (bool, optional): Option to print out diagnostic information.
1658
                Defaults to config["core"]["verbose"].
1659
            **kwds: additional arguments are passed to ``EnergyCalibrator.align_dld_sectors()``.
1660
        """
1661
        if verbose is None:
1✔
1662
            verbose = self.verbose
1✔
1663

1664
        tof_column = self._config["dataframe"]["tof_column"]
1✔
1665

1666
        if self._dataframe is not None:
1✔
1667
            if verbose:
1✔
1668
                print("Aligning 8s sectors of dataframe")
1✔
1669
            # TODO assert order of execution through metadata
1670

1671
            df, metadata = self.ec.align_dld_sectors(
1✔
1672
                df=self._dataframe,
1673
                sector_delays=sector_delays,
1674
                **kwds,
1675
            )
1676
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1677
                tdf, _ = self.ec.align_dld_sectors(
×
1678
                    df=self._timed_dataframe,
1679
                    sector_delays=sector_delays,
1680
                    **kwds,
1681
                )
1682

1683
            self._attributes.add(
1✔
1684
                metadata,
1685
                "dld_sector_alignment",
1686
                duplicate_policy="raise",
1687
            )
1688
            self._dataframe = df
1✔
1689
            if self._timed_dataframe is not None and tof_column in self._timed_dataframe.columns:
1✔
1690
                self._timed_dataframe = tdf
×
1691
        else:
1692
            raise ValueError("No dataframe loaded!")
×
1693
        if preview:
1✔
1694
            print(self._dataframe.head(10))
×
1695
        else:
1696
            if verbose:
1✔
1697
                print(self._dataframe)
1✔
1698

1699
    # Delay calibration function
1700
    def calibrate_delay_axis(
1✔
1701
        self,
1702
        delay_range: tuple[float, float] = None,
1703
        datafile: str = None,
1704
        preview: bool = False,
1705
        verbose: bool = None,
1706
        **kwds,
1707
    ):
1708
        """Append delay column to dataframe. Either provide delay ranges, or read
1709
        them from a file.
1710

1711
        Args:
1712
            delay_range (tuple[float, float], optional): The scanned delay range in
1713
                picoseconds. Defaults to None.
1714
            datafile (str, optional): The file from which to read the delay ranges.
1715
                Defaults to None.
1716
            preview (bool, optional): Option to preview the first elements of the data frame.
1717
                Defaults to False.
1718
            verbose (bool, optional): Option to print out diagnostic information.
1719
                Defaults to config["core"]["verbose"].
1720
            **kwds: Keyword args passed to ``DelayCalibrator.append_delay_axis``.
1721
        """
1722
        if verbose is None:
1✔
1723
            verbose = self.verbose
1✔
1724

1725
        adc_column = self._config["dataframe"]["adc_column"]
1✔
1726
        if adc_column not in self._dataframe.columns:
1✔
1727
            raise ValueError(f"ADC column {adc_column} not found in dataframe, cannot calibrate!")
×
1728

1729
        if self._dataframe is not None:
1✔
1730
            if verbose:
1✔
1731
                print("Adding delay column to dataframe:")
1✔
1732

1733
            if delay_range is None and datafile is None:
1✔
1734
                if len(self.dc.calibration) == 0:
1✔
1735
                    try:
1✔
1736
                        datafile = self._files[0]
1✔
1737
                    except IndexError:
×
1738
                        print(
×
1739
                            "No datafile available, specify either",
1740
                            " 'datafile' or 'delay_range'",
1741
                        )
1742
                        raise
×
1743

1744
            df, metadata = self.dc.append_delay_axis(
1✔
1745
                self._dataframe,
1746
                delay_range=delay_range,
1747
                datafile=datafile,
1748
                verbose=verbose,
1749
                **kwds,
1750
            )
1751
            if self._timed_dataframe is not None and adc_column in self._timed_dataframe.columns:
1✔
1752
                tdf, _ = self.dc.append_delay_axis(
1✔
1753
                    self._timed_dataframe,
1754
                    delay_range=delay_range,
1755
                    datafile=datafile,
1756
                    verbose=False,
1757
                    **kwds,
1758
                )
1759

1760
            # Add Metadata
1761
            self._attributes.add(
1✔
1762
                metadata,
1763
                "delay_calibration",
1764
                duplicate_policy="overwrite",
1765
            )
1766
            self._dataframe = df
1✔
1767
            if self._timed_dataframe is not None and adc_column in self._timed_dataframe.columns:
1✔
1768
                self._timed_dataframe = tdf
1✔
1769
        else:
1770
            raise ValueError("No dataframe loaded!")
×
1771
        if preview:
1✔
1772
            print(self._dataframe.head(10))
1✔
1773
        else:
1774
            if self.verbose:
1✔
1775
                print(self._dataframe)
1✔
1776

1777
    def save_delay_calibration(
1✔
1778
        self,
1779
        filename: str = None,
1780
        overwrite: bool = False,
1781
    ) -> None:
1782
        """Save the generated delay calibration parameters to the folder config file.
1783

1784
        Args:
1785
            filename (str, optional): Filename of the config dictionary to save to.
1786
                Defaults to "sed_config.yaml" in the current folder.
1787
            overwrite (bool, optional): Option to overwrite the present dictionary.
1788
                Defaults to False.
1789
        """
1790
        if filename is None:
1✔
1791
            filename = "sed_config.yaml"
×
1792

1793
        if len(self.dc.calibration) == 0:
1✔
1794
            raise ValueError("No delay calibration parameters to save!")
×
1795
        calibration = {}
1✔
1796
        for key, value in self.dc.calibration.items():
1✔
1797
            if key == "datafile":
1✔
1798
                calibration[key] = value
1✔
1799
            elif key in ["adc_range", "delay_range", "delay_range_mm"]:
1✔
1800
                calibration[key] = [float(i) for i in value]
1✔
1801
            else:
1802
                calibration[key] = float(value)
1✔
1803

1804
        if "creation_date" not in calibration:
1✔
1805
            calibration["creation_date"] = datetime.now().timestamp()
×
1806

1807
        config = {
1✔
1808
            "delay": {
1809
                "calibration": calibration,
1810
            },
1811
        }
1812
        save_config(config, filename, overwrite)
1✔
1813

1814
    def add_delay_offset(
1✔
1815
        self,
1816
        constant: float = None,
1817
        flip_delay_axis: bool = None,
1818
        columns: str | Sequence[str] = None,
1819
        weights: float | Sequence[float] = 1.0,
1820
        reductions: str | Sequence[str] = None,
1821
        preserve_mean: bool | Sequence[bool] = False,
1822
        preview: bool = False,
1823
        verbose: bool = None,
1824
    ) -> None:
1825
        """Shift the delay axis of the dataframe by a constant or other columns.
1826

1827
        Args:
1828
            constant (float, optional): The constant to shift the delay axis by.
1829
            flip_delay_axis (bool, optional): Option to reverse the direction of the delay axis.
1830
            columns (str | Sequence[str], optional): Name of the column(s) to apply the shift from.
1831
            weights (float | Sequence[float], optional): weights to apply to the columns.
1832
                Can also be used to flip the sign (e.g. -1). Defaults to 1.
1833
            reductions (str | Sequence[str], optional): The reduction to apply to the column.
1834
                Should be an available method of dask.dataframe.Series. For example "mean". In this
1835
                case the function is applied to the column to generate a single value for the whole
1836
                dataset. If None, the shift is applied per-dataframe-row. Defaults to None.
1837
                Currently only "mean" is supported.
1838
            preserve_mean (bool | Sequence[bool], optional): Whether to subtract the mean of the
1839
                column before applying the shift. Defaults to False.
1840
            preview (bool, optional): Option to preview the first elements of the data frame.
1841
                Defaults to False.
1842
            verbose (bool, optional): Option to print out diagnostic information.
1843
                Defaults to config["core"]["verbose"].
1844

1845
        Raises:
1846
            ValueError: If the delay column is not in the dataframe.
1847
        """
1848
        if verbose is None:
1✔
1849
            verbose = self.verbose
1✔
1850

1851
        delay_column = self._config["dataframe"]["delay_column"]
1✔
1852
        if delay_column not in self._dataframe.columns:
1✔
1853
            raise ValueError(f"Delay column {delay_column} not found in dataframe! ")
1✔
1854

1855
        if self.dataframe is not None:
1✔
1856
            if verbose:
1✔
1857
                print("Adding delay offset to dataframe:")
1✔
1858
            df, metadata = self.dc.add_offsets(
1✔
1859
                df=self._dataframe,
1860
                constant=constant,
1861
                flip_delay_axis=flip_delay_axis,
1862
                columns=columns,
1863
                delay_column=delay_column,
1864
                weights=weights,
1865
                reductions=reductions,
1866
                preserve_mean=preserve_mean,
1867
                verbose=verbose,
1868
            )
1869
            if self._timed_dataframe is not None and delay_column in self._timed_dataframe.columns:
1✔
1870
                tdf, _ = self.dc.add_offsets(
1✔
1871
                    df=self._timed_dataframe,
1872
                    constant=constant,
1873
                    flip_delay_axis=flip_delay_axis,
1874
                    columns=columns,
1875
                    delay_column=delay_column,
1876
                    weights=weights,
1877
                    reductions=reductions,
1878
                    preserve_mean=preserve_mean,
1879
                    verbose=False,
1880
                )
1881

1882
            self._attributes.add(
1✔
1883
                metadata,
1884
                "delay_offset",
1885
                duplicate_policy="append",
1886
            )
1887
            self._dataframe = df
1✔
1888
            if self._timed_dataframe is not None and delay_column in self._timed_dataframe.columns:
1✔
1889
                self._timed_dataframe = tdf
1✔
1890
        else:
1891
            raise ValueError("No dataframe loaded!")
×
1892
        if preview:
1✔
1893
            print(self._dataframe.head(10))
1✔
1894
        else:
1895
            if verbose:
1✔
1896
                print(self._dataframe)
1✔
1897

1898
    def save_delay_offsets(
1✔
1899
        self,
1900
        filename: str = None,
1901
        overwrite: bool = False,
1902
    ) -> None:
1903
        """Save the generated delay calibration parameters to the folder config file.
1904

1905
        Args:
1906
            filename (str, optional): Filename of the config dictionary to save to.
1907
                Defaults to "sed_config.yaml" in the current folder.
1908
            overwrite (bool, optional): Option to overwrite the present dictionary.
1909
                Defaults to False.
1910
        """
1911
        if filename is None:
1✔
1912
            filename = "sed_config.yaml"
×
1913
        if len(self.dc.offsets) == 0:
1✔
1914
            raise ValueError("No delay offset parameters to save!")
×
1915

1916
        if "creation_date" not in self.ec.offsets.keys():
1✔
1917
            self.ec.offsets["creation_date"] = datetime.now().timestamp()
1✔
1918

1919
        config = {
1✔
1920
            "delay": {
1921
                "offsets": self.dc.offsets,
1922
            },
1923
        }
1924
        save_config(config, filename, overwrite)
1✔
1925
        print(f'Saved delay offset parameters to "{filename}".')
1✔
1926

1927
    def save_workflow_params(
1✔
1928
        self,
1929
        filename: str = None,
1930
        overwrite: bool = False,
1931
    ) -> None:
1932
        """run all save calibration parameter methods
1933

1934
        Args:
1935
            filename (str, optional): Filename of the config dictionary to save to.
1936
                Defaults to "sed_config.yaml" in the current folder.
1937
            overwrite (bool, optional): Option to overwrite the present dictionary.
1938
                Defaults to False.
1939
        """
1940
        for method in [
×
1941
            self.save_splinewarp,
1942
            self.save_transformations,
1943
            self.save_momentum_calibration,
1944
            self.save_energy_correction,
1945
            self.save_energy_calibration,
1946
            self.save_energy_offset,
1947
            self.save_delay_calibration,
1948
            self.save_delay_offsets,
1949
        ]:
1950
            try:
×
1951
                method(filename, overwrite)
×
1952
            except (ValueError, AttributeError, KeyError):
×
1953
                pass
×
1954

1955
    def add_jitter(
1✔
1956
        self,
1957
        cols: list[str] = None,
1958
        amps: float | Sequence[float] = None,
1959
        **kwds,
1960
    ):
1961
        """Add jitter to the selected dataframe columns.
1962

1963
        Args:
1964
            cols (list[str], optional): The columns onto which to apply jitter.
1965
                Defaults to config["dataframe"]["jitter_cols"].
1966
            amps (float | Sequence[float], optional): Amplitude scalings for the
1967
                jittering noise. If one number is given, the same is used for all axes.
1968
                For uniform noise (default) it will cover the interval [-amp, +amp].
1969
                Defaults to config["dataframe"]["jitter_amps"].
1970
            **kwds: additional keyword arguments passed to ``apply_jitter``.
1971
        """
1972
        if cols is None:
1✔
1973
            cols = self._config["dataframe"]["jitter_cols"]
1✔
1974
        for loc, col in enumerate(cols):
1✔
1975
            if col.startswith("@"):
1✔
1976
                cols[loc] = self._config["dataframe"].get(col.strip("@"))
1✔
1977

1978
        if amps is None:
1✔
1979
            amps = self._config["dataframe"]["jitter_amps"]
1✔
1980

1981
        self._dataframe = self._dataframe.map_partitions(
1✔
1982
            apply_jitter,
1983
            cols=cols,
1984
            cols_jittered=cols,
1985
            amps=amps,
1986
            **kwds,
1987
        )
1988
        if self._timed_dataframe is not None:
1✔
1989
            cols_timed = cols.copy()
1✔
1990
            for col in cols:
1✔
1991
                if col not in self._timed_dataframe.columns:
1✔
1992
                    cols_timed.remove(col)
×
1993

1994
            if cols_timed:
1✔
1995
                self._timed_dataframe = self._timed_dataframe.map_partitions(
1✔
1996
                    apply_jitter,
1997
                    cols=cols_timed,
1998
                    cols_jittered=cols_timed,
1999
                )
2000
        metadata = []
1✔
2001
        for col in cols:
1✔
2002
            metadata.append(col)
1✔
2003
        # TODO: allow only appending if columns are not jittered yet
2004
        self._attributes.add(metadata, "jittering", duplicate_policy="append")
1✔
2005

2006
    def add_time_stamped_data(
1✔
2007
        self,
2008
        dest_column: str,
2009
        time_stamps: np.ndarray = None,
2010
        data: np.ndarray = None,
2011
        archiver_channel: str = None,
2012
        **kwds,
2013
    ):
2014
        """Add data in form of timestamp/value pairs to the dataframe using interpolation to the
2015
        timestamps in the dataframe. The time-stamped data can either be provided, or fetched from
2016
        an EPICS archiver instance.
2017

2018
        Args:
2019
            dest_column (str): destination column name
2020
            time_stamps (np.ndarray, optional): Time stamps of the values to add. If omitted,
2021
                time stamps are retrieved from the epics archiver
2022
            data (np.ndarray, optional): Values corresponding at the time stamps in time_stamps.
2023
                If omitted, data are retrieved from the epics archiver.
2024
            archiver_channel (str, optional): EPICS archiver channel from which to retrieve data.
2025
                Either this or data and time_stamps have to be present.
2026
            **kwds: additional keyword arguments passed to ``add_time_stamped_data``.
2027
        """
2028
        time_stamp_column = kwds.pop(
1✔
2029
            "time_stamp_column",
2030
            self._config["dataframe"].get("time_stamp_alias", ""),
2031
        )
2032

2033
        if time_stamps is None and data is None:
1✔
2034
            if archiver_channel is None:
×
2035
                raise ValueError(
×
2036
                    "Either archiver_channel or both time_stamps and data have to be present!",
2037
                )
2038
            if self.loader.__name__ != "mpes":
×
2039
                raise NotImplementedError(
×
2040
                    "This function is currently only implemented for the mpes loader!",
2041
                )
2042
            ts_from, ts_to = cast(MpesLoader, self.loader).get_start_and_end_time()
×
2043
            # get channel data with +-5 seconds safety margin
2044
            time_stamps, data = get_archiver_data(
×
2045
                archiver_url=self._config["metadata"].get("archiver_url", ""),
2046
                archiver_channel=archiver_channel,
2047
                ts_from=ts_from - 5,
2048
                ts_to=ts_to + 5,
2049
            )
2050

2051
        self._dataframe = add_time_stamped_data(
1✔
2052
            self._dataframe,
2053
            time_stamps=time_stamps,
2054
            data=data,
2055
            dest_column=dest_column,
2056
            time_stamp_column=time_stamp_column,
2057
            **kwds,
2058
        )
2059
        if self._timed_dataframe is not None:
1✔
2060
            if time_stamp_column in self._timed_dataframe:
1✔
2061
                self._timed_dataframe = add_time_stamped_data(
1✔
2062
                    self._timed_dataframe,
2063
                    time_stamps=time_stamps,
2064
                    data=data,
2065
                    dest_column=dest_column,
2066
                    time_stamp_column=time_stamp_column,
2067
                    **kwds,
2068
                )
2069
        metadata: list[Any] = []
1✔
2070
        metadata.append(dest_column)
1✔
2071
        metadata.append(time_stamps)
1✔
2072
        metadata.append(data)
1✔
2073
        self._attributes.add(metadata, "time_stamped_data", duplicate_policy="append")
1✔
2074

2075
    def pre_binning(
1✔
2076
        self,
2077
        df_partitions: int | Sequence[int] = 100,
2078
        axes: list[str] = None,
2079
        bins: list[int] = None,
2080
        ranges: Sequence[tuple[float, float]] = None,
2081
        **kwds,
2082
    ) -> xr.DataArray:
2083
        """Function to do an initial binning of the dataframe loaded to the class.
2084

2085
        Args:
2086
            df_partitions (int | Sequence[int], optional): Number of dataframe partitions to
2087
                use for the initial binning. Defaults to 100.
2088
            axes (list[str], optional): Axes to bin.
2089
                Defaults to config["momentum"]["axes"].
2090
            bins (list[int], optional): Bin numbers to use for binning.
2091
                Defaults to config["momentum"]["bins"].
2092
            ranges (Sequence[tuple[float, float]], optional): Ranges to use for binning.
2093
                Defaults to config["momentum"]["ranges"].
2094
            **kwds: Keyword argument passed to ``compute``.
2095

2096
        Returns:
2097
            xr.DataArray: pre-binned data-array.
2098
        """
2099
        if axes is None:
1✔
2100
            axes = self._config["momentum"]["axes"]
1✔
2101
        for loc, axis in enumerate(axes):
1✔
2102
            if axis.startswith("@"):
1✔
2103
                axes[loc] = self._config["dataframe"].get(axis.strip("@"))
1✔
2104

2105
        if bins is None:
1✔
2106
            bins = self._config["momentum"]["bins"]
1✔
2107
        if ranges is None:
1✔
2108
            ranges_ = list(self._config["momentum"]["ranges"])
1✔
2109
            ranges_[2] = np.asarray(ranges_[2]) / self._config["dataframe"]["tof_binning"]
1✔
2110
            ranges = [cast(tuple[float, float], tuple(v)) for v in ranges_]
1✔
2111

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

2114
        return self.compute(
1✔
2115
            bins=bins,
2116
            axes=axes,
2117
            ranges=ranges,
2118
            df_partitions=df_partitions,
2119
            **kwds,
2120
        )
2121

2122
    def compute(
1✔
2123
        self,
2124
        bins: int | dict | tuple | list[int] | list[np.ndarray] | list[tuple] = 100,
2125
        axes: str | Sequence[str] = None,
2126
        ranges: Sequence[tuple[float, float]] = None,
2127
        normalize_to_acquisition_time: bool | str = False,
2128
        **kwds,
2129
    ) -> xr.DataArray:
2130
        """Compute the histogram along the given dimensions.
2131

2132
        Args:
2133
            bins (int | dict | tuple | list[int] | list[np.ndarray] | list[tuple], optional):
2134
                Definition of the bins. Can be any of the following cases:
2135

2136
                - an integer describing the number of bins in on all dimensions
2137
                - a tuple of 3 numbers describing start, end and step of the binning
2138
                  range
2139
                - a np.arrays defining the binning edges
2140
                - a list (NOT a tuple) of any of the above (int, tuple or np.ndarray)
2141
                - a dictionary made of the axes as keys and any of the above as values.
2142

2143
                This takes priority over the axes and range arguments. Defaults to 100.
2144
            axes (str | Sequence[str], optional): The names of the axes (columns)
2145
                on which to calculate the histogram. The order will be the order of the
2146
                dimensions in the resulting array. Defaults to None.
2147
            ranges (Sequence[tuple[float, float]], optional): list of tuples containing
2148
                the start and end point of the binning range. Defaults to None.
2149
            normalize_to_acquisition_time (bool | str): Option to normalize the
2150
                result to the acquisition time. If a "slow" axis was scanned, providing
2151
                the name of the scanned axis will compute and apply the corresponding
2152
                normalization histogram. Defaults to False.
2153
            **kwds: Keyword arguments:
2154

2155
                - **hist_mode**: Histogram calculation method. "numpy" or "numba". See
2156
                  ``bin_dataframe`` for details. Defaults to
2157
                  config["binning"]["hist_mode"].
2158
                - **mode**: Defines how the results from each partition are combined.
2159
                  "fast", "lean" or "legacy". See ``bin_dataframe`` for details.
2160
                  Defaults to config["binning"]["mode"].
2161
                - **pbar**: Option to show the tqdm progress bar. Defaults to
2162
                  config["binning"]["pbar"].
2163
                - **n_cores**: Number of CPU cores to use for parallelization.
2164
                  Defaults to config["core"]["num_cores"] or N_CPU-1.
2165
                - **threads_per_worker**: Limit the number of threads that
2166
                  multiprocessing can spawn per binning thread. Defaults to
2167
                  config["binning"]["threads_per_worker"].
2168
                - **threadpool_api**: The API to use for multiprocessing. "blas",
2169
                  "openmp" or None. See ``threadpool_limit`` for details. Defaults to
2170
                  config["binning"]["threadpool_API"].
2171
                - **df_partitions**: A sequence of dataframe partitions, or the
2172
                  number of the dataframe partitions to use. Defaults to all partitions.
2173
                - **filter**: A Sequence of Dictionaries with entries "col", "lower_bound",
2174
                  "upper_bound" to apply as filter to the dataframe before binning. The
2175
                  dataframe in the class remains unmodified by this.
2176

2177
                Additional kwds are passed to ``bin_dataframe``.
2178

2179
        Raises:
2180
            AssertError: Rises when no dataframe has been loaded.
2181

2182
        Returns:
2183
            xr.DataArray: The result of the n-dimensional binning represented in an
2184
            xarray object, combining the data with the axes.
2185
        """
2186
        assert self._dataframe is not None, "dataframe needs to be loaded first!"
1✔
2187

2188
        hist_mode = kwds.pop("hist_mode", self._config["binning"]["hist_mode"])
1✔
2189
        mode = kwds.pop("mode", self._config["binning"]["mode"])
1✔
2190
        pbar = kwds.pop("pbar", self._config["binning"]["pbar"])
1✔
2191
        num_cores = kwds.pop("num_cores", self._config["core"]["num_cores"])
1✔
2192
        threads_per_worker = kwds.pop(
1✔
2193
            "threads_per_worker",
2194
            self._config["binning"]["threads_per_worker"],
2195
        )
2196
        threadpool_api = kwds.pop(
1✔
2197
            "threadpool_API",
2198
            self._config["binning"]["threadpool_API"],
2199
        )
2200
        df_partitions: int | Sequence[int] = kwds.pop("df_partitions", None)
1✔
2201
        if isinstance(df_partitions, int):
1✔
2202
            df_partitions = list(range(0, min(df_partitions, self._dataframe.npartitions)))
1✔
2203
        if df_partitions is not None:
1✔
2204
            dataframe = self._dataframe.partitions[df_partitions]
1✔
2205
        else:
2206
            dataframe = self._dataframe
1✔
2207

2208
        filter_params = kwds.pop("filter", None)
1✔
2209
        if filter_params is not None:
1✔
2210
            try:
1✔
2211
                for param in filter_params:
1✔
2212
                    if "col" not in param:
1✔
2213
                        raise ValueError(
1✔
2214
                            "'col' needs to be defined for each filter entry! ",
2215
                            f"Not present in {param}.",
2216
                        )
2217
                    assert set(param.keys()).issubset({"col", "lower_bound", "upper_bound"})
1✔
2218
                    dataframe = apply_filter(dataframe, **param)
1✔
2219
            except AssertionError as exc:
1✔
2220
                invalid_keys = set(param.keys()) - {"lower_bound", "upper_bound"}
1✔
2221
                raise ValueError(
1✔
2222
                    "Only 'col', 'lower_bound' and 'upper_bound' allowed as filter entries. ",
2223
                    f"Parameters {invalid_keys} not valid in {param}.",
2224
                ) from exc
2225

2226
        self._binned = bin_dataframe(
1✔
2227
            df=dataframe,
2228
            bins=bins,
2229
            axes=axes,
2230
            ranges=ranges,
2231
            hist_mode=hist_mode,
2232
            mode=mode,
2233
            pbar=pbar,
2234
            n_cores=num_cores,
2235
            threads_per_worker=threads_per_worker,
2236
            threadpool_api=threadpool_api,
2237
            **kwds,
2238
        )
2239

2240
        for dim in self._binned.dims:
1✔
2241
            try:
1✔
2242
                self._binned[dim].attrs["unit"] = self._config["dataframe"]["units"][dim]
1✔
2243
            except KeyError:
1✔
2244
                pass
1✔
2245

2246
        self._binned.attrs["units"] = "counts"
1✔
2247
        self._binned.attrs["long_name"] = "photoelectron counts"
1✔
2248
        self._binned.attrs["metadata"] = self._attributes.metadata
1✔
2249

2250
        if normalize_to_acquisition_time:
1✔
2251
            if isinstance(normalize_to_acquisition_time, str):
1✔
2252
                axis = normalize_to_acquisition_time
1✔
2253
                print(
1✔
2254
                    f"Calculate normalization histogram for axis '{axis}'...",
2255
                )
2256
                self._normalization_histogram = self.get_normalization_histogram(
1✔
2257
                    axis=axis,
2258
                    df_partitions=df_partitions,
2259
                )
2260
                # if the axes are named correctly, xarray figures out the normalization correctly
2261
                self._normalized = self._binned / self._normalization_histogram
1✔
2262
                self._attributes.add(
1✔
2263
                    self._normalization_histogram.values,
2264
                    name="normalization_histogram",
2265
                    duplicate_policy="overwrite",
2266
                )
2267
            else:
2268
                acquisition_time = self.loader.get_elapsed_time(
×
2269
                    fids=df_partitions,
2270
                )
2271
                if acquisition_time > 0:
×
2272
                    self._normalized = self._binned / acquisition_time
×
2273
                self._attributes.add(
×
2274
                    acquisition_time,
2275
                    name="normalization_histogram",
2276
                    duplicate_policy="overwrite",
2277
                )
2278

2279
            self._normalized.attrs["units"] = "counts/second"
1✔
2280
            self._normalized.attrs["long_name"] = "photoelectron counts per second"
1✔
2281
            self._normalized.attrs["metadata"] = self._attributes.metadata
1✔
2282

2283
            return self._normalized
1✔
2284

2285
        return self._binned
1✔
2286

2287
    def get_normalization_histogram(
1✔
2288
        self,
2289
        axis: str = "delay",
2290
        use_time_stamps: bool = False,
2291
        **kwds,
2292
    ) -> xr.DataArray:
2293
        """Generates a normalization histogram from the timed dataframe. Optionally,
2294
        use the TimeStamps column instead.
2295

2296
        Args:
2297
            axis (str, optional): The axis for which to compute histogram.
2298
                Defaults to "delay".
2299
            use_time_stamps (bool, optional): Use the TimeStamps column of the
2300
                dataframe, rather than the timed dataframe. Defaults to False.
2301
            **kwds: Keyword arguments:
2302

2303
                - **df_partitions**: A sequence of dataframe partitions, or the
2304
                  number of the dataframe partitions to use. Defaults to all partitions.
2305

2306
        Raises:
2307
            ValueError: Raised if no data are binned.
2308
            ValueError: Raised if 'axis' not in binned coordinates.
2309
            ValueError: Raised if config["dataframe"]["time_stamp_alias"] not found
2310
                in Dataframe.
2311

2312
        Returns:
2313
            xr.DataArray: The computed normalization histogram (in TimeStamp units
2314
            per bin).
2315
        """
2316

2317
        if self._binned is None:
1✔
2318
            raise ValueError("Need to bin data first!")
1✔
2319
        if axis not in self._binned.coords:
1✔
2320
            raise ValueError(f"Axis '{axis}' not found in binned data!")
1✔
2321

2322
        df_partitions: int | Sequence[int] = kwds.pop("df_partitions", None)
1✔
2323
        if isinstance(df_partitions, int):
1✔
2324
            df_partitions = list(range(0, min(df_partitions, self._dataframe.npartitions)))
1✔
2325
        if use_time_stamps or self._timed_dataframe is None:
1✔
2326
            if df_partitions is not None:
1✔
2327
                self._normalization_histogram = normalization_histogram_from_timestamps(
1✔
2328
                    self._dataframe.partitions[df_partitions],
2329
                    axis,
2330
                    self._binned.coords[axis].values,
2331
                    self._config["dataframe"]["time_stamp_alias"],
2332
                )
2333
            else:
2334
                self._normalization_histogram = normalization_histogram_from_timestamps(
×
2335
                    self._dataframe,
2336
                    axis,
2337
                    self._binned.coords[axis].values,
2338
                    self._config["dataframe"]["time_stamp_alias"],
2339
                )
2340
        else:
2341
            if df_partitions is not None:
1✔
2342
                self._normalization_histogram = normalization_histogram_from_timed_dataframe(
1✔
2343
                    self._timed_dataframe.partitions[df_partitions],
2344
                    axis,
2345
                    self._binned.coords[axis].values,
2346
                    self._config["dataframe"]["timed_dataframe_unit_time"],
2347
                )
2348
            else:
2349
                self._normalization_histogram = normalization_histogram_from_timed_dataframe(
×
2350
                    self._timed_dataframe,
2351
                    axis,
2352
                    self._binned.coords[axis].values,
2353
                    self._config["dataframe"]["timed_dataframe_unit_time"],
2354
                )
2355

2356
        return self._normalization_histogram
1✔
2357

2358
    def view_event_histogram(
1✔
2359
        self,
2360
        dfpid: int,
2361
        ncol: int = 2,
2362
        bins: Sequence[int] = None,
2363
        axes: Sequence[str] = None,
2364
        ranges: Sequence[tuple[float, float]] = None,
2365
        backend: str = "bokeh",
2366
        legend: bool = True,
2367
        histkwds: dict = None,
2368
        legkwds: dict = None,
2369
        **kwds,
2370
    ):
2371
        """Plot individual histograms of specified dimensions (axes) from a substituent
2372
        dataframe partition.
2373

2374
        Args:
2375
            dfpid (int): Number of the data frame partition to look at.
2376
            ncol (int, optional): Number of columns in the plot grid. Defaults to 2.
2377
            bins (Sequence[int], optional): Number of bins to use for the specified
2378
                axes. Defaults to config["histogram"]["bins"].
2379
            axes (Sequence[str], optional): Names of the axes to display.
2380
                Defaults to config["histogram"]["axes"].
2381
            ranges (Sequence[tuple[float, float]], optional): Value ranges of all
2382
                specified axes. Defaults to config["histogram"]["ranges"].
2383
            backend (str, optional): Backend of the plotting library
2384
                ('matplotlib' or 'bokeh'). Defaults to "bokeh".
2385
            legend (bool, optional): Option to include a legend in the histogram plots.
2386
                Defaults to True.
2387
            histkwds (dict, optional): Keyword arguments for histograms
2388
                (see ``matplotlib.pyplot.hist()``). Defaults to {}.
2389
            legkwds (dict, optional): Keyword arguments for legend
2390
                (see ``matplotlib.pyplot.legend()``). Defaults to {}.
2391
            **kwds: Extra keyword arguments passed to
2392
                ``sed.diagnostics.grid_histogram()``.
2393

2394
        Raises:
2395
            TypeError: Raises when the input values are not of the correct type.
2396
        """
2397
        if bins is None:
1✔
2398
            bins = self._config["histogram"]["bins"]
1✔
2399
        if axes is None:
1✔
2400
            axes = self._config["histogram"]["axes"]
1✔
2401
        axes = list(axes)
1✔
2402
        for loc, axis in enumerate(axes):
1✔
2403
            if axis.startswith("@"):
1✔
2404
                axes[loc] = self._config["dataframe"].get(axis.strip("@"))
1✔
2405
        if ranges is None:
1✔
2406
            ranges = list(self._config["histogram"]["ranges"])
1✔
2407
            for loc, axis in enumerate(axes):
1✔
2408
                if axis == self._config["dataframe"]["tof_column"]:
1✔
2409
                    ranges[loc] = np.asarray(ranges[loc]) / self._config["dataframe"]["tof_binning"]
1✔
2410
                elif axis == self._config["dataframe"]["adc_column"]:
1✔
NEW
2411
                    ranges[loc] = np.asarray(ranges[loc]) / self._config["dataframe"]["adc_binning"]
×
2412

2413
        input_types = map(type, [axes, bins, ranges])
1✔
2414
        allowed_types = [list, tuple]
1✔
2415

2416
        df = self._dataframe
1✔
2417

2418
        if not set(input_types).issubset(allowed_types):
1✔
2419
            raise TypeError(
×
2420
                "Inputs of axes, bins, ranges need to be list or tuple!",
2421
            )
2422

2423
        # Read out the values for the specified groups
2424
        group_dict_dd = {}
1✔
2425
        dfpart = df.get_partition(dfpid)
1✔
2426
        cols = dfpart.columns
1✔
2427
        for ax in axes:
1✔
2428
            group_dict_dd[ax] = dfpart.values[:, cols.get_loc(ax)]
1✔
2429
        group_dict = ddf.compute(group_dict_dd)[0]
1✔
2430

2431
        # Plot multiple histograms in a grid
2432
        grid_histogram(
1✔
2433
            group_dict,
2434
            ncol=ncol,
2435
            rvs=axes,
2436
            rvbins=bins,
2437
            rvranges=ranges,
2438
            backend=backend,
2439
            legend=legend,
2440
            histkwds=histkwds,
2441
            legkwds=legkwds,
2442
            **kwds,
2443
        )
2444

2445
    def save(
1✔
2446
        self,
2447
        faddr: str,
2448
        **kwds,
2449
    ):
2450
        """Saves the binned data to the provided path and filename.
2451

2452
        Args:
2453
            faddr (str): Path and name of the file to write. Its extension determines
2454
                the file type to write. Valid file types are:
2455

2456
                - "*.tiff", "*.tif": Saves a TIFF stack.
2457
                - "*.h5", "*.hdf5": Saves an HDF5 file.
2458
                - "*.nxs", "*.nexus": Saves a NeXus file.
2459

2460
            **kwds: Keyword arguments, which are passed to the writer functions:
2461
                For TIFF writing:
2462

2463
                - **alias_dict**: Dictionary of dimension aliases to use.
2464

2465
                For HDF5 writing:
2466

2467
                - **mode**: hdf5 read/write mode. Defaults to "w".
2468

2469
                For NeXus:
2470

2471
                - **reader**: Name of the pynxtools reader to use.
2472
                  Defaults to config["nexus"]["reader"]
2473
                - **definition**: NeXus application definition to use for saving.
2474
                  Must be supported by the used ``reader``. Defaults to
2475
                  config["nexus"]["definition"]
2476
                - **input_files**: A list of input files to pass to the reader.
2477
                  Defaults to config["nexus"]["input_files"]
2478
                - **eln_data**: An electronic-lab-notebook file in '.yaml' format
2479
                  to add to the list of files to pass to the reader.
2480
        """
2481
        if self._binned is None:
1✔
2482
            raise NameError("Need to bin data first!")
1✔
2483

2484
        if self._normalized is not None:
1✔
2485
            data = self._normalized
×
2486
        else:
2487
            data = self._binned
1✔
2488

2489
        extension = pathlib.Path(faddr).suffix
1✔
2490

2491
        if extension in (".tif", ".tiff"):
1✔
2492
            to_tiff(
1✔
2493
                data=data,
2494
                faddr=faddr,
2495
                **kwds,
2496
            )
2497
        elif extension in (".h5", ".hdf5"):
1✔
2498
            to_h5(
1✔
2499
                data=data,
2500
                faddr=faddr,
2501
                **kwds,
2502
            )
2503
        elif extension in (".nxs", ".nexus"):
1✔
2504
            try:
1✔
2505
                reader = kwds.pop("reader", self._config["nexus"]["reader"])
1✔
2506
                definition = kwds.pop(
1✔
2507
                    "definition",
2508
                    self._config["nexus"]["definition"],
2509
                )
2510
                input_files = kwds.pop(
1✔
2511
                    "input_files",
2512
                    self._config["nexus"]["input_files"],
2513
                )
2514
            except KeyError as exc:
×
2515
                raise ValueError(
×
2516
                    "The nexus reader, definition and input files need to be provide!",
2517
                ) from exc
2518

2519
            if isinstance(input_files, str):
1✔
2520
                input_files = [input_files]
1✔
2521

2522
            if "eln_data" in kwds:
1✔
2523
                input_files.append(kwds.pop("eln_data"))
×
2524

2525
            to_nexus(
1✔
2526
                data=data,
2527
                faddr=faddr,
2528
                reader=reader,
2529
                definition=definition,
2530
                input_files=input_files,
2531
                **kwds,
2532
            )
2533

2534
        else:
2535
            raise NotImplementedError(
1✔
2536
                f"Unrecognized file format: {extension}.",
2537
            )
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