io.py 26.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/

__authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "06/12/2019"

import logging
31
from datetime import datetime
32
import h5py
33
import numpy
34
from silx.io.dictdump import dicttoh5, h5todict
35
from silx.io.url import DataUrl
36
from silx.utils.enum import Enum
37
from est.units import ur
38
39
40
from est.core.types.dim import Dim
from est.core.types import Spectra
from est.io.utils.spec import read_spectrum as read_spec_spectrum
41
from est.io.utils import get_data
42
import silx.io.h5py_utils
43
from silx.io.h5py_utils import File as HDF5File
44
from est import settings
45

46
try:
payno's avatar
payno committed
47
    from est.io.utils.larch import read_ascii as larch_read_ascii
48
49
50
51
except ImportError:
    has_larch = False
else:
    has_larch = True
52

53
54
55
_logger = logging.getLogger(__name__)


56
class InputType(Enum):
payno's avatar
payno committed
57
58
59
60
    dat_spectrum = "*.dat"  # contains one spectrum
    hdf5_spectra = "*.h5"  # contains several spectra
    xmu_spectrum = "*.xmu"  # contains one spectrum
    csv_spectrum = "*.csv"  # two columns, comma separated
61
62


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def move_axis_to_standard(spectra, dimensions):
    # make sure all dimensions are defined
    for dim in Dim:
        if dim not in dimensions:
            err = "%s is not defined in the dimensions" % dim
            raise ValueError(err)
    # fit spectra according to dimension
    src_axis = (
        dimensions.index(Dim.DIM_2),
        dimensions.index(Dim.DIM_1),
        dimensions.index(Dim.DIM_0),
    )
    dst_axis = (0, 1, 2)
    _logger.warning("move axis for spectra, from %s to %s" % (src_axis, dst_axis))
    if isinstance(spectra, Spectra):
        spectra.data = numpy.moveaxis(spectra.data, src_axis, dst_axis)
    elif isinstance(spectra, numpy.ndarray):
        spectra = numpy.moveaxis(spectra, src_axis, dst_axis)
    return spectra


84
def load_data(
85
86
87
88
89
90
    data_url: DataUrl,
    name: str,
    dimensions: tuple,
    columns_names=None,
    energy_unit=ur.eV,
    timeout=settings.DEFAULT_READ_TIMEOUT,
91
):
92
93
94
95
96
97
98
99
    """
    Load a specific data from an url. Manage the different scheme (silx, fabio,
    numpy, PyMca, xraylarch)

    :param data_url: silx DataUrl with path to the data
    :type: DataUrl
    :param str name: name of the data we want to load. Should be in
                    ('spectra', 'energy', 'configuration')
100
101
102
    :param Union[None,dict] columns_names: name of the column to pick for .dat
                                           files... Expect key 'mu' and
                                                    'energy' to be registered
103
104
105
106
107
    :return: data loaded
    :rtype: Union[None,dict,numpy.ndarray]
    """
    if data_url is None:
        return None
payno's avatar
fix CI    
payno committed
108
109
    from est.core.types import Dim  # avoid cyclic import

110
111
    if dimensions is not None:
        dimensions = tuple([Dim.from_value(dim) for dim in dimensions])
112
    assert isinstance(data_url, DataUrl)
113
    if data_url.scheme() in ("PyMca", "PyMca5", "Spec", "spec", "pymca"):
payno's avatar
payno committed
114

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        def get_energy_col_name():
            if columns_names is not None:
                return columns_names["energy"]
            if name == "energy" and data_url.data_path() is not None:
                return data_url.data_path()
            else:
                return None

        def get_absorption_col_name():
            if columns_names is not None:
                return columns_names["mu"]
            if name == "spectra" and data_url.data_path() is not None:
                return data_url.data_path()
            else:
                return None

131
132
        energy, mu = read_spec_spectrum(
            data_url.file_path(),
133
134
135
136
            energy_col_name=get_energy_col_name(),
            absorption_col_name=get_absorption_col_name(),
            monitor_col_name=columns_names["monitor"] if columns_names else None,
            scan_header_S=columns_names["scan_title"] if columns_names else None,
137
138
139
140
            energy_unit=energy_unit,
        )
        if name == "spectra":
            return mu.reshape(-1, 1, 1)
