Name | hdfmap JSON |
Version |
0.7.0
JSON |
| download |
home_page | None |
Summary | Map objects within a HDF file and create a dataset namespace |
upload_time | 2025-01-08 15:32:25 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.10 |
license | Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |
keywords |
nexus
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# hdfmap
Map objects within an HDF file and create a dataset namespace.
[](https://pypi.org/project/hdfmap)
[](https://opensource.org/licenses/Apache-2.0)
[](https://github.com/DiamondLightSource/hdfmap)
**Version 0.7**
| By Dan Porter |
|----------------------|
| Diamond Light Source |
| 2024 |
### Documentation
[](https://diamondlightsource.github.io/hdfmap/)
[diamondlightsource.github.io/hdfmap](https://diamondlightsource.github.io/hdfmap/)
### TL;DR - Usage
```python
from hdfmap import create_nexus_map, load_hdf
# HdfMap from NeXus file - get dataset paths:
m = create_nexus_map('file.nxs')
m['energy'] # >> '/entry/instrument/monochromator/energy'
m['signal'] # >> '/entry/measurement/sum'
m['axes0'] # >> '/entry/measurement/theta'
m.get_image_path() # >> '/entry/instrument/pil3_100k/data'
# load dataset data
with load_hdf('file.nxs') as nxs:
path = m.get_path('scan_command')
cmd = nxs[path][()] # returns bytes data direct from file
cmd = m.get_data(nxs, 'scan_command') # returns converted str output
string = m.format_hdf(nxs, "the energy is {energy:.2f} keV")
d = m.get_dataholder(nxs) # classic data table, d.scannable, d.metadata
# Shortcuts - single file reloader class
from hdfmap import NexusLoader
scan = NexusLoader('file.hdf')
[data1, data2] = scan.get_data(['dataset_name_1', 'dataset_name_2'])
data = scan.eval('dataset_name_1 * 100 + 2')
string = scan.format('my data is {dataset_name_1:.2f}')
# Shortcuts - multifile load data (generate map from first file)
from hdfmap import hdf_data, hdf_eval, hdf_format, hdf_image
all_data = hdf_data([f'file{n}.nxs' for n in range(100)], 'dataset_name')
normalised_data = hdf_eval(filenames, 'total / Transmission / (rc / 300.)')
descriptions = hdf_format(filenames, 'Energy: {en:5.3f} keV')
image_stack = hdf_image(filenames, index=31)
```
### Installation
*Requires:* Python >=3.10, Numpy, h5py
#### from PyPI
```bash
python -m pip install hdfmap
```
#### from GitHub
```bash
python -m pip install --upgrade git+https://github.com/DiamondLightSource/hdfmap.git
```
### Description
Another generic hdf reader but the idea here is to build up a namespace dict of `{'name': 'path'}`
for every dataset, then group them in hopefully a useful way.
Objects within the HDF file are separated into Groups and Datasets. Each object has a
defined 'path' and 'name' paramater, as well as other attributes
- path -> '/entry/measurement/data' -> the location of an object within the file
- name -> 'data' -> an path expressed as a simple variable name
Paths are unique locations within the file but can be used to identify similar objects in other files
Names may not be unique within a file and are generated from the path.
| | **name** | **path** |
|---------------|------------------------------|--------------------------------------|
| *Description* | simple identifier of dataset | hdf path built from position in file |
| *Example* | `'scan_command'` | `'/entry/scan_command'` |
Names of different types of datasets are stored for arrays (size > 0) and values (size 0)
Names for scannables relate to all arrays of a particular size
A combined list of names is provided where scannables > arrays > values
### HdfMap Attributes
| | |
|----------------|--------------------------------------------------------|
| map.groups | stores attributes of each group by path |
| map.classes | stores list of group paths by nx_class |
| map.datasets | stores attributes of each dataset by path |
| map.arrays | stores array dataset paths by name |
| map.values | stores value dataset paths by name |
| map.scannables | stores array dataset paths with given size, by name |
| map.combined | stores array and value paths (arrays overwrite values) |
| map.image_data | stores dataset paths of image data |
#### E.G.
```python
map.groups = {'/hdf/group': ('class', 'name', {attrs}, [datasets])}
map.classes = {'class_name': ['/hdf/group1', '/hdf/group2']}
map.datasets = {'/hdf/group/dataset': ('name', size, shape, {attrs})}
map.arrays = {'name': '/hdf/group/dataset'}
map.values = {'name': '/hdf/group/dataset'}
map.scannables = {'name': '/hdf/group/dataset'}
map.image_data = {'name': '/hdf/group/dataset'}
```
### HdfMap Methods
| | |
|---------------------------------------------------|-----------------------------------------------------------------------------|
| `map.populate(h5py.File)` | populates the dictionaries using the given file |
| `map.generate_scannables(array_size)` | populates scannables namespace with arrays of same size |
| `map.most_common_size()` | returns the most common dataset size > 1 |
| `map.get_attr('name_or_path', 'attr')` | return value of dataset attribute |
| `map.get_path('name_or_group_or_class')` | returns path of object with name |
| `map.get_image_path()` | returns default path of detector dataset (or largest dataset) |
| `map.get_group_path('name_or_path_or_class')` | return path of group with class |
| `map.get_group_datasets('name_or_path_or_class')` | return list of dataset paths in class |
| `map.find_groups(*names_or_classes)` | return list of group paths matching given group names or classes |
| `map.find_datasets(*names_or_classes)` | return list of dataset paths matching given names, classes or attributes |
| `map.find_paths('string')` | return list of dataset paths containing string |
| `map.find_names('string')` | return list of dataset names containing string |
| `map.find_attr('attr_name')` | return list of paths of groups or datasets containing attribute 'attr_name' |
### HdfMap File Methods
| | |
|------------------------------------------|-------------------------------------------------------|
| `map.get_metadata(h5py.File)` | returns dict of value datasets |
| `map.get_scannables(h5py.File)` | returns dict of scannable datasets |
| `map.get_scannalbes_array(h5py.File)` | returns numpy array of scannable datasets |
| `map.get_dataholder(h5py.File)` | returns dict like object with metadata and scannables |
| `map.get_image(h5py.File, index)` | returns image data |
| `map.get_data(h5py.File, 'name')` | returns data from dataset |
| `map.eval(h5py.File, 'expression')` | returns output of expression using dataset names |
| `map.format(h5py.File, 'string {name}')` | returns output of str expression |
### NeXus Files
Files using the [NeXus Format](https://www.nexusformat.org/) can generate special NexusMap objects.
These work in the same way as the general HdfMaps but contain additional special names in the namespace:
| | |
|----------------|------------------------------------|
| `'axes'` | returns path of default NXaxes |
| `'signal'` | returns path of default NXsignal |
In addition, the `map.scannables` dict will be populated automatically by the names given in the "scan_fields" dataset
or by datasets from the first *NXdata* group. The default *image* data will be taken from the first
*NXdetector* dataset.
## Examples
### scan data & metadata
Separate datasets in a NeXus file into Diamond's classic scannables and metadata, similar to what was in the old
'*.dat' files.
```python
from hdfmap import create_nexus_map, load_hdf
# HdfMap from NeXus file:
hmap = create_nexus_map('file.nxs')
with load_hdf('file.nxs') as nxs:
scannables = hmap.get_scannables_array(nxs) # creates 2D numpy array
labels = scannables.dtype.names
metadata = hmap.get_metadata(nxs) # {'name': value}
d = hmap.get_dataholder(nxs) # classic data table, d.scannable, d.metadata
d.theta == d['theta'] # scannable array 'theta'
d.metadata.scan_command == d.metadata['scan_command'] # single value 'scan_command'
# OR, use the shortcut:
from hdfmap import nexus_data_block
d = nexus_data_block('file.nxs')
# The data loader class removes the need to open the files:
from hdfmap import NexusLoader
scan = NexusLoader('file.nxs')
metadata = scan.get_metadata()
scannables = scan.get_scannables()
```
### automatic default plot axes
If defined in the nexus file, 'axes' and 'signal' will be populated automatically
```python
import matplotlib.pyplot as plt
from hdfmap import create_nexus_map, load_hdf
# HdfMap from NeXus file:
hmap = create_nexus_map('file.nxs')
with load_hdf('file.nxs') as nxs:
axes = hmap.get_data(nxs, 'axes')
signal = hmap.get_data(nxs, 'signal')
title = hmap.format_hdf(nxs, "{entry_identifier}\n{scan_command}")
axes_label = hmap.get_path('axes')
signal_label = hmap.get_path('signal')
# plot the data (e.g. using matplotlib)
plt.figure()
plt.plot(axes, signal)
plt.xlabel(axes_label)
plt.ylabel(signal_label)
plt.title(title)
# Or, using NexusLoader:
from hdfmap import NexusLoader
scan = NexusLoader('file.nxs')
axes, signal = scan('axes, signal')
axes_label, signal_label = scan('_axes, _signal')
title = scan.format("{entry_identifier}\n{scan_command}")
```
### Automatic image data
Get images from the first detector in a NeXus file
```python
from hdfmap import create_nexus_map, load_hdf
# HdfMap from NeXus file:
hmap = create_nexus_map('file.nxs')
image_location = hmap.get_image_path() # returns the hdf path chosen for the default detector
with load_hdf('file.nxs') as nxs:
middle_image = hmap.get_image(nxs) # returns single image from index len(dataset)//2
first_image = hmap.get_image(nxs, 0) # returns single image from dataset[0, :, :]
volume = hmap.get_image(nxs, ()) # returns whole volume as array
roi = hmap.get_image(nxs, (0, slice(5, 10, 1), slice(5, 10, 1))) # returns part of dataset
# Or, using NexusLoader:
from hdfmap import NexusLoader
scan = NexusLoader('file.nxs')
image = scan.get_image(index=0) # using index as defined above
```
### Multi-scan metadata string
Generate a metadata string from every file in a directory very quickly. The HdfMap is only created for the first file,
the remaining files are treated as having identical structure.
```python
from hdfmap import list_files, hdf_format
format_string = "#{entry_identifier}: {start_time} : E={incident_energy:.3f} keV : {scan_command}"
files = list_files('/directoy/path', extension='.nxs')
strings_list = hdf_format(files, format_string)
print('\n'.join(strings_list))
# other multi-file readers:
from hdfmap import hdf_data, hdf_image, hdf_eval
data_list = hdf_data(files, 'incident_energy')
image_list = hdf_image(files, index=0)
data_list = hdf_eval(files, 'signal / Transmission')
```
### Metadata Evaluation
Functionality for namespace evaluation of the hdf file allows for a number of rules allowing easy extraction
of formatted metadata. The Evaluation functions are:
- `HdfMap.eval(hdfobj, 'name')` -> value
- `HdfMap.format_hdf(hdfobj, '{name}')` -> string
- `HdfLoader('eval')` -> value
- `HdfLoader.eval('eval')` -> value
- `HdfLoader.format('{name}')` -> string
- `hdf_eval([files], 'name')` -> list[values]
- `hdf_format([files], '{name}')` -> list[string]
#### eval vs format
Evaluation functions evaluate the expression as given, replacing names in the hdfmap namespace with their associated
values, or using the rules below. The format functions allow the input of python
[f-strings](https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting),
allowing precise formatting to be applied and returning a string.
#### Rules
The following patterns are allowed in any expression:
- 'filename': str, name of hdf_file
- 'filepath': str, full path of hdf_file
- '_*name*': str hdf path of *name*
- '__*name*': str internal name of *name* (e.g. for 'axes')
- 's_*name*': string representation of dataset (includes units if available)
- '*name*@attr': returns attribute of dataset *name*
- '*name*?(default)': returns default if *name* doesn't exist
- '(name1|name2|name3)': returns the first available of the names
- '(name1|name2@(default))': returns the first available name or default
#### Examples
```python
from hdfmap import create_nexus_map, load_hdf
# HdfMap from NeXus file:
hmap = create_nexus_map('file.nxs')
with load_hdf('file.nxs') as nxs:
# mathematical array expressions (using np as Numpy)
data = hmap.eval(nxs, 'int(np.max(total / Transmission / count_time))')
# return the path of a name
path = hmap.eval(nxs, '_axes') # -> '/entry/measurement/h'
# return the real name of a variable
name = hmap.eval(nxs, '__axes') # -> 'h'
# return label, using dataset attributes
label = hmap.eval(nxs, 's_ppy') # example uses @decimals and @units
# return dataset attributes
attr = hmap.eval(nxs, 'idgap@units') # -> 'mm'
# return first available dataset
cmd = hmap.eval(nxs, '(cmd|title|scan_command)') # -> 'scan hkl ...'
# return first available or default value
atten = hmap.eval(nxs, '(gains_atten|atten?(0))') # -> 0
# python expression using multiple parameters
pol = hmap.eval(nxs, '"pol in" if abs(delta_offset) < 0.1 and abs(thp) > 20 else "pol out"')
# formatted strings
title = hmap.format_hdf(nxs, '{filename}: {scan_command}')
hkl = hmap.format_hdf(nxs, '({np.mean(h):.3g},{np.mean(k):.3g},{np.mean(l):.3g})')
# Or, using NexusLoader:
from hdfmap import NexusLoader
scan = NexusLoader('file.nxs')
# normalised default-signal
print(scan('signal / count_time / Transmission / (rc / 300.)'))
# axes label
print(scan.format('{__axes} [{axes@units}]'))
# Or, for multiple-files:
from hdfmap import hdf_eval, hdf_format, list_files
files = [f"file{n}.nxs" for n in range(10)]
energy_values = hdf_eval(files, '(en|energy@(8))')
list_scans = hdf_format(files, '{filename}: ({np.mean(h):.3g},{np.mean(k):.3g},{np.mean(l):.3g}) : {scan_command})')
print('\n'.join(list_scans))
```
Raw data
{
"_id": null,
"home_page": null,
"name": "hdfmap",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": "Dan Porter <dan.porter@diamond.ac.uk>",
"keywords": "nexus",
"author": null,
"author_email": "Dan Porter <dan.porter@diamond.ac.uk>",
"download_url": "https://files.pythonhosted.org/packages/53/2d/f7b552a79528c261d1bbb5ba844aca8cef267245c3d8c438498580050658/hdfmap-0.7.0.tar.gz",
"platform": null,
"description": "# hdfmap\nMap objects within an HDF file and create a dataset namespace.\n\n[](https://pypi.org/project/hdfmap)\n[](https://opensource.org/licenses/Apache-2.0)\n[](https://github.com/DiamondLightSource/hdfmap)\n\n**Version 0.7**\n\n| By Dan Porter | \n|----------------------|\n| Diamond Light Source |\n| 2024 |\n\n### Documentation\n[](https://diamondlightsource.github.io/hdfmap/)\n[diamondlightsource.github.io/hdfmap](https://diamondlightsource.github.io/hdfmap/)\n\n### TL;DR - Usage\n\n```python\nfrom hdfmap import create_nexus_map, load_hdf\n\n# HdfMap from NeXus file - get dataset paths:\nm = create_nexus_map('file.nxs')\nm['energy'] # >> '/entry/instrument/monochromator/energy'\nm['signal'] # >> '/entry/measurement/sum'\nm['axes0'] # >> '/entry/measurement/theta'\nm.get_image_path() # >> '/entry/instrument/pil3_100k/data'\n\n# load dataset data\nwith load_hdf('file.nxs') as nxs:\n path = m.get_path('scan_command')\n cmd = nxs[path][()] # returns bytes data direct from file\n cmd = m.get_data(nxs, 'scan_command') # returns converted str output\n string = m.format_hdf(nxs, \"the energy is {energy:.2f} keV\")\n d = m.get_dataholder(nxs) # classic data table, d.scannable, d.metadata\n\n# Shortcuts - single file reloader class\nfrom hdfmap import NexusLoader\n\nscan = NexusLoader('file.hdf')\n[data1, data2] = scan.get_data(['dataset_name_1', 'dataset_name_2'])\ndata = scan.eval('dataset_name_1 * 100 + 2')\nstring = scan.format('my data is {dataset_name_1:.2f}')\n\n# Shortcuts - multifile load data (generate map from first file)\nfrom hdfmap import hdf_data, hdf_eval, hdf_format, hdf_image\n\nall_data = hdf_data([f'file{n}.nxs' for n in range(100)], 'dataset_name')\nnormalised_data = hdf_eval(filenames, 'total / Transmission / (rc / 300.)')\ndescriptions = hdf_format(filenames, 'Energy: {en:5.3f} keV')\nimage_stack = hdf_image(filenames, index=31)\n```\n\n### Installation\n*Requires:* Python >=3.10, Numpy, h5py\n\n#### from PyPI\n```bash\npython -m pip install hdfmap\n```\n\n#### from GitHub\n```bash\npython -m pip install --upgrade git+https://github.com/DiamondLightSource/hdfmap.git\n```\n\n### Description\nAnother generic hdf reader but the idea here is to build up a namespace dict of `{'name': 'path'}` \nfor every dataset, then group them in hopefully a useful way. \n\nObjects within the HDF file are separated into Groups and Datasets. Each object has a\ndefined 'path' and 'name' paramater, as well as other attributes\n\n - path -> '/entry/measurement/data' -> the location of an object within the file\n - name -> 'data' -> an path expressed as a simple variable name\n\nPaths are unique locations within the file but can be used to identify similar objects in other files\nNames may not be unique within a file and are generated from the path.\n\n| | **name** | **path** |\n|---------------|------------------------------|--------------------------------------|\n| *Description* | simple identifier of dataset | hdf path built from position in file |\n| *Example* | `'scan_command'` | `'/entry/scan_command'` |\n\nNames of different types of datasets are stored for arrays (size > 0) and values (size 0)\nNames for scannables relate to all arrays of a particular size\nA combined list of names is provided where scannables > arrays > values\n\n### HdfMap Attributes\n| | |\n|----------------|--------------------------------------------------------|\n| map.groups | stores attributes of each group by path |\n| map.classes | stores list of group paths by nx_class |\n| map.datasets | stores attributes of each dataset by path |\n| map.arrays | stores array dataset paths by name |\n| map.values | stores value dataset paths by name |\n| map.scannables | stores array dataset paths with given size, by name |\n| map.combined | stores array and value paths (arrays overwrite values) |\n| map.image_data | stores dataset paths of image data |\n\n#### E.G.\n```python\nmap.groups = {'/hdf/group': ('class', 'name', {attrs}, [datasets])}\nmap.classes = {'class_name': ['/hdf/group1', '/hdf/group2']}\nmap.datasets = {'/hdf/group/dataset': ('name', size, shape, {attrs})}\nmap.arrays = {'name': '/hdf/group/dataset'}\nmap.values = {'name': '/hdf/group/dataset'}\nmap.scannables = {'name': '/hdf/group/dataset'}\nmap.image_data = {'name': '/hdf/group/dataset'}\n```\n\n\n### HdfMap Methods\n| | |\n|---------------------------------------------------|-----------------------------------------------------------------------------|\n| `map.populate(h5py.File)` | populates the dictionaries using the given file |\n| `map.generate_scannables(array_size)` | populates scannables namespace with arrays of same size |\n| `map.most_common_size()` | returns the most common dataset size > 1 |\n| `map.get_attr('name_or_path', 'attr')` | return value of dataset attribute |\n| `map.get_path('name_or_group_or_class')` | returns path of object with name |\n| `map.get_image_path()` | returns default path of detector dataset (or largest dataset) |\n| `map.get_group_path('name_or_path_or_class')` | return path of group with class |\n| `map.get_group_datasets('name_or_path_or_class')` | return list of dataset paths in class |\n| `map.find_groups(*names_or_classes)` | return list of group paths matching given group names or classes |\n| `map.find_datasets(*names_or_classes)` | return list of dataset paths matching given names, classes or attributes |\n| `map.find_paths('string')` | return list of dataset paths containing string |\n| `map.find_names('string')` | return list of dataset names containing string |\n| `map.find_attr('attr_name')` | return list of paths of groups or datasets containing attribute 'attr_name' |\n\n\n### HdfMap File Methods\n| | |\n|------------------------------------------|-------------------------------------------------------|\n| `map.get_metadata(h5py.File)` | returns dict of value datasets |\n| `map.get_scannables(h5py.File)` | returns dict of scannable datasets |\n| `map.get_scannalbes_array(h5py.File)` | returns numpy array of scannable datasets |\n| `map.get_dataholder(h5py.File)` | returns dict like object with metadata and scannables |\n| `map.get_image(h5py.File, index)` | returns image data |\n| `map.get_data(h5py.File, 'name')` | returns data from dataset |\n| `map.eval(h5py.File, 'expression')` | returns output of expression using dataset names |\n| `map.format(h5py.File, 'string {name}')` | returns output of str expression |\n\n\n### NeXus Files\nFiles using the [NeXus Format](https://www.nexusformat.org/) can generate special NexusMap objects.\nThese work in the same way as the general HdfMaps but contain additional special names in the namespace:\n\n| | |\n|----------------|------------------------------------|\n| `'axes'` | returns path of default NXaxes |\n| `'signal'` | returns path of default NXsignal |\n\nIn addition, the `map.scannables` dict will be populated automatically by the names given in the \"scan_fields\" dataset\nor by datasets from the first *NXdata* group. The default *image* data will be taken from the first \n*NXdetector* dataset.\n\n\n## Examples\n### scan data & metadata\nSeparate datasets in a NeXus file into Diamond's classic scannables and metadata, similar to what was in the old\n'*.dat' files.\n\n```python\nfrom hdfmap import create_nexus_map, load_hdf\n\n# HdfMap from NeXus file:\nhmap = create_nexus_map('file.nxs')\nwith load_hdf('file.nxs') as nxs:\n scannables = hmap.get_scannables_array(nxs) # creates 2D numpy array\n labels = scannables.dtype.names\n metadata = hmap.get_metadata(nxs) # {'name': value}\n d = hmap.get_dataholder(nxs) # classic data table, d.scannable, d.metadata\nd.theta == d['theta'] # scannable array 'theta'\nd.metadata.scan_command == d.metadata['scan_command'] # single value 'scan_command'\n\n# OR, use the shortcut:\nfrom hdfmap import nexus_data_block\n\nd = nexus_data_block('file.nxs')\n\n# The data loader class removes the need to open the files:\nfrom hdfmap import NexusLoader\n\nscan = NexusLoader('file.nxs')\nmetadata = scan.get_metadata()\nscannables = scan.get_scannables()\n```\n\n### automatic default plot axes\nIf defined in the nexus file, 'axes' and 'signal' will be populated automatically\n\n```python\nimport matplotlib.pyplot as plt\nfrom hdfmap import create_nexus_map, load_hdf\n\n# HdfMap from NeXus file:\nhmap = create_nexus_map('file.nxs')\nwith load_hdf('file.nxs') as nxs:\n axes = hmap.get_data(nxs, 'axes')\n signal = hmap.get_data(nxs, 'signal')\n title = hmap.format_hdf(nxs, \"{entry_identifier}\\n{scan_command}\")\naxes_label = hmap.get_path('axes')\nsignal_label = hmap.get_path('signal')\n# plot the data (e.g. using matplotlib)\nplt.figure()\nplt.plot(axes, signal)\nplt.xlabel(axes_label)\nplt.ylabel(signal_label)\nplt.title(title)\n\n# Or, using NexusLoader:\nfrom hdfmap import NexusLoader\n\nscan = NexusLoader('file.nxs')\naxes, signal = scan('axes, signal')\naxes_label, signal_label = scan('_axes, _signal')\ntitle = scan.format(\"{entry_identifier}\\n{scan_command}\")\n```\n\n### Automatic image data\nGet images from the first detector in a NeXus file\n\n```python\nfrom hdfmap import create_nexus_map, load_hdf\n\n# HdfMap from NeXus file:\nhmap = create_nexus_map('file.nxs')\nimage_location = hmap.get_image_path() # returns the hdf path chosen for the default detector\nwith load_hdf('file.nxs') as nxs:\n middle_image = hmap.get_image(nxs) # returns single image from index len(dataset)//2\n first_image = hmap.get_image(nxs, 0) # returns single image from dataset[0, :, :]\n volume = hmap.get_image(nxs, ()) # returns whole volume as array\n roi = hmap.get_image(nxs, (0, slice(5, 10, 1), slice(5, 10, 1))) # returns part of dataset\n\n# Or, using NexusLoader:\nfrom hdfmap import NexusLoader\n\nscan = NexusLoader('file.nxs')\nimage = scan.get_image(index=0) # using index as defined above\n```\n\n### Multi-scan metadata string\nGenerate a metadata string from every file in a directory very quickly. The HdfMap is only created for the first file,\nthe remaining files are treated as having identical structure.\n```python\nfrom hdfmap import list_files, hdf_format\n\nformat_string = \"#{entry_identifier}: {start_time} : E={incident_energy:.3f} keV : {scan_command}\"\nfiles = list_files('/directoy/path', extension='.nxs')\nstrings_list = hdf_format(files, format_string)\nprint('\\n'.join(strings_list))\n\n# other multi-file readers:\nfrom hdfmap import hdf_data, hdf_image, hdf_eval\n\ndata_list = hdf_data(files, 'incident_energy')\nimage_list = hdf_image(files, index=0)\ndata_list = hdf_eval(files, 'signal / Transmission')\n```\n\n### Metadata Evaluation \nFunctionality for namespace evaluation of the hdf file allows for a number of rules allowing easy extraction\nof formatted metadata. The Evaluation functions are:\n\n - `HdfMap.eval(hdfobj, 'name')` -> value\n - `HdfMap.format_hdf(hdfobj, '{name}')` -> string\n - `HdfLoader('eval')` -> value\n - `HdfLoader.eval('eval')` -> value\n - `HdfLoader.format('{name}')` -> string\n - `hdf_eval([files], 'name')` -> list[values]\n - `hdf_format([files], '{name}')` -> list[string]\n\n#### eval vs format\nEvaluation functions evaluate the expression as given, replacing names in the hdfmap namespace with their associated\nvalues, or using the rules below. The format functions allow the input of python \n[f-strings](https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting),\nallowing precise formatting to be applied and returning a string.\n\n#### Rules\nThe following patterns are allowed in any expression:\n - 'filename': str, name of hdf_file\n - 'filepath': str, full path of hdf_file\n - '_*name*': str hdf path of *name*\n - '__*name*': str internal name of *name* (e.g. for 'axes')\n - 's_*name*': string representation of dataset (includes units if available)\n - '*name*@attr': returns attribute of dataset *name*\n - '*name*?(default)': returns default if *name* doesn't exist\n - '(name1|name2|name3)': returns the first available of the names\n - '(name1|name2@(default))': returns the first available name or default\n\n#### Examples\n```python\nfrom hdfmap import create_nexus_map, load_hdf\n\n# HdfMap from NeXus file:\nhmap = create_nexus_map('file.nxs')\nwith load_hdf('file.nxs') as nxs:\n # mathematical array expressions (using np as Numpy)\n data = hmap.eval(nxs, 'int(np.max(total / Transmission / count_time))')\n # return the path of a name\n path = hmap.eval(nxs, '_axes') # -> '/entry/measurement/h'\n # return the real name of a variable\n name = hmap.eval(nxs, '__axes') # -> 'h'\n # return label, using dataset attributes\n label = hmap.eval(nxs, 's_ppy') # example uses @decimals and @units\n # return dataset attributes\n attr = hmap.eval(nxs, 'idgap@units') # -> 'mm'\n # return first available dataset\n cmd = hmap.eval(nxs, '(cmd|title|scan_command)') # -> 'scan hkl ...'\n # return first available or default value\n atten = hmap.eval(nxs, '(gains_atten|atten?(0))') # -> 0\n # python expression using multiple parameters\n pol = hmap.eval(nxs, '\"pol in\" if abs(delta_offset) < 0.1 and abs(thp) > 20 else \"pol out\"')\n # formatted strings\n title = hmap.format_hdf(nxs, '{filename}: {scan_command}')\n hkl = hmap.format_hdf(nxs, '({np.mean(h):.3g},{np.mean(k):.3g},{np.mean(l):.3g})')\n\n# Or, using NexusLoader:\nfrom hdfmap import NexusLoader\n\nscan = NexusLoader('file.nxs')\n# normalised default-signal\nprint(scan('signal / count_time / Transmission / (rc / 300.)'))\n# axes label\nprint(scan.format('{__axes} [{axes@units}]'))\n\n# Or, for multiple-files:\nfrom hdfmap import hdf_eval, hdf_format, list_files\n\nfiles = [f\"file{n}.nxs\" for n in range(10)]\n\nenergy_values = hdf_eval(files, '(en|energy@(8))')\nlist_scans = hdf_format(files, '{filename}: ({np.mean(h):.3g},{np.mean(k):.3g},{np.mean(l):.3g}) : {scan_command})')\nprint('\\n'.join(list_scans))\n```\n",
"bugtrack_url": null,
"license": "Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. \"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. \"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. \"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. \"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License. \"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. \"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. \"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). \"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. \"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\" \"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets \"[]\" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \"printed page\" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ",
"summary": "Map objects within a HDF file and create a dataset namespace",
"version": "0.7.0",
"project_urls": {
"Bug Tracker": "https://github.com/DiamondLightSource/hdfmap",
"Changelog": "https://github.com/DiamondLightSource/hdfmap/blob/master/README.md",
"Documentation": "https://diamondlightsource.github.io/hdfmap/",
"Homepage": "https://github.com/DiamondLightSource/hdfmap",
"Repository": "https://github.com/DiamondLightSource/hdfmap"
},
"split_keywords": [
"nexus"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "f8f6c7cfc1262541e6f3603923a655823fae905c1e081da864ecc41f7314f2a4",
"md5": "8b3aa415bb92b5e86a143a21bc005521",
"sha256": "84dc7f545361334c9d6ec69ba00956e6c39608da2f8d5ea6a19393e70f23d360"
},
"downloads": -1,
"filename": "hdfmap-0.7.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "8b3aa415bb92b5e86a143a21bc005521",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 40845,
"upload_time": "2025-01-08T15:32:20",
"upload_time_iso_8601": "2025-01-08T15:32:20.678130Z",
"url": "https://files.pythonhosted.org/packages/f8/f6/c7cfc1262541e6f3603923a655823fae905c1e081da864ecc41f7314f2a4/hdfmap-0.7.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "532df7b552a79528c261d1bbb5ba844aca8cef267245c3d8c438498580050658",
"md5": "6cea1a91847dccfa1c12e63b3d0481b5",
"sha256": "0c28a63f91f467c282bccbe31566ea685505dfd8cd0decc0eaf185cbcfabefa3"
},
"downloads": -1,
"filename": "hdfmap-0.7.0.tar.gz",
"has_sig": false,
"md5_digest": "6cea1a91847dccfa1c12e63b3d0481b5",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 47232,
"upload_time": "2025-01-08T15:32:25",
"upload_time_iso_8601": "2025-01-08T15:32:25.864683Z",
"url": "https://files.pythonhosted.org/packages/53/2d/f7b552a79528c261d1bbb5ba844aca8cef267245c3d8c438498580050658/hdfmap-0.7.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-01-08 15:32:25",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "DiamondLightSource",
"github_project": "hdfmap",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "hdfmap"
}