Code Description¶
MMG_Toolbox¶
Magnetic Materials Group Toolbox
Experiment
¶
Experiment class Monitors data folders for scan files and provies a convenient way to load scan data using only a scan number.
E.G. from mmg_toolbox import Experiment exp = Experiment('path/to/folder1', 'path/to/folder2', instrument='i06') print(scan) scan = exp.scan(-1) # latest scan scan_list = exp.scans(range(12345, 12355)) data = exp.join_scan_data(range(-100, 0), data_fields=['cmd', 'Ta']) # returns dict of arrays
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_paths
|
str
|
file directories containing .nxs files |
()
|
instrument
|
str | None
|
instrument name for configuration. |
None
|
Source code in mmg_toolbox/utils/experiment.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | |
add_data_paths(*folder_paths)
¶
Add additional paths
Source code in mmg_toolbox/utils/experiment.py
add_roi(name, cen_i, cen_j, wid_i=30, wid_j=30, image_name='IMAGE')
¶
Add an image ROI (region of interest) to scans The ROI operates on the default IMAGE dataset, loading only the required region from the file. The following expressions will be added, for use in self.eval etc. name -> returns the whole ROI array as a HDF5 dataset name_total -> returns the sum of each image in the ROI array name_max -> returns the max of each image in the ROI array name_min -> returns the min of each image in the ROI array name_mean -> returns the mean of each image in the ROI array name_bkg -> returns the background ROI array (area around ROI) name_rmbkg -> returns the total with background subtracted name_box -> returns the pixel positions of the ROI corners name_bkg_box -> returns the pixel positions of the background ROI
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
string name of the ROI |
required |
cen_i
|
int | str
|
central pixel index along first dimension, can be callable string |
required |
cen_j
|
int | str
|
central pixel index along second dimension, can be callable string |
required |
wid_i
|
int
|
full width along first dimension, in pixels |
30
|
wid_j
|
int
|
full width along second dimension, in pixels |
30
|
image_name
|
str
|
string name of the image |
'IMAGE'
|
Source code in mmg_toolbox/utils/experiment.py
all_scans_str(metadata_str=None, hdf_map=None)
¶
Return string descriptions for all files
Source code in mmg_toolbox/utils/experiment.py
find_scans(*scan_files, hdf_map=None, first_only=False, **matches)
¶
Find scans files with matching metadata
matches = {
'name1': 'scan', # matches if 'scan' in file['name1']
'name2': value, # matches if file['name2'] ~= value
'name3': (value, tol), # matches if abs(file['name3'] - value) < tol
}
match_files = find_scans(*filenames, **matches)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scan_files
|
int | str
|
set of scan numbers or filenames, if not given will search all scans in folder. |
()
|
hdf_map
|
NexusMap | None
|
if given, uses this hdfmap rather than generating one. |
None
|
first_only
|
bool
|
if true, returns on the first result |
False
|
matches
|
str | float | tuple[float, float]
|
keyword arguments for matching parameters |
{}
|
Returns:
| Type | Description |
|---|---|
list[NexusScan]
|
list of scan files that match all requirements |
Source code in mmg_toolbox/utils/experiment.py
generate_mesh(*scan_files, hdf_map=None, axes='axes', signal='axes', values=None)
¶
Generate 2D mesh from scan or scans
x, y, z = generate_mesh(*range(-10, 0), axes='eta', signal='roi2_sum', values='Tsample')
# or, if scan 12345 is a 2D grid scan
x, y, z = generate_mesh(12345, axes=('sx', 'sy'), signal='roi2_sum')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scan_files
|
int | str
|
multiple files or single 2D grid scan |
()
|
hdf_map
|
NexusMap | None
|
hdfmap.NeXus map, or None to generate |
None
|
axes
|
str | tuple[str, str]
|
x-axis name, or for grid scans the names of ('xaxis', 'yaxis') |
'axes'
|
signal
|
str
|
signal name |
'axes'
|
values
|
str | None
|
name of the value that changes between multiple files |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
X, Y, IMAGE rank 2 arrays |
Source code in mmg_toolbox/utils/experiment.py
generate_scans_title(*scan_files, metadata_str=None, hdf_map=None)
¶
Generate title from multiple scan files
Source code in mmg_toolbox/utils/experiment.py
get_all_data(*fields, default=np.array([0.0]))
¶
Return dict of data for all files
get_scan_filename(scan_file=-1)
¶
Return the full filename of a scan number
Source code in mmg_toolbox/utils/experiment.py
join_scan_data(*scan_files, hdf_map=None, data_fields=None, default=np.array([0.0]))
¶
Join data from scans
Source code in mmg_toolbox/utils/experiment.py
load_xas(*scan_files, sample_name='', element_edge=None, mode='all', dls_loader=False, match_metadata=True, temp_tol=1.0, field_tol=0.1)
¶
Read XAS spectra - see xas.SpectraContainer
spectra_list = exp.load_xas(12345, 12346, mode='TEY', match_metadata=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scan_files
|
int | str
|
List of filenames or scan numbers in folder |
()
|
sample_name
|
str | None
|
sample name, e.g. 'sample1' or None to load from NeXus file |
''
|
element_edge
|
str | None
|
element edge, e.g. 'FeL3' or None to determine from energy range |
None
|
mode
|
str | list[str]
|
detector values to load, 'all', 'default' or e.g. 'tey', 'tfy' as specified in file |
'all'
|
dls_loader
|
bool
|
bool, if True uses explicit loading of metadata from DLS MMG beamlines |
False
|
match_metadata
|
bool
|
bool, if True uses metadata to determine from sample name |
True
|
temp_tol
|
float
|
Tolerance for temperature comparison (default: 0.1 K) |
1.0
|
field_tol
|
float
|
Tolerance for field comparison (default: 0.1 T) |
0.1
|
Returns:
| Type | Description |
|---|---|
list[SpectraContainer]
|
List of SpectraContainer objects containing XAS spectra |
Source code in mmg_toolbox/utils/experiment.py
scan(scan_file=-1)
¶
scan_str(scan_file=0, metadata_str=None, hdf_map=None)
¶
Read scan file and return metadata string
Source code in mmg_toolbox/utils/experiment.py
scans(*scan_files, hdf_map=None)
¶
Read Nexus files as lazy NexusScan. All files use the same HdfMap, based on the first scan
Source code in mmg_toolbox/utils/experiment.py
scans_str(*scan_files, metadata_str=None, hdf_map=None)
¶
Return list of string descriptions for multiple files
Source code in mmg_toolbox/utils/experiment.py
xas_polarised_spectra(*scan_files, sample_name='', element_edge=None, mode='all', dls_loader=False, match_metadata=True, temp_tol=1.0, field_tol=0.1)
¶
Read XAS spectra - see xas.SpectraContainer
pol1, pol2 = exp.xas_polarised_spectra(12345, 12346, mode='TEY', match_metadata=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scan_files
|
int | str
|
List of filenames or scan numbers in folder |
()
|
sample_name
|
str | None
|
sample name, e.g. 'sample1' or None to load from NeXus file |
''
|
element_edge
|
str | None
|
element edge, e.g. 'FeL3' or None to determine from energy range |
None
|
mode
|
str | list[str]
|
detector values to load, 'all', 'default' or e.g. 'tey', 'tfy' as specified in file |
'all'
|
dls_loader
|
bool
|
bool, if True uses explicit loading of metadata from DLS MMG beamlines |
False
|
match_metadata
|
bool
|
bool, if True uses metadata to determine from sample name |
True
|
temp_tol
|
float
|
Tolerance for temperature comparison (default: 0.1 K) |
1.0
|
field_tol
|
float
|
Tolerance for field comparison (default: 0.1 T) |
0.1
|
Returns:
| Type | Description |
|---|---|
tuple[SpectraContainer, SpectraContainer]
|
pol1, pol2 SpectraContainer objects containing averaged XAS spectra |
Source code in mmg_toolbox/utils/experiment.py
NexusDataHolder
¶
Bases: DataHolder, NexusScan
Nexus data holder class - Automatically reads scannable and metadata from file - acts like the old .dat DataHolder class - has additional functions to read data from NeXus file
Example: scan = NexusDataHolder('12345.nxs') scan.eta -> returns array scan.metadata.metadata -> returns value scan('signal') -> evaluate expression
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | None
|
path to Nexus file |
required |
hdf_map
|
NexusMap | None
|
NexusMap object or None to generate |
None
|
flatten_scannables
|
bool
|
if True, flattens all scannable arrays to 1D |
True
|
Source code in mmg_toolbox/nexus/nexus_scan.py
NexusScan
¶
Bases: NexusLoader
Light-weight NeXus file reader
Example: >>> scan = NexusScan('scan.nxs') >>> scan('scan_command') 'scan x ...' >>> x, y = scan('axes, signal / monitor') >>> scan.plot() # default plot >>> scan.plot.image() # other plot options >>> result = scan.fit.multi_peak_fit() >>> print(scan) # print scan default metadata >>> print(scan.info()) # print scan namespace >>> scan.map.add_roi('name', ...) # add ROI to namespace >>> scan.image(0) # return first detector image as array >>> scan.volume() # return image stack >>> data = scan.get_plot_data() # return dict of plot data
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nxs_filename
|
str
|
path to nexus file |
required |
hdf_map
|
NexusMap | None
|
NexusMap object or None |
None
|
config
|
dict | None
|
configuration dict |
None
|
Source code in mmg_toolbox/nexus/nexus_scan.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
arrays(*args, units='', default=np.array([np.nan]))
¶
Return Numpy arrays
Source code in mmg_toolbox/nexus/nexus_scan.py
datasets(*args)
¶
Return HDF5 datasets from NeXus file (leaves file in open state)
get_plot_axis(axis_name, reduce_shape=True, flatten=False)
¶
Return plot axis data and label for given axis name
>>> data, label = scan.get_plot_axis('axes', flatten=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis_name
|
str
|
axis name as given in self.map |
required |
reduce_shape
|
bool
|
reduces shape (summing additional axes) of >2D arrays to self.map.scannables_shape |
True
|
flatten
|
bool
|
flattens output if True |
False
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, str]
|
(data, label) tuple |
Source code in mmg_toolbox/nexus/nexus_scan.py
get_plot_data(x_axis=None, *y_axis, z_axis=None)
¶
Return dict of plottable data
>>> data = scan.get_plot_data('axes', 'signal')
>>> plt.plot(data['x'], data['y'])
>>> plt.xlabel(data['xlabel'])
>>> plt.ylabel(data['ylabel'])
>>> plt.title(data['title'])
>>> plt.legend(data['legend'])
:param x_axis: axis name or expression as given in self.map
:param y_axis: axis name or expression as given in self.map
:param z_axis: axis name or expression as given in self.map
:returns: {
'xlabel': str label of first axes
'ylabel': str label of first signal
'xdata': flattened array of first axes
'ydata': flattened array of first signal
'axes_names': list of axes names,
'signal_names': list of signal + auxiliary signal names,
'axes_data': list of ND arrays of data for axes,
'signal_data': list of ND array of data for signal + auxiliary signals,
'axes_labels': list of axes labels as 'name [units]',
'signal_labels': list of signal labels,
'data': dict of all scannables axes,
'title': str title as 'filename
NXtitle' if dataset is a 2D grid scan, additional rows: 'grid_xlabel': str label of grid x-axis 'grid_ylabel': str label of grid y-axis 'grid_label': str label of height or colour 'grid_xdata': 2D array of x-coordinates 'grid_ydata': 2D array of y-coordinates 'grid_data': 2D array of height or colour }
Source code in mmg_toolbox/nexus/nexus_scan.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | |
hdf_find(*field_or_class, find_all=False)
¶
Find datasets and groups within hdf file
>>> HdfDataset = scan.hdf_find('NXentry', ['NXdata', 'measurement'], 'signal')
Warning: HDF file stays in open state while Dataset or Group objects exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_or_class
|
str | list[str]
|
names to search for, in hierarchical order. Lists treated as OR |
()
|
find_all
|
bool
|
whether to return all datasets or only the first match |
False
|
Returns:
| Type | Description |
|---|---|
Dataset | Group | list[Dataset | Group]
|
matching Dataset or Group, or list of matching Datasets or Groups |
Source code in mmg_toolbox/nexus/nexus_scan.py
hdf_tree_string(group='/', all_links=True, attributes=True)
¶
Generate string of the hdf file structure, similar to h5ls. Uses h5py.visititems
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_links
|
bool
|
bool, if True, also show links |
True
|
group
|
str
|
only display tree structure of this group (default root) |
'/'
|
attributes
|
bool
|
if True, display the attributes of groups and datasets |
True
|
Returns:
| Type | Description |
|---|---|
str
|
str |
Source code in mmg_toolbox/nexus/nexus_scan.py
image(index=None)
¶
Return image or selection from default detector
Source code in mmg_toolbox/nexus/nexus_scan.py
image_background(index=(), n_bins=100)
¶
Return the modal value of the detector image, which usually gives the background value.
The modal value is determined by histograming the image (or image stack) and taking the value of the largest bin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | tuple | slice | str | None
|
index of image to return, use () for full image stack. |
()
|
n_bins
|
int
|
number of histogram bins |
100
|
Returns:
| Type | Description |
|---|---|
ndarray
|
modal value or values per image |
Source code in mmg_toolbox/nexus/nexus_scan.py
info(arrays=False, values=False, combined=False, metadata=False, scannables=True, image_data=True, local=False, alternate=True)
¶
Return string of namespace information
Source code in mmg_toolbox/nexus/nexus_scan.py
instrument_model()
¶
load_hdf()
¶
metadata_str(expression=None)
¶
Generate metadata string from beamline config
strings(*args, units=False)
¶
table(delimiter=', ', string_spec='', format_spec='f', default_decimals=8)
¶
Return data table
Source code in mmg_toolbox/nexus/nexus_scan.py
times(*args)
¶
Return datetime object
Source code in mmg_toolbox/nexus/nexus_scan.py
values(*args, value_func=np.mean, units='', default=np.array(np.nan))
¶
Return float values
Source code in mmg_toolbox/nexus/nexus_scan.py
volume()
¶
xas_spectra(sample_name=None, element_edge=None, mode='all', dls_loader=False)
¶
Load XAS Spectra from the scan file
>>> spectra = scan.xas_spectra()
>>> spectra = spectra.remove_background('slope')
>>> spectra.plot()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_name
|
str | None
|
sample name, e.g. 'sample1' or None to load from NeXus file |
None
|
element_edge
|
str | None
|
element edge, e.g. 'FeL3' or None to determine from energy range |
None
|
mode
|
str | list[str]
|
detector values to load, 'all', 'default' or e.g. 'tey', 'tfy' as specified in file |
'all'
|
dls_loader
|
bool
|
bool, if True uses explicit loading of metadata from DLS MMG beamlines |
False
|
Returns:
| Type | Description |
|---|---|
SpectraContainer
|
SpectraContainer |
Source code in mmg_toolbox/nexus/nexus_scan.py
create_notebooks(directory=None, beamline=None, start_jupyter=None, prefix='', quiet=False)
¶
Create notebooks at start of experiment
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | None
|
directory where to create notebooks, or visit ID for current beamline |
None
|
beamline
|
str | None
|
Beamline name, e.g. i06-1 |
None
|
start_jupyter
|
bool | None
|
start jupyter lab |
None
|
prefix
|
str
|
prefix for notebook/ script filenames |
''
|
quiet
|
bool
|
quiet mode (no user inputs) |
False
|
Source code in mmg_toolbox/scripts/experiment_startup.py
data_file_reader(filename, beamline=None)
¶
Read Nexus or dat file as DataHolder
Source code in mmg_toolbox/utils/file_reader.py
find_scan_files(scan_file, directory=None, instrument=None, extension='.nxs')
¶
Recursively search a directory for scan files, returns a generator
fn = find_scan_files(12345, '/dls/i16/data')
filepath = next(fn, None) # returns first filepath with '12345' in the title
all_paths = list(fn)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scan_file
|
str | int
|
scan number or part of filename |
required |
directory
|
str | None
|
directory to search for scan files, or None to use instrument |
None
|
instrument
|
str | None
|
if directory is None, use instrument to use DLS data directory (None to use current beamline) |
None
|
extension
|
str
|
extension to search for scan files |
'.nxs'
|
Returns:
| Type | Description |
|---|---|
Iterator[str]
|
generator object for search |
Source code in mmg_toolbox/utils/env_functions.py
get_dls_visits(instrument=None, year=None, max_visits=None, omit_empty=False)
¶
Return dict of {visit: path} for each visible visit in the beamline directory
visits = get_dls_visits('i16')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instrument
|
str | None
|
displays visits for this instrument, or None for current beamline. |
None
|
year
|
str | int | None
|
displays visits in this year, or None for current year. |
None
|
max_visits
|
int | None
|
maximum number of visits to display, nor None for all visits |
None
|
omit_empty
|
bool
|
if True, omits visits containing no scans |
False
|
Source code in mmg_toolbox/utils/env_functions.py
get_dls_visits_str(instrument=None, year=None, max_visits=3, omit_empty=True)
¶
Return str of visits for each visible visit int he beamline directory
print(get_dls_visits_str('i16', 2025))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instrument
|
str | None
|
displays visits for this instrument, or None for current beamline. |
None
|
year
|
str | int | None
|
displays visits in this year, or None for current year. |
None
|
max_visits
|
int | None
|
maximum number of visits to display, nor None for all visits |
3
|
omit_empty
|
bool
|
if True, omits visits containing no scans |
True
|
Returns:
| Type | Description |
|---|---|
str
|
multiline string |
Source code in mmg_toolbox/utils/env_functions.py
scan_number_mapping(*folders, extension='.nxs')
¶
Build mapping of scan number to scan file