141
        else:
142
            return energy
payno's avatar
payno committed
143
    elif data_url.scheme() in ("larch", "xraylarch"):
144
        if has_larch is False:
payno's avatar
payno committed
145
            _logger.warning("Requires larch to load data from " "%s" % data_url.path())
146
147
            return None
        else:
payno's avatar
payno committed
148
            assert name in ("spectra", "energy")
149
150
151
            energy, mu = larch_read_ascii(
                xmu_file=data_url.file_path(), energy_unit=energy_unit
            )
152

payno's avatar
payno committed
153
            if name == "spectra":
154
                mu = numpy.ascontiguousarray(mu[:])
155
156
157
                return mu.reshape(mu.shape[0], 1, 1)
            else:
                return energy
payno's avatar
payno committed
158
    elif data_url.scheme() == "numpy":
159
        return move_axis_to_standard(numpy.load(data_url.file_path()), dimensions)
payno's avatar
payno committed
160
161
    elif data_url.scheme() == "est":
        assert name == "spectra"
payno's avatar
payno committed
162
163
        # TODO: might need to be improved because this is redefined each
        #  time. Not sure about the cost
164
165
166
167
168
169
170
171
172
        @silx.io.h5py_utils.retry(retry_timeout=timeout)
        def read_dataset(url):
            spectra = []
            with silx.io.h5py_utils.File(url.file_path(), "r") as hdf5:
                # get all possible entries
                entries = filter(
                    lambda x: isinstance(hdf5[x], h5py.Group)
                    and "est_saving_pt" in hdf5[x].keys(),
                    hdf5.keys(),
payno's avatar
payno committed
173
                )
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                entries = list(entries)
                if len(entries) == 0:
                    _logger.error(
                        "no spectra dataset found in the file", url.file_path()
                    )
                    return

                if len(entries) > 1:
                    _logger.warning(
                        "several entry detected, only one will be loaded:", entries[0]
                    )
                spectra_path = "/".join((entries[0], "est_saving_pt", "spectra"))
                node_spectra = hdf5[spectra_path]
                spectrum_indexes = list(node_spectra.keys())
                spectrum_indexes = list(map(lambda x: int(x), spectrum_indexes))
                spectrum_indexes.sort()
                from est.core.types import Spectrum

                for index in spectrum_indexes:
                    spectrum_path = "/".join((spectra_path, str(index)))
                    dict_ = h5todict(
                        h5file=url.file_path(), path=spectrum_path, asarray=False
                    )
                    spectrum = Spectrum().load_frm_dict(dict_)
                    spectra.append(spectrum)
                return spectra

        spectra = read_dataset(data_url)
202
        return Spectra(energy=spectra[0].energy, spectra=spectra)
203
204
    else:
        if data_url.is_valid():
payno's avatar
payno committed
205
206
            # TODO: might need to be improved because this is redefined each
            #  time. Not sure about the cost
207
208
209
210
            @silx.io.h5py_utils.retry(retry_timeout=timeout)
            def read_dataset(url):
                return get_data(url)

211
            try:
212
                data = read_dataset(data_url)
213
214
            except ValueError as e:
                _logger.error(e)
Mauro Rovezzi's avatar
Mauro Rovezzi committed
215
            else:
payno's avatar
payno committed
216
                if name == "spectra":
Mauro Rovezzi's avatar
Mauro Rovezzi committed
217
218
                    if data.ndim == 1:
                        return data.reshape(data.shape[0], 1, 1)
219
                    elif data.ndim == 3:
payno's avatar
payno committed
220
                        return move_axis_to_standard(data, dimensions=dimensions)
Mauro Rovezzi's avatar
Mauro Rovezzi committed
221
                return data
222
        else:
223
224
225
            _logger.warning(
                "invalid url for {}: {}  will not load it".format(name, data_url)
            )
226
227


228
def read_xas(information, timeout=settings.DEFAULT_READ_TIMEOUT):
229
    """
230
231
    Read the given spectra, configuration... from the provided input
    Information
232

233
    :param InputInformation informationUnion:
234

235
    :return: spectra, energy, configuration
236
    """
