Source code for nxsblisswriter.NXSFile

#!/usr/bin/env python
#   This file is part of nexdatas - Tango Server for NeXus data writer
#
#    Copyright (C) 2026 DESY, Jan Kotanski <jkotan@mail.desy.de>
#
#    nexdatas is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    nexdatas is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with nexdatas.  If not, see <http://www.gnu.org/licenses/>.
#

""" Provides the access to a database with NDTS configuration files """

import functools
import time
import pathlib
from pninexus import nexus, h5cpp
import xml.etree.ElementTree as et
from lxml.etree import XMLParser
from lxml import etree
import numpy as np
import json
import os

# from blissdata.redis_engine.store import DataStore
# from blissdata.redis_engine.scan import ScanState
from blissdata.redis_engine.exceptions import EndOfStream
# from blissdata.redis_engine.exceptions import NoScanAvailable


ALLOWED_NXS_SURFIXES = {".nxs", ".h5", ".hdf5", ".nx"}

try:
    _npver = np.version.version.split(".")
    NPMAJOR = int(_npver[0])
except Exception:
    NPMAJOR = 1

utf8 = h5cpp.datatype.kVariableString
utf8.encoding = h5cpp.datatype.CharacterEncoding.UTF8

PTH = {
    "long": h5cpp.datatype.Integer,
    "str": utf8,
    "unicode": utf8,
    "ascii": h5cpp.datatype.kVariableString,
    "bool": h5cpp.datatype.kEBool,
    "int": h5cpp.datatype.kInt64,
    "int64": h5cpp.datatype.kInt64,
    "int32": h5cpp.datatype.kInt32,
    "int16": h5cpp.datatype.kInt16,
    "int8": h5cpp.datatype.kInt8,
    "uint": h5cpp.datatype.kInt64,
    "uint64": h5cpp.datatype.kUInt64,
    "uint32": h5cpp.datatype.kUInt32,
    "uint16": h5cpp.datatype.kUInt16,
    "uint8": h5cpp.datatype.kUInt8,
    "float": h5cpp.datatype.kFloat32,
    "float64": h5cpp.datatype.kFloat64,
    "float32": h5cpp.datatype.kFloat32,
    "string": h5cpp.datatype.kVariableString,
}

ATTRDESC = {
    "nexus_type": "type",
    "unit": "units",
    "depends_on": "depends_on",
    "trans_type": "transformation_type",
    "trans_vector": "vector",
    "trans_offset": "offset",
    # "source": "nexdatas_source",
    "strategy": "nexdatas_strategy",
}


NOATTRS = {"name", "label", "dtype", "value", "nexus_path",
           "shape", "stream", "__vmaps__", "__vmaps_shape__"}


