File

class bapsflib._hdf.utils.file.File(name: str, mode='r', control_path='/', digitizer_path='/', msi_path='/', silent=False, **kwargs)

Bases: File

Open a HDF5 file created at the Basic Plasma Science Facility.

All functionality of h5py.File is preserved (for details see http://docs.h5py.org/en/latest/)

Parameters:
  • name (str) – name (and path) of file on disk

  • mode (str, optional) – readonly 'r' (DEFAULT) and read/write 'r+'

  • control_path (str, optional) – internal HDF5 path to group containing control devices

  • digitizer_path (str, optional) – internal HDF5 path to group containing digitizer devices

  • msi_path (str, optional) – internal HDF5 path to group containing MSI devices

  • silent (bool, optional) – set True to suppress warnings (False DEFAULT)

  • kwargs (dict, optional) – additional keywords passed on to h5py.File

Examples

>>> # open HDF5 file
>>> f = File('sample.hdf5',
...          control_path='Raw data + config',
...          digitizer_path='Raw data + config',
...          msi_path='MSI')
>>> type(f)
bapsflib._hdf.utils.file.File

Attributes Summary

attrs

Attributes attached to this object

controls

Dictionary of control device mappings.

digitizers

Dictionary of digitizer device mappings

driver

Low-level HDF5 file driver used to open file

file

Return a File instance associated with this object

file_map

HDF5 file map (HDFMapper)

filename

File name on disk

id

Low-level identifier appropriate for this object

info

Dictionary of general info on the HDF5 file and the experimental run.

libver

low, high)

meta_block_size

Meta block size (in bytes)

mode

Python mode used to open file

msi

Dictionary of MSI device mappings.

name

Return the full name of this object.

overview

HDF5 file overview.

parent

Return the parent group of this object.

ref

An (opaque) HDF5 reference to this object

regionref

Create a region reference (Datasets only).

swmr_mode

Controls single-writer multiple-reader mode

userblock_size

User block size (in bytes)

CONTROL_PATH

Internal HDF5 path for control devices.

DIGITIZER_PATH

Internal HDF5 path for digitizer devices.

MSI_PATH

Internal HDF5 path for MSI devices.

Methods Summary

build_virtual_dataset(name, shape, dtype[, ...])

Assemble a virtual dataset in this group.

clear()

close()

Close the file.

copy(source, dest[, name, shallow, ...])

Copy an object or group.

create_dataset(name[, shape, dtype, data])

Create a new HDF5 dataset

create_dataset_like(name, other, **kwupdate)

Create a dataset similar to other.

create_group(name[, track_order, track_times])

Create and return a new subgroup.

create_virtual_dataset(name, layout[, fillvalue])

Create a new virtual dataset in this group.

flush()

Tell the HDF5 library to flush its buffers.

get(name[, default, getclass, getlink, ...])

Retrieve an item or other information.

get_digitizer_specs(board, channel, *[, ...])

Get a dictionary of the digitizer setup for the given board and channel.

get_time_array(data_info)

Get the time numpy array associated with the data_info argument.

in_memory([file_image])

Create an HDF5 file in memory, without an underlying file

items()

Get a view object on member items

keys()

Get a view object on member names

move(source, dest)

Move a link to a new location in the file.

pop(k[,d])

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()

as a 2-tuple; but raise KeyError if D is empty.

read_controls(controls[, shotnum, ...])

Reads data from control device datasets.

read_data(board, channel[, index, shotnum, ...])

Reads data from digitizer datasets and attaches control device data when requested.

read_msi(msi_diag[, silent])

Reads data from MSI Diagnostic datasets.

require_dataset(name, shape, dtype[, exact])

Open a dataset, creating it if it doesn't exist.

require_group(name)

Return a group, creating it if it doesn't exist.

setdefault(k[,d])

update([E, ]**F)

If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()

Get a view object on member objects

visit(func)

Recursively visit all names in this group and subgroups.

visit_links(func)

Recursively visit all names in this group and subgroups.

visititems(func)

Recursively visit names and objects in this group.

visititems_links(func)

Recursively visit links in this group.

Attributes Documentation

attrs

Attributes attached to this object

controls

Dictionary of control device mappings.

digitizers

Dictionary of digitizer device mappings

driver

Low-level HDF5 file driver used to open file

file

Return a File instance associated with this object

file_map

HDF5 file map (HDFMapper)