payno's avatar
payno committed
237

238
239
240
    def get_url(original_url, name):
        url_ = original_url
        if type(url_) is str:
241
242
            try:
                url_ = DataUrl(path=url_)
243
            except Exception:
payno's avatar
payno committed
244
                url_ = DataUrl(file_path=url_, scheme="PyMca")
245

246
        if not isinstance(url_, DataUrl):
payno's avatar
payno committed
247
            raise TypeError("given input for {} is invalid ({})".format(name, url_))
248
249
        return url_

250
251
252
    _spectra_url = get_url(original_url=information.spectra_url, name="spectra")
    _energy_url = get_url(original_url=information.channel_url, name="energy")
    _config_url = information.config_url
payno's avatar
payno committed
253
    if type(_config_url) is str and _config_url == "":
254
        _config_url = None
255
    if not (_config_url is None or isinstance(_config_url, DataUrl)):
payno's avatar
payno committed
256
        raise TypeError("given input for configuration is invalid")
257

258
    from est.core.types import Dim  # avoid cyclic import
payno's avatar
payno committed
259

260
261
262
    # this should be extractable and done in the InputInformation class
    dimensions_ = information.dimensions
    if dimensions_ is None:
263
        dimensions_ = (Dim.DIM_2, Dim.DIM_1, Dim.DIM_0)
264
265
    else:
        dimensions_ = []
266
        for dim in information.dimensions:
267
            dimensions_.append(Dim.from_value(dim))
268
269
270
    spectra = load_data(
        _spectra_url,
        name="spectra",
271
        dimensions=dimensions_,
272
273
        columns_names=information.columns_names,
        energy_unit=information.energy_unit,
274
        timeout=timeout,
275
    )
276
277
278
    energy = load_data(
        _energy_url,
        name="energy",
279
        dimensions=dimensions_,
280
281
        columns_names=information.columns_names,
        energy_unit=information.energy_unit,
282
        timeout=timeout,
283
284
285
286
    )
    configuration = load_data(
        _config_url,
        name="configuration",
287
        dimensions=dimensions_,
288
289
        columns_names=information.columns_names,
        energy_unit=information.energy_unit,
290
        timeout=timeout,
payno's avatar
payno committed
291
    )
292

293
294
    if energy is None:
        raise ValueError("Unable to load energy from {}".format(_energy_url))
295
    if not energy.ndim == 1:
payno's avatar
payno committed
296
        raise ValueError("Energy / channel is not 1D")
payno's avatar
payno committed
297
298
299
    if energy.shape[0] > spectra.shape[0]:
        energy = energy[: spectra.shape[0]]
        _logger.warning("energy has less value than spectra. Clip energy.")
300
    if not energy.shape[0] == spectra.shape[0]:
payno's avatar
payno committed
301
302
303
304
        err = "Energy / channel and spectra dim1 have incoherent length (%s vs %s)" % (
            energy.shape[0],
            spectra.shape[0],
        )
305
        raise ValueError(err)
306
    return spectra, energy * information.energy_unit, configuration
307
308


payno's avatar
payno committed
309
def write_xas_proc(
310
311
312
313
314
315
316
317
    h5_file,
    entry,
    process,
    results,
    processing_order,
    plots,
    data_path="/",
    overwrite=True,
payno's avatar
payno committed
318
):
319
320
321
322
323
    """
    Write a xas :class:`.Process` into .h5

    :param str h5_file: path to the hdf5 file
    :param str entry: entry name
324
325
    :param process: process executed
    :type: :class:`.Process`
326
    :param results: process result data
327
328
329
330
331
    :type: numpy.ndarray
    :param processing_order: processing order of treatment
    :type: int
    :param data_path: path to store the data
    :type: str
332
    """
333
334
    if plots is None:
        plots = tuple()
payno's avatar
payno committed
335
    process_name = "xas_process_" + str(processing_order)
336
    # write the xasproc default information
337
    with HDF5File(h5_file, "a") as h5f:
payno's avatar
payno committed
338
        nx_entry = h5f.require_group("/".join((data_path, entry)))
339
340
        nx_entry.attrs["NX_class"] = "NXentry"