[docs]def first(array): """ get first element if the only :param array: numpy array :type array: :class:`numpy.ndarray` :returns: first element of the array :type array: :obj:`any` """ try: if isinstance(array, np.ndarray) and len(array) == 1: return array[0] except Exception: try: if hasattr(array, "all"): if NPMAJOR < 2: array = array.all() if hasattr(array, "decode"): return array.decode() except Exception: pass return array
[docs]def create_nexus_file(scan, streams, default_nexus_path="/scan{serialno}:NXentry/" "instrument:NXinstrument/collection", vmaps_shape_plugins=None, vds_plugins=None): """ open nexus file :param scan: blissdata scan :type scan: :obj:`blissdata.redis_engine.scan.Scan` :param streams: tango-like steamset class :type streams: :class:`StreamSet` or :class:`tango.LatestDeviceImpl` :param default_nexus_path: default nexus path :type default_nexus_path: :obj:`str` :param vmaps_shape_plugins: vmaps_shape plugins :type vmaps_shape_plugins: :obj:`list` <:obj:`str`> :param vds_plugins: vds plugins :type vds_plugins: :obj:`list` <:obj:`str`> :returns: nexus file object :rtype: :obj:`NXSFile` """ fpath = pathlib.Path(scan.info["filename"]) if fpath.suffix not in ALLOWED_NXS_SURFIXES: fpath = fpath.with_suffix(".nxs") fdir = fpath.parent if not fdir.is_dir(): fdir.mkdir(parents=True) number = scan.number serialno = "" entryname = "entry" snapshot = {} si = scan.info if "snapshot" in si: snapshot = si["snapshot"] if serialno in snapshot.keys() and "value" in snapshot["serialno"]: serialno = snapshot["serialno"]["value"] if entryname in snapshot.keys() and "value" in snapshot["entryname"]: entryname = snapshot["entryname"]["value"] nxsfl = NXSFile(scan, fpath, streams, default_nexus_path.format( number=number, serialno=serialno, entryname=entryname), vmaps_shape_plugins, vds_plugins ) # ?? append mode if not fpath.exists(): nxsfl.create_file_structure() return nxsfl
[docs]class NXSFile: def __init__(self, scan, fpath, streams, default_nexus_path="/scan{serialno}:NXentry/" "instrument:NXinstrument/collection", vmaps_shape_plugins=None, vds_plugins=None, max_write_interval=1): """ constructor :param scan: blissdata scan :type scan: :obj:`blissdata.redis_engine.scan.Scan` :param fpath: nexus file path :type fpath: :obj:`pathlib.Path` :param streams: tango-like steamset class :type streams: :class:`StreamSet` or :class:`tango.LatestDeviceImpl` :param default_nexus_path: default nexus path :type default_nexus_path: :obj:`str` :param vmaps_shape_plugins: vmaps_shape plugins :type vmaps_shape_plugins: :obj:`list` <:obj:`str`> :param vds_plugins: vds plugins :type vds_plugins: :obj:`list` <:obj:`str`> :param max_write_interval: max write interval :type max_write_interval: :obj:`int` """ self.__scan = scan self.__fpath = fpath #: (:class:`StreamSet` or :class:`tango.LatestDeviceImpl`) stream set self._streams = streams self.__default_nexus_path = default_nexus_path self.__mfile = None self.__cursors = {} self.__nxfields = {} self.__lbnames = {} self.__last_write_time = 0 self.__max_write_interval = max_write_interval #: (:obj:`list` <:obj:`str`>) vmaps shape plugins self.__vmaps_shape_plugins = vmaps_shape_plugins or [] self.__vds = {} #: (:obj:`list` <:obj:`str`>) vds plugins self.__vds_plugins = vds_plugins or ["lima", "asapo_stream"] @functools.cached_property def channels(self): """ returns a list of channels with description :returns: list of channels descriptions :rtype: :obj:`list` <:obj: `dict` > """ return tuple(ch for ch in self.__scan.info["datadesc"].values()) @functools.cached_property def labels(self): """ returns a list of channels with description :returns: list of channel labels :rtype: :obj:`list` <:obj: `str` > """ labels = (ch["label"] for ch in self.channels) return tuple(label.replace(" ", "_") for label in labels)
[docs] def create_file_structure(self): """ create nexus structure """ si = self.__scan.info filename = str(self.__fpath.absolute()) snapshot = {} if "snapshot" in si: snapshot = si["snapshot"] xmls = None try: xmlc = snapshot["nxsdatawriter_xmlsettings"]["value"] except Exception as e: self._streams.error( "NXSFile::create_file_structure( )- %s" % (str(e))) xmlc = None if xmlc: xmlc1 = xmlc.replace('"NX_DATE_TIME"', '"NX_CHAR"') xmlc2 = xmlc1.replace('index="1"', 'index="0"').replace( 'index="2"', 'index="1"').replace('index="3"', 'index="2"') etroot = et.fromstring( xmlc2, parser=XMLParser(collect_ids=False)) etdims = etroot.findall(".//dimensions") for etdim in etdims: dparent = etdim.getparent() if dparent.tag in ["field", "vds"]: ddparent = dparent.getparent() ddparent.remove(dparent) xmls = etree.tostring(etroot, encoding='unicode', method='xml', pretty_print=True) self.__mfile = nexus.create_file(filename, h5cpp.file.AccessFlags.TRUNCATE) root = self.__mfile.root() if xmls: nexus.create_from_string(root, xmls)
[docs] def write_init_snapshot(self): """ write init data """ si = self.__scan.info root = self.__mfile.root() snapshot = {} if "snapshot" in si: snapshot = si["snapshot"] for ds, items in snapshot.items(): if not isinstance(items, list): items = [items] for item in items: strategy = None if "strategy" in item: strategy = item["strategy"] if not strategy or strategy in ["INIT"]: try: # print("WRITE", ds, strategy) self.write_snapshot_item( root, item, "%s/%s" % (self.__default_nexus_path, ds)) except Exception as e: self._streams.error( "NXSFile::write_init_snapshot() %s %s %s %s" % (ds, strategy, item, str(e))) break else: continue break
[docs] def prepareChannels(self): """ prepare cursors """ self.__cursors = {} self.__nxfields = {} # for key, stream in self.__scan.streams.items(): # - self.__cursors[key] = stream.cursor() for ch in self.channels: key = ch["label"] name = ch.get("name", key) if key in self.__lbnames: self.__lbnames[key].append(name) else: self.__lbnames[key] = [name] # print("CH", key, list(self.__scan.streams.keys())) nxpath = ch.get( 'nexus_path', "%s/%s" % (self.__default_nexus_path, key)) lnxpath = nxpath.split("/") h5path = "/".join([nd.split(":")[0] for nd in lnxpath]) if key in list(self.__scan.streams.keys()): stream = self.__scan.streams[key] self.__cursors[key] = stream.cursor() shape = [0] + list(stream.shape) chunk = [1] + list(stream.shape) dtype = str(stream.dtype) if hasattr(dtype, "__name__"): dtype = str(dtype.__name__) if dtype == "string": dtype = "str" root = self.__mfile.root() dataset = None try: self.__nxfields[name] = root.get_dataset(h5path) dataset = self.__nxfields[name] except Exception as e: if str(e).startswith("No node ["): # print("S", key, shape, chunk, stream.dtype, ch) if stream.plugin in self.__vds_plugins: self.__vds[key] = { "nxpath": lnxpath, "dtype": dtype} else: self.__nxfields[name] = self.create_groupfield( root, lnxpath, dtype, value=None, shape=shape, chunk=chunk) dataset = self.__nxfields[name] elif str(e).startswith("Node ["): self._streams.warn( "NXSFile::prepareChannels() - %s" % (str(e))) else: self._streams.error( "NXSFile::prepareChannels() - %s" % (str(e))) raise self.add_attributes(dataset, ch)
[docs] def updateVDS(self): """ prepare cursors """ si = self.__scan.info if "datadesc" not in si: return channels = si["datadesc"] for _, ch in channels.items(): try: key = ch["label"] nxpath = ch.get( 'nexus_path', "%s/%s" % (self.__default_nexus_path, key)) lnxpath = nxpath.split("/") if key not in list(self.__scan.streams.keys()): dtype = ch['dtype'] self.__vds[key] = { "nxpath": lnxpath, "dtype": dtype} _ = ch["__vmaps_shape__"] _ = ch["__vmaps__"] except Exception as e: self._streams.error( "NXSFile::prepareChannels() - %s" % (str(e)))
[docs] def add_attributes(self, dataset, item): """ add dataset attribute :param dataset: h5cpp dataset :type dataset: :class:`pninexus.h5cpp.node.Dataset` :param item: channel descrition :type item: :obj:`dict` <:obj:`str`, `any`> """ if dataset is not None: attrs = set(item.keys()) - NOATTRS am = dataset.attributes for anm in attrs: avl = item[anm] if isinstance(avl, list): av = avl[0] while isinstance(av, list) and len(av): av = av[0] dtp = str(type(av).__name__) elif hasattr(avl, "dtype"): dtp = str(avl.dtype.__name__) else: dtp = str(type(avl).__name__) nanm = ATTRDESC.get(anm, anm) try: self.write_attr(am, nanm, dtp, avl, item) except Exception as e: self._streams.error( "NXSFile::prepareChannels() " "- %s %s %s %s %s %s" % (am, nanm, dtp, avl, item, str(e)))
[docs] def write_scan_points(self): """ write step data """ now = time.monotonic() if (now - self.__last_write_time) < self.__max_write_interval: return rs = set() eos = set() eose = None for ch in self.channels: if "stream" in ch and ch["stream"] not in ["stream"]: self._streams.info( "NXSFile::write_scan_point() - " "SKIP {}".format(ch["label"])) continue try: if ch["label"] in eos: continue val = self.__cursors[ch["label"]].read() rs.add(ch["label"]) except EndOfStream as e: self._streams.debug( "NXSFile::write_scan_point() - " "End of stream for ct column {}".format(ch)) eose = e eos.add(ch["label"]) continue # raise try: try: key = ch["label"] values = val.get_data() except Exception as e: print(str(e)) continue # print("CHANNEL", ch["label"], ch["shape"], values) npoints = len(values) for name in self.__lbnames.get(key, [key]): if npoints: oldshape = \ self.__nxfields[name].dataspace.current_dimensions rank = len(oldshape) if rank: offset = [0] * rank block = list(oldshape) offset[0] = oldshape[0] block[0] = npoints selection = h5cpp.dataspace.Hyperslab( offset=offset, block=block) self.__nxfields[name].extent(0, npoints) # print(self.__nxfields[name].dataspace.current_dimensions) # print(offset, block) self.__nxfields[name].write(values, selection) except Exception as e: self._streams.error( "NXSFile::write_scan_points()- %s %s %s %s" % (ch, key, values, str(e))) # npoints = len(values[0]) # for i in range(npoints): self.__last_write_time = now if not len(rs): self._streams.info( "NXSFile::write_scan_point() - " "End of stream for all columns: %s" % (str(eos))) if eose is not None: raise eose else: raise EndOfStream("No active channels")
[docs] def write_final_snapshot(self): """ write final data """ root = self.__mfile.root() si = self.__scan.info snapshot = {} if "snapshot" in si: snapshot = si["snapshot"] for ds, items in snapshot.items(): if not isinstance(items, list): items = [items] for item in items: strategy = None if "strategy" in item: strategy = item["strategy"] if strategy in ["FINAL"]: try: # print("WRITE", ds, strategy) self.write_snapshot_item( root, item, "%s/%s" % (self.__default_nexus_path, ds)) except Exception as e: self._streams.error( "NXSFile::write_final_snapshot() %s %s %s %s" % (ds, strategy, item, str(e))) break else: continue break if "datadesc" not in si: return ddesc = si["datadesc"] # self._streams.info("CREATE VDS %s" % (self.__vds)) for key, vl in self.__vds.items(): if key not in ddesc: continue desc = ddesc[key] # self._streams.info("CREATE DESC %s" % (desc)) nxpath = vl["nxpath"] dtype = vl["dtype"] stream = self.__scan.streams[key] \ if key in self.__scan.streams else None shape = None if key in self.__vmaps_shape_plugins and "__vmaps_shape__" in desc: shape = desc["__vmaps_shape__"] elif stream is not None: shape = [len(stream)] + list(stream.shape) elif "__vmaps_shape__" in desc: shape = desc["__vmaps_shape__"] vmaps = [] if hasattr(stream, "info") and "format" in stream.info and \ stream.info["format"] in ["lima_v1"]: linfo = stream.info["lima_info"] fp = linfo["file_path"] fn = self.__fpath common_prefix = os.path.commonprefix( [os.path.split(fn)[0], fp]) if common_prefix in ["/", "", os.sep]: tfn = os.path.splitext(fn) ofp = fp.split(os.sep) file_pattern = os.sep.join([tfn[0], key, ofp[-1]]) else: file_pattern = os.path.relpath(fp, common_prefix) frame_per_acquisition = linfo["frame_per_acquisition"] # acquisition_offset = linfo["acquisition_offset"] file_offset = linfo["file_offset"] file_format = linfo["file_format"] data_path = linfo["data_path"] frame_per_file = linfo["frame_per_file"] vmaps = self.generate_vmaps( shape, frame_per_acquisition, file_offset, file_format, file_pattern, data_path, frame_per_file) elif "__vmaps__" in desc: vmaps = desc["__vmaps__"] root = self.__mfile.root() # self._streams.info( # "CREATE GROUP %s %s %s %s" % (nxpath, key, dtype, shape)) self.__nxfields[key] = self.create_groupvds( root, nxpath, dtype, shape, vmaps) self.add_attributes(self.__nxfields[key], desc)
[docs] def create_field(self, grp, name, dtype, value=None, shape=None, chunk=None): """ create field :param grp: nexus group :type grp: :class:`pninexus.h5cpp.node.Group` :param name: group name :type name: :obj:`str` :param dtype: nexus field type :type dtype: :obj:`str` :param shape: shape :type shape: :obj:`list` < :obj:`int` > :param chunk: chunk :type chunk: :obj:`list` < :obj:`int` > :returns: file tree field :rtype: :class:`pninexus.h5cpp.node.Dataset` """ # print("CREATE", name, dtype, value, shape, chunk) dcpl = h5cpp.property.DatasetCreationList() if shape is None and hasattr(value, "shape"): shape = value.shape elif dtype in ["str", "unicode", "string"]: dataspace = h5cpp.dataspace.Scalar() field = h5cpp.node.Dataset( grp, h5cpp.Path(name), PTH[dtype], dataspace, dcpl=dcpl) if value is not None: field.write(value) return field shape = shape or [1] dataspace = h5cpp.dataspace.Simple( tuple(shape), tuple([h5cpp.dataspace.UNLIMITED] * len(shape))) if chunk is None: chunk = [(dm if dm != 0 else 1) for dm in shape] dcpl.layout = h5cpp.property.DatasetLayout.CHUNKED dcpl.chunk = tuple(chunk) field = h5cpp.node.Dataset( grp, h5cpp.Path(name), PTH[dtype], dataspace, dcpl=dcpl) if value is not None: field.write(value) return field
[docs] def create_groupfield(self, root, lnxpath, dtype, value=None, shape=None, chunk=None): """ create field :param root: root object :type root: :class:`pninexus.h5cpp.node.Group` :param lnxpath: nexus path list :type lnxpath: :obj:`list` <:obj:`str`> :param dtype: nexus field type :type dtype: :obj:`str` :param value: field value :type value: :obj:`any` :param shape: shape :type shape: :obj:`list` < :obj:`int` > :param chunk: chunk :type chunk: :obj:`list` < :obj:`int` > :returns: nexus field :rtype: :class:`pninexus.h5cpp.node.Dataset` """ grp = root for gr in lnxpath[:-1]: gn = gr gt = None if ":" in gr: gn, gt = gr.split(":") if grp.has_group(gn): grp = grp.get_group(gn) else: grp = h5cpp.node.Group(grp, gn) if gt is not None: grp.attributes.create( "NX_class", h5cpp.datatype.kVariableString).write(gt) # print(gn) name = lnxpath[-1] if isinstance(value, list): value = np.array(value, dtype=dtype) # print("CREATE %s (%s)" % (nxpath, dtype)) dataset = self.create_field(grp, name, dtype, value, shape, chunk) return dataset
[docs] def add_vmap(self, vfl, vmap): """ create field :param n: group name :type n: :obj:`str` :param type_code: nexus field type :type type_code: :obj:`str` :param shape: shape :type shape: :obj:`list` < :obj:`int` > :returns: file tree field :rtype: :class:`pninexus.h5cpp.node.Dataset` """ lview = vmap["view"] fname = vmap["filename"] eview = vmap["sourceview"] path = vmap["path"] sds = eview["dataspace"] lds = lview["dataspace"] shape = lds["shape"] eshape = sds["shape"] h5_lds = h5cpp.dataspace.Simple(tuple(shape)) h5_sds = h5cpp.dataspace.Simple(tuple(eshape)) if "selection" in lview: selection = lview["selection"] h5_selection = h5cpp.dataspace.Hyperslab(**selection) h5_lview = h5cpp.dataspace.View(h5_lds, h5_selection) else: h5_lview = h5cpp.dataspace.View(h5_lds) if "selection" in eview: usel = eview["selection"] h5_usel = h5cpp.dataspace.Hyperslab(**usel) h5_eview = h5cpp.dataspace.View(h5_sds, h5_usel) else: h5_eview = h5cpp.dataspace.View(h5_sds) # self._streams.info("ADD %s %s " % (fname, path)) vfl.add(h5cpp.property.VirtualDataMap( h5_lview, str(fname), h5cpp.Path(path), h5_eview))
[docs] def generate_vmaps(self, shape, frame_per_acquisition, file_offset, file_format, file_pattern, data_path, frame_per_file): """ generate virtual map list :param shape: shape :type shape: :obj:`list` < :obj:`int` > :param frame_per_acquisition: frame per acquisition :type frame_per_acquisition: :obj:`int` :param file_offset: file offset :type file_offset: :obj:`int` :param file_format: file format :type file_format: :obj:`str` :param file_pattern: file pattern :type file_pattern: :obj:`str` :param data_path: nexus data path :type data_path: :obj:`str` :param frame_per_file: frame per file :type frame_per_file: :obj:`int` :returns: virtual map list :rtype: :obj:`list` <:obj:`dict`> """ vmaps = [] if file_format not in ["hdf5"] or not frame_per_acquisition \ or not data_path or not frame_per_file: return vmaps length = shape[0] acq_nb, remaining_scan_frame_nb = divmod(length, frame_per_acquisition) acq_files_nb, last_file_scan_frame_nb = divmod( frame_per_acquisition, frame_per_file) remaining_acq_files_nb, remaining_last_file_scan_frame_nb = divmod( remaining_scan_frame_nb, frame_per_file) acq_frames = [frame_per_file] * acq_files_nb if last_file_scan_frame_nb: acq_frames += [last_file_scan_frame_nb] remaining_frames = [frame_per_file] * remaining_acq_files_nb if remaining_last_file_scan_frame_nb: remaining_frames += [remaining_last_file_scan_frame_nb] frame_nb = [] for acq in range(acq_nb): frame_nb.extend(acq_frames) frame_nb.extend(remaining_frames) off = 0 for nid, nb in enumerate(frame_nb): vmap = {} fid = file_offset + nid try: fname = file_pattern % fid except Exception: fname = file_pattern vmap["class"] = "VirtualDataMap" vmap["filename"] = fname vmap["path"] = data_path vshape = shape[:] vshape[0] = nb offset = [0] * len(shape) offset[0] = off vmap["view"] = {"class": "View", "dataspace": {"class": "Simple", "shape": vshape}, "selection": {"block": vshape, "offset": offset, "stride": vshape, "count": [1] * len(vshape) } } vmap["sourceview"] = {"class": "View", "dataspace": {"class": "Simple", "shape": vshape}} off += nb vmaps.append(vmap) # print("VMAP", vmap) return vmaps
[docs] def create_vds(self, grp, name, dtype, shape, vmaps, fillvalue=0): """ create field :param n: group name :type n: :obj:`str` :param type_code: nexus field type :type type_code: :obj:`str` :param shape: shape :type shape: :obj:`list` < :obj:`int` > :param vmaps: virtual map list :type: :obj:`list` <:obj:`dict`> :param fillvalue: vds file value :type fillvalue: :any: :returns: file tree field :rtype: :class:`pninexus.h5cpp.node.Dataset` """ # self._streams.info( # "CREATE %s %s %s %s " % (name, dtype, shape, vmaps)) vfl = h5cpp.property.VirtualDataMaps() for vmap in vmaps: self.add_vmap(vfl, vmap) dcpl = h5cpp.property.DatasetCreationList() dcpl.set_fill_value(fillvalue, PTH[dtype]) dataspace = h5cpp.dataspace.Simple( tuple(shape), tuple([h5cpp.dataspace.UNLIMITED] * len(shape))) vf = h5cpp.node.VirtualDataset( grp, h5cpp.Path(name), PTH[dtype], dataspace, vfl, dcpl=dcpl) return vf
[docs] def create_groupvds(self, root, lnxpath, dtype, shape, vmaps): """ create field :param root: root object :type root: :class:`nxgroup` :param lnxpath: nexus path list :type lnxpath: :obj:`list` <:obj:`str`> :param dtype: nexus field type :type dtype: :obj:`str` :param shape: shape :type shape: :obj:`list` < :obj:`int` > :returns: nexus field :rtype: :class:`pninexus.h5cpp.node.Dataset` """ grp = root for gr in lnxpath[:-1]: gn = gr gt = None if ":" in gr: gn, gt = gr.split(":") if grp.has_group(gn): grp = grp.get_group(gn) else: grp = h5cpp.node.Group(grp, gn) if gt is not None: grp.attributes.create( "NX_class", h5cpp.datatype.kVariableString).write(gt) # print(gn) name = lnxpath[-1] # print("CREATE VDS", name, dtype, shape, vmaps) dataset = self.create_vds(grp, name, dtype, shape, vmaps) return dataset
[docs] def write_attr(self, am, name, dtype, value, item=None): """ write attribute :param am: attribute manager :type am: :class:`pninexus.h5cpp.attribute.AttributeManager` :param name: attribute name :type name: :obj:`str` :param name: attribute type :type name: :obj:`str` :param name: attribute value :type name: :any: :param item: element description :type item: :obj:`dict` """ at = None try: if name in [att.name for att in am]: at = am[name] except Exception: pass if at is None: try: vshape = None if isinstance(value, list): vshape = np.array(value).shape elif hasattr(value, "shape"): vshape = value.shape if not vshape: at = am.create(name, PTH[str(dtype)]) else: at = am.create(name, PTH[str(dtype)], vshape) except Exception as e: self._streams.error( "NXSFile::write_attr() - %s %s %s %s" % (name, dtype, PTH[str(dtype)], str(e))) try: if at is not None: try: rvalue = None try: if at.dataspace.type == h5cpp.dataspace.Type.SCALAR \ or sum(at.dataspace.current_dimensions): rvalue = at.read() except Exception: pass ashape = None vshape = None if isinstance(value, list): vshape = np.array(value).shape elif hasattr(value, "shape"): vshape = value.shape if at.dataspace.type == h5cpp.dataspace.Type.SCALAR: rvalue = first(rvalue) else: ashape = at.dataspace.current_dimensions if str(rvalue) != str(value): if ashape != vshape: am.remove(name) at = am.create(name, PTH[str(dtype)], vshape) at.write(value) # print("WRITE", am, name, dtype, value, # type(value), rvalue) # print("DIFF", name, str(value), str(rvalue)) else: pass # print("THE SAME", name, value) except Exception as e: self._streams.error( "NXSFile::write_attr() - %s %s %s %s" % (name, dtype, PTH[str(dtype)], str(e))) # print("at", at.read(), dir(at)) shape = None if hasattr(at.dataspace, "current_dimensions"): shape = at.dataspace.current_dimensions if shape: if not isinstance(value, list) and \ not hasattr(value, "shape"): value = json.loads(value) at.write(value) except Exception as e: # print("READ", at.read()) self._streams.error( "NXSFile::write_attr() - %s %s %s %s %s" % (name, am, dtype, PTH[str(dtype)], str(e)))
# print("WW", am, name, dtype, value, item) # print(at, dir(at))
[docs] def write_snapshot_item(self, root, item, default_nexus_path=None): """ write snapshot item :param root: nexus root group :type root: :class:`pninexus.h5cpp.node.Group` :param item: element description :type item: :obj:`dict` :param default_nexus_path: default nexus path :type default_nexus_path: :obj:`str` """ nxpath = item.get('nexus_path', default_nexus_path) value = item.get('value', None) dtype = item.get('dtype', None) if dtype == "string": dtype = "str" dataset = None if nxpath and value is not None: attr = None if "@" in nxpath: nxpath, attr = nxpath.split("@", 1) lnxpath = nxpath.split("/") h5path = "/".join([nd.split(":")[0] for nd in lnxpath]) try: if not attr: dataset = root.get_dataset(h5path) if dataset.dataspace.type != \ h5cpp.dataspace.Type.SCALAR: if not dataset.dataspace.size: try: dataset.extent(0, 1) except Exception: pass dataset.write(value) else: if ":" not in lnxpath: try: adataset = root.get_dataset(h5path) am = adataset.attributes except Exception: group = root.get_group(h5path) am = group.attributes else: group = root.get_group(h5path) am = group.attributes self.write_attr(am, attr, dtype, value) except Exception as e: # print(nxpath, str(e)) if str(e).startswith("No node ["): dataset = self.create_groupfield( root, lnxpath, dtype, value) else: self._streams.error( "NXSFile::write_snapshot_item() - %s %s %s %s" % (am, dtype, PTH[str(dtype)], str(e))) raise self.add_attributes(dataset, item)
[docs] def close(self): """ close file """ root = self.__mfile.root() root.close() self.__mfile.close() self.__mfile = None self.__cursors = {} self.__nxfields = {} self.__lbnames = {}