filename

File name on disk

id

Low-level identifier appropriate for this object

info

Dictionary of general info on the HDF5 file and the experimental run.

libver

low, high)

Type:

File format version bounds (2-tuple

meta_block_size

Meta block size (in bytes)

mode

Python mode used to open file

msi

Dictionary of MSI device mappings.

name

Return the full name of this object. None if anonymous.

overview

HDF5 file overview. (HDFOverview)

parent

Return the parent group of this object.

This is always equivalent to obj.file[posixpath.dirname(obj.name)]. ValueError if this object is anonymous.

ref

An (opaque) HDF5 reference to this object

regionref

Create a region reference (Datasets only).

The syntax is regionref[<slices>]. For example, dset.regionref[…] creates a region reference in which the whole dataset is selected.

Can also be used to determine the shape of the referenced dataset (via .shape property), or the shape of the selection (via the .selection property).

swmr_mode

Controls single-writer multiple-reader mode

userblock_size

User block size (in bytes)

CONTROL_PATH

Internal HDF5 path for control devices. (DEFAULT '/')

DIGITIZER_PATH

Internal HDF5 path for digitizer devices. (DEFAULT '/')

MSI_PATH

Internal HDF5 path for MSI devices. (DEFAULT '/')

Methods Documentation

build_virtual_dataset(name, shape, dtype, maxshape=None, fillvalue=None)

Assemble a virtual dataset in this group.

This is used as a context manager:

with f.build_virtual_dataset('virt', (10, 1000), np.uint32) as layout:
    layout[0] = h5py.VirtualSource('foo.h5', 'data', (1000,))
name

(str) Name of the new dataset

shape

(tuple) Shape of the dataset

dtype

A numpy dtype for data read from the virtual dataset

maxshape

(tuple, optional) Maximum dimensions if the dataset can grow. Use None for unlimited dimensions.

fillvalue

The value used where no data is available.

clear() None.  Remove all items from D.
close()

Close the file. All open objects become invalid

copy(source, dest, name=None, shallow=False, expand_soft=False, expand_external=False, expand_refs=False, without_attrs=False)

Copy an object or group.

The source can be a path, Group, Dataset, or Datatype object. The destination can be either a path or a Group object. The source and destinations need not be in the same file.

If the source is a Group object, all objects contained in that group will be copied recursively.

When the destination is a Group object, by default the target will be created in that group with its current name (basename of obj.name). You can override that by setting “name” to a string.

There are various options which all default to “False”:

  • shallow: copy only immediate members of a group.

  • expand_soft: expand soft links into new objects.

  • expand_external: expand external links into new objects.

  • expand_refs: copy objects that are pointed to by references.

  • without_attrs: copy object without copying attributes.

Example

>>> f = File('myfile.hdf5', 'w')
>>> f.create_group("MyGroup")
>>> list(f.keys())
['MyGroup']
>>> f.copy('MyGroup', 'MyCopy')
>>> list(f.keys())
['MyGroup', 'MyCopy']
create_dataset(name, shape=None, dtype=None, data=None, **kwds)

Create a new HDF5 dataset

name

Name of the dataset (absolute or relative). Provide None to make an anonymous dataset.

shape

Dataset shape. Use “()” for scalar datasets. Required if “data” isn’t provided.

dtype

Numpy dtype or string. If omitted, dtype(‘f’) will be used. Required if “data” isn’t provided; otherwise, overrides data array’s dtype.

data

Provide data to initialize the dataset. If used, you can omit shape and dtype arguments.

Keyword-only arguments:

chunks

(Tuple or int) Chunk shape, or True to enable auto-chunking. Integers can be used for 1D shape.

maxshape

(Tuple or int) Make the dataset resizable up to this shape. Use None for axes within the tuple you want to be unlimited. Integers can be used for 1D shape. For 1D datasets with unlimited maxshape, a shape tuple of length 1 must be provided, (None,). Passing None sets ``maxshape` to shape, making the dataset un-resizable, which is the default.

compression

(String or int) Compression strategy. Legal values are ‘gzip’, ‘szip’, ‘lzf’. If an integer in range(10), this indicates gzip compression level. Otherwise, an integer indicates the number of a dynamically loaded compression filter.

compression_opts

Compression settings. This is an integer for gzip, 2-tuple for szip, etc. If specifying a dynamically loaded compression filter number, this must be a tuple of values.

scaleoffset

(Integer) Enable scale/offset filter for (usually) lossy compression of integer or floating-point data. For integer data, the value of scaleoffset is the number of bits to retain (pass 0 to let HDF5 determine the minimum number of bits necessary for lossless compression). For floating point data, scaleoffset is the number of digits after the decimal place to retain; stored values thus have absolute error less than 0.5*10**(-scaleoffset).

shuffle

(T/F) Enable shuffle filter.

fletcher32

(T/F) Enable fletcher32 error detection. Not permitted in conjunction with the scale/offset filter.

fillvalue

(Scalar) Use this value for uninitialized parts of the dataset.

track_times

(T/F) Enable dataset creation timestamps.

track_order

(T/F) Track attribute creation order if True. If omitted use global default h5.get_config().track_order.

external

(Iterable of tuples) Sets the external storage property, thus designating that the dataset will be stored in one or more non-HDF5 files external to the HDF5 file. Adds each tuple of (name, offset, size) to the dataset’s list of external files. Each name must be a str, bytes, or os.PathLike; each offset and size, an integer. If only a name is given instead of an iterable of tuples, it is equivalent to [(name, 0, h5py.h5f.UNLIMITED)].

efile_prefix

(String) External dataset file prefix for dataset access property list. Does not persist in the file.

virtual_prefix

(String) Virtual dataset file prefix for dataset access property list. Does not persist in the file.

allow_unknown_filter

(T/F) Do not check that the requested filter is available for use. This should only be used with write_direct_chunk, where the caller compresses the data before handing it to h5py.

rdcc_nbytes

Total size of the dataset’s chunk cache in bytes. The default size is 1024**2 (1 MiB) for HDF5 before 2.0 and 8 MiB for HDF5 2.0 or later.

rdcc_w0

The chunk preemption policy for this dataset. This must be between 0 and 1 inclusive and indicates the weighting according to which chunks which have been fully read or written are penalized when determining which chunks to flush from cache. A value of 0 means fully read or written chunks are treated no differently than other chunks (the preemption is strictly LRU) while a value of 1 means fully read or written chunks are always preempted before other chunks. If your application only reads or writes data once, this can be safely set to 1. Otherwise, this should be set lower depending on how often you re-read or re-write the same data. The default value is 0.75.

rdcc_nslots

The number of chunk slots in the dataset’s chunk cache. Increasing this value reduces the number of cache collisions, but slightly increases the memory used. Due to the hashing strategy, this value should ideally be a prime number. As a rule of thumb, this value should be at least 10 times the number of chunks that can fit in rdcc_nbytes bytes. For maximum performance, this value should be set approximately 100 times that number of chunks. The default value is 521.

create_dataset_like(name, other, **kwupdate)

Create a dataset similar to other.

name

Name of the dataset (absolute or relative). Provide None to make an anonymous dataset.

other

The dataset which the new dataset should mimic. All properties, such as shape, dtype, chunking, … will be taken from it, but no data or attributes are being copied.

Any dataset keywords (see create_dataset) may be provided, including shape and dtype, in which case the provided values take precedence over those from other.

create_group(name, track_order=None, *, track_times=False)

Create and return a new subgroup.

Name may be absolute or relative. Fails if the target name already exists.

track_order

Track dataset/group/attribute creation order under this group if True. If None use global default h5.get_config().track_order.

track_times: bool or None, default: False

If True, store timestamps for this group in the file. If None, fall back to the default value.

create_virtual_dataset(name, layout, fillvalue=None)

Create a new virtual dataset in this group.

See virtual datasets in the docs for more information.

name

(str) Name of the new dataset

layout

(VirtualLayout) Defines the sources for the virtual dataset

fillvalue

The value to use where there is no data.

flush()

Tell the HDF5 library to flush its buffers.

get(name, default=None, getclass=False, getlink=False, elink_mode=None, elink_locking=None, elink_swmr=None)

Retrieve an item or other information.

“name” given only:

Return the item, or “default” if it doesn’t exist

“getclass” is True:

Return the class of object (Group, Dataset, etc.), or “default” if nothing with that name exists

“getlink” is True:

Return HardLink, SoftLink or ExternalLink instances. Return “default” if nothing with that name exists.

“getlink” and “getclass” are True:

Return HardLink, SoftLink and ExternalLink classes. Return “default” if nothing with that name exists.

“elink_mode”:

External links access mode:

  • “r”: Read-only

  • “r+”: Read/write

  • None (default): Use current file access mode

“elink_locking”:

External links file locking behavior:

  • None (default) – Use the current file locking

  • False (or “false”) – Disable file locking

  • True (or “true”) – Enable file locking

  • “best-effort” – Enable file locking but ignore some errors

Warning:

The HDF5_USE_FILE_LOCKING environment variable can override this parameter.

“elink_swmr”:

External link SWMR read mode. Set to True only when elink_mode = ‘r’ and current file is not opened in SWMR write mode. By default, use current file SWMR mode.

Example:

>>> cls = group.get('foo', getclass=True)
>>> if cls == SoftLink:
get_digitizer_specs(board: int, channel: int, *, digitizer: str | None = None, adc: str | None = None, config_name: str | None = None, silent: bool = False) Dict[str, Any]

Get a dictionary of the digitizer setup for the given board and channel.

Parameters:
  • board (int) – Digitizer board number.

  • channel (int) – Digitizer channel number.

  • digitizer (str, optional) – Digitizer name. If None, then the digitizer will be inferred if only one digitizer was used. (DEFAULT: None)

  • adc (str, optional) – Digitizer analog-digital-converter name. If None, then the adc will be taken from the digitizer configuration assuming only one adc was used. (DEFAULT: None)

  • config_name (str, optional) – Digitizer configuration name. If None, then the config_name will be taken from the digitizer configuration assuming only one active configuration was used. (DEFAULT: None)

  • silent (bool) – Set True to suppress warnings. (DEFAULT: False)

Returns:

Dictionary of the digitizer setup for the specified board and channel.

Return type:

Dict[str, Any]

Notes

The returned dictionary will contain the following data:

Key

Description

"board"

Digitizer board number.

"channel"

Digitizer channel number.

"digitizer"

Digitizer name.

"adc"

Name of analog-digital-converter.

"configuration name"

Name of digitizer configuration.

"nshotnum"

Num. of shot numbers in the data run.

"nt"

Num. of time samples.

"bit"

Bit-ness of the digitizer.

"clock rate"

Digitizer clock rate

"shot average"

Num. of timeseries averaged together

"sample average"

Num. of time samples averaged together

"device group path"

internal path to device group

"device dataset path"

internal path to digitizer dataset

"source file"

absolute path to HDF5 file

"time_dset_path"

internal path to time series dataset

get_time_array(data_info: HDFReadData | Dict[str, Any]) np.ndarray

Get the time numpy array associated with the data_info argument.

data_info can be an HDFReadData object obtained using read_data() or and information dict generated using get_digitizer_specs().

Parameters:

data_info (HDFReadData | Dict[str, Any]) – An HDFReadData object instance or a dictionary containing the necessary time meta-data.

Returns:

A 1D numpy array containing the time series data.

Return type:

np.ndarray

Notes

The method uses the meta-data contained in either the information dictionary generated by get_digitizer_specs() or the info dictionary bound to HDFReadData (which is generated by method read_data()).

If the information dictionary contains the key "clock rate", then the time array will be calculated using the "clock rate", "nt", and "sample average".

If "clock rate" is None, then the it is assumed the time series is stored in a dedicated dataset which is indicated by the "time_dset_path" key.

Examples

Retrieving the time series array AFTER reading out the digitizer data:

>>> f = File("sample.hdf5")
>>> data = f.read_data(0, 1, silent=True)
>>> time_arr = f.get_time_array(data)

Retrieving the time series array BEFORE reading out the digitizer data:

>>> f = File("sample.hdf5")
>>> _info = f.get_digitizer_specs(0, 1, silent=True)
>>> time_arr = f.get_time_array(_info)
classmethod in_memory(file_image=None, **kwargs)

Create an HDF5 file in memory, without an underlying file

file_image

The initial file contents as bytes (or anything that supports the Python buffer interface). HDF5 takes a copy of this data.

block_size

Chunk size for new memory alloactions (default 64 KiB).

Other keyword arguments are like File(), although name, mode, driver and locking can’t be passed.

items()

Get a view object on member items

keys()

Get a view object on member names

move(source, dest)

Move a link to a new location in the file.

If “source” is a hard link, this effectively renames the object. If “source” is a soft or external link, the link itself is moved, with its value unmodified.

pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

read_controls(controls: List[str | Tuple[str, Any]], shotnum=slice(None, None, None), intersection_set=True, silent=False, **kwargs) HDFReadControls

Reads data from control device datasets. See HDFReadControls for more detail.

Parameters:
  • controls (List[str | Tuple[str, Any]]) – A list of strings and/or 2-element tuples indicating the control device(s). If a control device has only one configuration then only the device name 'control' needs to be passed in the list. If a control device has multiple configurations, then the device name and its configuration “name” needs to be passed as a tuple element ('control', 'config') in the list. (see condition_controls() for details)

  • shotnum (int | list(int) | slice() | numpy.array, optional) – HDF5 file shot number(s) indicating data entries to be extracted

  • intersection_set (bool, optional) – True (DEFAULT) will force the returned shot numbers to be the intersection of shotnum and the shot numbers contained in each control device dataset. False will return the union instead of the intersection, minus \(shotnum \le 0\). (see HDFReadControls for details)

  • silent (bool, optional) –

    False (DEFAULT). Set True to ignore any BaPSFWarning

    (soft-warnings)

Returns:

structured numpy array of control device data

Return type:

HDFReadControls

Examples

>>> # open HDF5 file
>>> f = File('sample.hdf5')
>>>
>>> # list control devices
>>> list(f.controls)
['6K Compumotor', 'Waveform']
>>>
>>> # list '6K Compumotor' configurations
>>> list(f.controls['6K Compumotor'].configs)
[2, 3]
>>>
>>> # extract all '6k Compumotor' data for configuration 3
>>> cdata = f.read_controls([('6K Compumotor', 3)])
>>> type(cdata)
bapsflib._hdf.utils.hdfreadcontrols.HDFReadControls
>>>
>>> # list 'Waveform' configurations
>>> list(f.file_map.controls['Waveform'].configs)
['config01']
>>>
>>> # extract 'Waveform' data
>>> cdata = f.read_controls(['Waveform'])
>>> list(cdata.info['controls'])
['Waveform']
>>>
>>> # extract both 'Waveform' and '6K Compumotor'
>>> controls = ['Waveform', ('6K Compumotor', 2)]
>>> cdata = f.read_controls(controls)
>>> list(cdata.info['controls'])
['6K Compumotor', 'Waveform']
read_data(board: int, channel: int, index=slice(None, None, None), shotnum=slice(None, None, None), time_slice: slice = slice(None, None, None), digitizer=None, adc=None, config_name=None, keep_bits=False, add_controls=None, intersection_set=True, silent=False, **kwargs) HDFReadData

Reads data from digitizer datasets and attaches control device data when requested.

Parameters:
  • board (int) – Analog-digital-converter board number

  • channel (int) – Analog-digital-converter channel number

  • index (int | list(int) | slice() | numpy.array, optional) – (DEFAULT: slice(None)) Dataset row indices to be readout. Overridden by argument shotnum.

  • shotnum (int | list(int) | slice() | numpy.array, optional) – (DEFAULT: slice(None)) HDF5 file shot number(s) indicating data entries to be extracted. Overrides argument index.

  • time_slice (slice, optional) – (DEFAULT: slice(None)) A slice object representing the time slice to be extracted from the digitizer dataset.

  • digitizer (str, optional) – (DEFAULT: None) Name of digitizer

  • adc (str, optional) – (DEFAULT: None) Name of the digitizer’s analog-digital converter

  • config_name (str, optional) – (DEFAULT: None) Name of digitizer configuration

  • keep_bits (bool, optional) – (DEFAULT: False) Set True to keep the extracted data as is (i.e. in bits). Set False to convert the extracted data to voltage using stored meta-data in the associated header dataset.

  • add_controls (List[str | Tuple[str, Any]], optional) – (DEFAULT: None) A list of strings and/or 2-element tuples indicating the control device(s). If a control device has only one configuration, then only the device name 'control' needs to be passed in the list. If a control device has multiple configurations, then the device name and its configuration “name” needs to be passed as a tuple element ('control', 'config') in the list. (see condition_controls() for details)

  • intersection_set (bool, optional) – (DEFAULT: True) True will force the returned shot numbers to be the intersection of shotnum, the digitizer dataset shot numbers, and, if requested, the shot numbers contained in each control device dataset. False will return the union instead of the intersection, minus \(shotnum \le 0\). (see HDFReadData for details)

  • silent (bool, optional) – (DEFAULT: False) Set True to ignore any issued BaPSFWarning.

Returns:

structured numpy array of digitized data

Return type:

HDFReadData

Notes

Note

The shotnum keyword will always override the index keyword, but, due to extra overhead required for identifying shot number locations in the digitizer dataset, the index keyword will always execute quicker than the shotnum keyword.

Examples

To read data associated with a digitizer there are 5 descriptors needed to fully define what data is to be extracted. These descriptors are board, channel, digitizer, config_name, and adc. In the following example, board 1, channel 2 will be read for the "SIS crate" digitizer on the "SIS 3302" analog-digital-converter for the "config01" digitizer configuration.

>>> # open HDF5 file
>>> f = File("sample.hdf5")
>>>
>>> # print detail about the mapped digitizers
>>> print(f.digitizers)
| Digitizer   | Configuration | ADC        | (board, [channel, ...]) | Shot Num. Range | nt   |
+-------------+---------------+------------+-------------------------+-----------------+------+
| 'SIS crate' | 'config01'    | 'SIS 3302' | (1, (2, 3, 4))          | ??              | 2500 |
|             |---------------|------------|-------------------------|-----------------|------|
|             | 'config02'    | 'SIS 3302' | (1, (2, 3, 4))          | ??              | 2500 |
|             |               | 'SIS 3305' | (1, (1,))               | ??              | 2500 |
>>>
>>> # get data for brd = 1, ch = 2
>>> data = f.read_data(
...     1,
...     2,
...     digitizer="SIS crate",
...     adc="SIS 3302",
...     config_name="config01",
... )
>>> type(data)
bapsflib._hdf.utils.hdfreaddata.HDFReadData

The digitizer, config_name, and adc arguments are optional if there is only one value for each of those. In this example digitizer is singular and adc is singular for configuration 'config01', so only the configuration name (in addition to board and channel) needs to be specified.

>>> data = f.read_data(1, 2, config_name="config01")

data in this case will be a structured numpy array containing at least three fields: "shotnum", "signal", and "xyz". 'shotnum' is the array of shot numbers associated with the digitized data; "signal" is the actual digitized data; and "zyz" is the probe xyz location. The later is NaN at the moment, since positional data read-out has not been requested.

>>> data.dtype
dtype([('shotnum', '<u4'), ('signal', '<f4', (2500,)),
      ('xyz', '<f4', (3,))])
>>>
>>> # display shot numbers
>>> data["shotnum"]
array([  1,  2, ..., 98, 99], dtype=uint32)
>>>
>>> # show 'signal' values for shot number 1
>>> data["signal"][0]
array([-0.41381955, -0.4134333 , -0.4118886 , ..., -0.41127062,
       -0.4105754 , -0.41119337], dtype=float32)
>>>
>>> # show 'xyz' values for shot number 1
>>> data["xyz"][0]
array([nan, nan, nan], dtype=float32)

If it is desired to read out only certain digitized traces, then this can be achieved with either the index or shotnum argument, with the later taking precedence.

>>> # get the first 5 traces using index
>>> data = f.read_data(1, 2, config_name="config01", index=slice(5))
>>> data = f.read_data(1, 2, config_name="config01", index=np.s_[:5])
>>>
>>> # get every 10th shot using shotnum
>>> data = f.read_data(1, 2, config_name="config01", shotnum=slice(10, None, 10))
>>> data = f.read_data(1, 2, config_name="config01", shotnum=np.s_[10::10])

Sometimes only a certain time slice is desired, and this can be achieved using the time_slice argument.

>>> # get time subset
>>> data = f.read_data(
...     1,
...     2,
...     config_name="config01",
...     time_slice=slice(200, 500, 1),
... )
>>> data = f.read_data(
...     1,
...     2,
...     config_name="config01",
...     time_slice=np.s_[200:500:1],
... )
>>>
>>> # time_slice can be used with index or shotnum
>>> data = HDFReadData(
...     f,
...     1,
...     2,
...     config_name="config01",
...     time_slice=slice(200, 500, 1),
...     shotnum=slice(10, None, 10),
... )
>>> data = HDFReadData(
...     f,
...     1,
...     2,
...     config_name="config01",
...     time_slice=slice(200, 500, 1),
...     index=np.s_[0:5],
... )

Now lets add position data to the read out. Position data is recorded by control devices. For this example lets assume the position data was recorded by the "6K Compumotor" control device using the probe drive attached to receptacle 3. This information can be given using the add_controls argument.

>>> # read digitizer data while adding '6K Compumotor' data
>>> # from receptacle (configuration) 3
>>> data = f.read_data(
...     1,
...     2,
...     config_name="config01",
...     add_controls=[("6K Compumotor", 3)],
... )
>>> data.dtype
dtype([('shotnum', '<u4'), ('signal', '<f4', (2500,)),
       ('xyz', '<f4', (3,)), ('ptip_rot_theta', '<f8'),
       ('ptip_rot_phi', '<f8')])
>>>
>>> # show 'xyz' values for shot number 1
>>> data["xyz"][0]
array([ -32. ,   15. , 1022.4], dtype=float32)

Now the "xyz" is populated with position data, but additional fields ("ptip_rot_theta" and "ptip_rot_phi") are added to the structured numpy array. Each control device can add its own data fields to the array. And, multiple control devices can be specified at the time of the data read.

read_msi(msi_diag: str, silent=False, **kwargs) HDFReadMSI

Reads data from MSI Diagnostic datasets. See HDFReadMSI for more detail.

Parameters:
  • msi_diag (str) – name of MSI diagnostic

  • silent (bool, optional) – False (DEFAULT). Set True to ignore any BaPSFWarning (soft-warnings)

Returns:

structured numpy array of MSI diagnostic data

Return type:

HDFReadMSI

Examples

>>> # open HDF5 file
>>> f = File('sample.hdf5')
>>>
>>> # list msi diagnostics
>>> list(f.msi)
['Interferometer array', 'Magnetic field']
>>>
>>> # read 'Interferometer array'
>>> mdata = f.read_msi('Interferometer array')
>>> type(mdata)
bapsflib._hdf.utils.hdfreadmsi.HDFReadMSI
require_dataset(name, shape, dtype, exact=False, **kwds)

Open a dataset, creating it if it doesn’t exist.

If keyword “exact” is False (default), an existing dataset must have the same shape and a conversion-compatible dtype to be returned. If True, the shape and dtype must match exactly.

If keyword “maxshape” is given, the maxshape and dtype must match instead.

If any of the keywords “rdcc_nslots”, “rdcc_nbytes”, or “rdcc_w0” are given, they will be used to configure the dataset’s chunk cache.

Other dataset keywords (see create_dataset) may be provided, but are only used if a new dataset is to be created.

Raises TypeError if an incompatible object already exists, or if the shape, maxshape or dtype don’t match according to the above rules.

require_group(name)

Return a group, creating it if it doesn’t exist.

TypeError is raised if something with that name already exists that isn’t a group.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()

Get a view object on member objects

visit(func)

Recursively visit all names in this group and subgroups.

Note: visit ignores soft and external links. To visit those, use visit_links.

You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:

func(<member name>) => <None or return value>

Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. The iteration order is lexicographic.

Example:

>>> # List the entire contents of the file
>>> f = File("foo.hdf5")
>>> list_of_names = []
>>> f.visit(list_of_names.append)

Recursively visit all names in this group and subgroups. Each link will be visited exactly once, regardless of its target.

You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:

func(<member name>) => <None or return value>

Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. The iteration order is lexicographic.

Example:

>>> # List the entire contents of the file
>>> f = File("foo.hdf5")
>>> list_of_names = []
>>> f.visit_links(list_of_names.append)
visititems(func)

Recursively visit names and objects in this group.

Note: visititems ignores soft and external links. To visit those, use visititems_links.

You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:

func(<member name>, <object>) => <None or return value>

Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. The iteration order is lexicographic.

Example:

# Get a list of all datasets in the file >>> mylist = [] >>> def func(name, obj): … if isinstance(obj, Dataset): … mylist.append(name) … >>> f = File(‘foo.hdf5’) >>> f.visititems(func)

Recursively visit links in this group. Each link will be visited exactly once, regardless of its target.

You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:

func(<member name>, <link>) => <None or return value>

Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. The iteration order is lexicographic.

Example:

# Get a list of all softlinks in the file >>> mylist = [] >>> def func(name, link): … if isinstance(link, SoftLink): … mylist.append(name) … >>> f = File(‘foo.hdf5’) >>> f.visititems_links(func)