341
        nx_process = nx_entry.require_group(process_name)
payno's avatar
payno committed
342
        nx_process.attrs["NX_class"] = "NXprocess"
343
        if overwrite:
payno's avatar
payno committed
344
345
346
347
348
349
350
351
            for key in (
                "program",
                "version",
                "date",
                "processing_order",
                "class_instance",
                "ft",
            ):
352
353
                if key in nx_process:
                    del nx_process[key]
payno's avatar
payno committed
354
355
356
357
        nx_process["program"] = process.program_name()
        nx_process["version"] = process.program_version()
        nx_process["date"] = datetime.now().replace(microsecond=0).isoformat()
        nx_process["processing_order"] = numpy.int32(processing_order)
payno's avatar
payno committed
358
        _class = process.__class__
payno's avatar
payno committed
359
        nx_process["class_instance"] = ".".join((_class.__module__, _class.__name__))
360

payno's avatar
payno committed
361
362
363
        nx_data = nx_entry.require_group("data")
        nx_data.attrs["NX_class"] = "NXdata"
        nx_data.attrs["signal"] = "data"
364
        nx_process_path = nx_process.name
365

366
367
    if isinstance(results, numpy.ndarray):
        data_ = {"data": results}
368
    else:
369
        data_ = results
370

371
372
373
    def get_interpretation(my_data):
        """Return hdf5 attribute for this type of data"""
        if isinstance(my_data, numpy.ndarray):
374
            if my_data.ndim == 1:
payno's avatar
payno committed
375
                return "spectrum"
376
            elif my_data.ndim in (2, 3):
payno's avatar
payno committed
377
                return "image"
378
379
        return None

380
381
382
383
384
385
386
387
    def get_path_to_result(res_name):
        res_name = res_name.replace(".", "/")
        path = "/".join((entry, process_name, "results", res_name))
        if path.startswith("/"):
            path = "/" + path
        return path

    # save results
388
    def save_key(key_path, value, attrs):
389
        """Save the given value to the associated path. Manage numpy arrays
390
391
392
393
394
395
        and dictionaries.
        """
        if attrs is not None:
            assert value is None, "can save value or attribute not both"
        if value is not None:
            assert attrs is None, "can save value or attribute not both"
payno's avatar
payno committed
396
        key_path = key_path.replace(".", "/")
397
398
        # save if is dict
        if isinstance(value, dict):
payno's avatar
payno committed
399
400
            h5_path = "/".join((entry, process_name, key_path))
            dicttoh5(
401
402
403
404
405
                value,
                h5file=h5_file,
                h5path=h5_path,
                overwrite_data=True,
                mode="a",
payno's avatar
payno committed
406
            )
407
        else:
408
            with HDF5File(h5_file, "a") as h5f:
409
                nx_process = h5f.require_group(nx_process_path)
410
411
412
413
                if attrs is None:
                    try:
                        nx_process[key_path] = value
                    except TypeError as e:
414
                        _logger.warning(
415
416
417
418
419
420
421
422
423
                            "Unable to write at {} reason is {}"
                            "".format(str(key_path), str(e))
                        )
                    else:
                        interpretation = get_interpretation(value)
                        if interpretation:
                            nx_process[key_path].attrs[
                                "interpretation"
                            ] = interpretation
424
                else:
425
426
427
428
429
                    for key, value in attrs.items():
                        try:
                            nx_process[key_path].attrs[key] = value
                        except Exception as e:
                            _logger.warning(e)
430
431

    for key, value in data_.items():
432
433
434
435
436
437
        if isinstance(key, tuple):
            key_path = "/".join(("results", key[0]))
            save_key(key_path=key_path, value=None, attrs={key[1]: value})
        else:
            key_path = "/".join(("results", str(key)))
            save_key(key_path=key_path, value=value, attrs=None)
438

439
440
441
442
443
    def save_plot(plot_name, plot):
        """save the given plot to an hdf5 group"""
        plot_name = plot_name.replace(".", "/")
        plot_path = "/".join((entry, process_name, "plots", plot_name))

444
        with HDF5File(h5_file, "a") as h5f:
445
446
447
448
449
450
451
452
453
454
455
456
457
458
            plot_group = h5f.require_group(plot_path)
            plot_group.attrs["NX_class"] = "NXdata"
            plot_group.attrs["interpretation"] = "spectrum"
            assert plot.signal is not None
            assert plot.axes is not None

            def link_dataset(dataset_to_link, name):
                # to insure silx isplotting it we should have curve as a 1D object
                # but by default we are handling a map of spectra. This is why we
                # need to duplicate data here
                if dataset_to_link.ndim == 1:
                    plot_group[name] = h5py.SoftLink(dataset_to_link.name)
                elif dataset_to_link.ndim == 2:
                    plot_group[name] = dataset_to_link[:, 0]
459
460
461
                    for key in ("units", "units_latex"):
                        if key in dataset_to_link.attrs:
                            plot_group[name].attrs[key] = dataset_to_link.attrs[key]
462
463
                elif dataset_to_link.ndim == 3:
                    plot_group[name] = dataset_to_link[:, 0, 0]
464
465
466
                    for key in ("units", "units_latex"):
                        if key in dataset_to_link.attrs:
                            plot_group[name].attrs[key] = dataset_to_link.attrs[key]
467
                else:
payno's avatar
payno committed
468
469
470
                    raise ValueError(
                        "Unable to handle dataset {}".format(dataset_to_link.name)
                    )
471
472
473

            # handle signal
            # plot is only handling 1D data
payno's avatar
payno committed
474
475
476
477
478
479
            try:
                signal_dataset = h5f[get_path_to_result(plot.signal)]
            except KeyError:
                _logger.info("{} is not available".format(plot.signal))
            else:
                link_dataset(dataset_to_link=signal_dataset, name=plot.signal)
480
481
482
            plot_group.attrs["signal"] = plot.signal
            # handle axes
            for axe in plot.axes:
payno's avatar
payno committed
483
484
485
486
487
488
                try:
                    axe_dataset = h5f[get_path_to_result(axe)]
                except KeyError:
                    _logger.info("{} is not available".format(axe))
                else:
                    link_dataset(dataset_to_link=axe_dataset, name=axe)
489
490
491
492
            plot_group.attrs["axes"] = plot.axes
            # handle auxiliary signals
            if plot.auxiliary_signals is not None:
                for aux_sig in plot.auxiliary_signals:
payno's avatar
payno committed
493
494
495
496
497
498
499
500
                    try:
                        aux_sig_dataset = h5f[get_path_to_result(aux_sig)]
                    except KeyError:
                        _logger.info("{} is not available".format(aux_sig))
                    else:
                        link_dataset(dataset_to_link=aux_sig_dataset, name=aux_sig)

                plot_group.attrs["auxiliary_signals"] = plot.auxiliary_signals
501
502
503
504
505
506
507
            # handle title(s)
            if plot.title is not None:
                plot_group.attrs["title"] = plot.title
            if plot.title_latex is not None:
                plot_group.attrs["title_latex"] = plot.title_latex

            # handle silx style
payno's avatar
payno committed
508
509
510
511
            if plot.silx_style is not None:
                import json

                plot_group.attrs["SILX_style"] = json.dumps(plot.silx_style)
512
513
514
515
516
517
518
519
520

    # save plots
    for i_plot, plot in enumerate(plots):
        plot_name = "plot_{}".format(i_plot)
        save_plot(plot_name=plot_name, plot=plot)

    # default plot will always be the first one
    if len(plots) > 0:
        plots_path = "/".join((entry, process_name, "plots"))
521
        with HDF5File(h5_file, "a") as h5f:
522
523
524
525
            plots_group = h5f.require_group(plots_path)
            plots_group.attrs["NX_class"] = "NXdata"
            plots_group.attrs["default"] = "plot_0"

526
    if process.getConfiguration() is not None:
payno's avatar
payno committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
        h5_path = "/".join((nx_process_path, "configuration"))
        dicttoh5(
            process.getConfiguration(),
            h5file=h5_file,
            h5path=h5_path,
            overwrite_data=True,
            mode="a",
        )


def write_xas(
    h5_file,
    entry,
    energy,
    mu,
    sample=None,
    start_time=None,
    data_path="/",
    title=None,
    definition=None,
    overwrite=True,
):
549
550
551
552
553
    """
    Write raw date in nexus format

    :param str h5_file: path to the hdf5 file
    :param str entry: entry name
554
555
556
557
558
559
    :param sample: definition of the sample
    :type: :class:`.Sample`
    :param energy: beam energy (1D)
    :type: numpy.ndarray
    :param mu: beam absorption (2D)
    :type: numpy.ndarray
560
    :param start_time:
561
    :param str data_path:
562
563
564
    :param str title: experiment title
    :param str definition: experiment definition
    """
565
    with HDF5File(h5_file, "w") as h5f:
payno's avatar
payno committed
566
        nx_entry = h5f.require_group("/".join((data_path, entry)))
567
568
569
        nx_entry.attrs["NX_class"] = "NXentry"

        # store energy
payno's avatar
payno committed
570
571
572
573
574
575
576
        nx_monochromator = nx_entry.require_group("monochromator")
        nx_monochromator.attrs["NX_class"] = "NXmonochromator"
        if overwrite and "energy" in nx_monochromator:
            del nx_monochromator["energy"]
        nx_monochromator["energy"] = energy
        nx_monochromator["energy"].attrs["interpretation"] = "spectrum"
        nx_monochromator["energy"].attrs["NX_class"] = "NXdata"
payno's avatar
payno committed
577
        nx_monochromator["energy"].attrs["unit"] = "eV"
578
579

        # store absorbed beam
payno's avatar
payno committed
580
581
582
583
584
585
586
        nx_absorbed_beam = nx_entry.require_group("absorbed_beam")
        nx_absorbed_beam.attrs["NX_class"] = "NXdetector"
        if overwrite and "data" in nx_absorbed_beam:
            del nx_absorbed_beam["data"]
        nx_absorbed_beam["data"] = mu
        nx_absorbed_beam["data"].attrs["interpretation"] = "image"
        nx_absorbed_beam["data"].attrs["NX_class"] = "NXdata"
587
588

        if sample:
payno's avatar
payno committed
589
590
591
592
593
594
595
596
            nx_sample = nx_entry.require_group("sample")
            nx_sample.attrs["NX_class"] = "NXsample"
            if overwrite and "name" in nx_sample:
                del nx_sample["name"]
            nx_sample["name"] = sample.name

        nx_data = nx_entry.require_group("data")
        nx_data.attrs["NX_class"] = "NXdata"
597
        # create some link on data
payno's avatar
payno committed
598
599
600
601
602
603
        if overwrite and "energy" in nx_data:
            del nx_data["energy"]
        nx_data["energy"] = h5py.SoftLink(nx_monochromator["energy"].name)
        if overwrite and "absorbed_beam" in nx_data:
            del nx_data["absorbed_beam"]
        nx_data["absorbed_beam"] = h5py.SoftLink(nx_absorbed_beam["data"].name)
604
605

        if start_time is not None:
payno's avatar
payno committed
606
607
608
            if overwrite and "start_time" in nx_entry:
                del nx_entry["start_time"]
            nx_entry["start_time"] = start_time
609
        if title is not None:
payno's avatar
payno committed
610
611
612
            if overwrite and "title" in nx_entry:
                del nx_entry["title"]
            nx_entry["title"] = title
613
        if definition is not None:
payno's avatar
payno committed
614
615
616
            if overwrite and "definition" in nx_entry:
                del nx_entry["definition"]
            nx_entry["definition"] = definition
617
618


619
620
621
622
623
624
625
626
627
def write_spectrum_saving_pt(h5_file, entry, obj, overwrite=True):
    """Save the current status of an est object

    :param str h5_file: path to the hdf5 file
    :param str entry: entry name
    :param obj: object to save.
    :param str obj_name: name of the object to store
    :param str data_path:
    """
payno's avatar
payno committed
628
    dicttoh5(obj, h5file=h5_file, h5path=entry, overwrite_data=True, mode="a")
629
630


631
632
633
def get_xasproc(h5_file, entry):
    """
    Return the list of all NXxasproc existing at the data_path level
634

635
636
    :param str h5_file: hdf5 file
    :param str entry: data location
637
638

    :return:
639
640
    :rtype: list
    """
payno's avatar
payno committed
641

642
643
644
    def copy_nx_xas_process(h5_group):
        """copy base information from nx_xas_process"""
        res = {}
payno's avatar
payno committed
645
646
647
648
649
650
651
652
653
        res["_h5py_path"] = h5_group.name
        relevant_keys = (
            "program",
            "version",
            "data",
            "parameters",
            "processing_order",
            "configuration",
            "class_instance",
654
            "plots",
payno's avatar
payno committed
655
        )
656
        from silx.io.dictdump import h5todict
payno's avatar
payno committed
657

658
659
660
        for key in h5_group.keys():
            # for now we don't want to copy the numpy array (data)
            if key in relevant_keys:
payno's avatar
payno committed
661
662
                if key == "configuration":
                    config_path = "/".join((h5_group.name, "configuration"))
663
                    res[key] = h5todict(h5_file, config_path, asarray=False)
664
665
666
667
668
                elif key == "plots":
                    plots_grp = h5_group["plots"]
                    res[key] = {}
                    for plot_key in plots_grp.keys():
                        res[key][plot_key] = dict(plots_grp[plot_key].attrs.items())
669
670
                else:
                    res[key] = h5_group[key][...]
671
672
673
        return res

    res = []
674
    with HDF5File(h5_file, "a") as h5f:
675
676
677
        try:
            root_group = h5f[entry]
        except KeyError:
payno's avatar
payno committed
678
            _logger.warning(entry + " does not exist in " + h5_file)
679
680
681
        else:
            for key in root_group.keys():
                elmt = root_group[key]
payno's avatar
payno committed
682
683
                if hasattr(elmt, "attrs") and "NX_class" in elmt.attrs:
                    if elmt.attrs["NX_class"] == "NXprocess":
684
685
                        nx_xas_proc = copy_nx_xas_process(elmt)
                        if len(nx_xas_proc) == 0:
payno's avatar
payno committed
686
687
688
689
                            _logger.warning(
                                "one xas process was not readable "
                                "from the hdf5 file at:" + key
                            )
690
691
692
693
694
                        else:
                            res.append(nx_xas_proc)
    return res


payno's avatar
payno committed
695
if __name__ == "__main__":
696
    import os
payno's avatar
payno committed
697
698
699
    from est.core.process.pymca.normalization import PyMca_normalization
    from est.core.process.pymca.exafs import PyMca_exafs
    from est.core.types import Sample
payno's avatar
payno committed
700
701

    h5_file = "test_xas_123.h5"
702
703
    if os.path.exists(h5_file):
        os.remove(h5_file)
payno's avatar
payno committed
704
    sample = Sample(name="mysample")
705
    data = numpy.random.rand(256 * 20 * 10)
706
    data = data.reshape((256, 20, 10))
707
    process_data = numpy.random.rand(256 * 20 * 10).reshape((256, 20, 10))
708
709
    energy = numpy.linspace(start=3.25, stop=3.69, num=256)

payno's avatar
payno committed
710
    write_xas(h5_file=h5_file, entry="scan1", sample=sample, energy=energy, mu=data)
711
712

    process_norm = PyMca_normalization()
payno's avatar
payno committed
713
714
715
716
    write_xas_proc(
        h5_file=h5_file,
        entry="scan1",
        process=process_norm,
717
        results=process_data,
payno's avatar
payno committed
718
719
        processing_order=1,
    )
720
    process_exafs = PyMca_exafs()
721
    process_data2 = numpy.random.rand(256 * 20 * 10).reshape((256, 20, 10))
payno's avatar
payno committed
722
723
724
725
    write_xas_proc(
        h5_file=h5_file,
        entry="scan1",
        process=process_exafs,
726
        results=process_data2,
payno's avatar
payno committed
727
728
        processing_order=2,
    )
729
730
731
732
733
734
735
736
737
738
739
740


def get_column_name(dat_file):
    from silx.io.spech5 import SpecH5
    from silx.io.spech5 import SpecFile

    spec_h5 = SpecH5(dat_file)
    spec_file = SpecFile(dat_file)


if __name__ == "__main__":
    get_column_name("specfiledata_tests.dat")