NRSS.morphology#
Bases:
BackendSelectionErrorRaised when a known backend is not currently runnable.
- class NRSS.morphology.Material(materialID=1, Vfrac=None, S=None, theta=None, psi=None, NumZYX=None, energies=None, opt_constants=None, name=None)#
Bases:
OpticalConstantsObject to hold the voxel-level data for an NRSS morphology. Inherits from the OpticalConstants class.
- materialID#
Integer value denoting the material number. Used in CyRSoXS
- Type:
int
- Vfrac#
Volume fractions for a Material
- Type:
ndarray
- S#
Orientational order parameter field, or SFieldMode.ISOTROPIC for the explicit full-material isotropic contract
- Type:
ndarray or SFieldMode
- theta#
The second Euler angle (ZYZ convention)
- Type:
ndarray
- psi#
The third Euler angle (ZYZ convention)
- Type:
ndarray
- NumZYX#
Dimensions of the Material arrays (NumZ, NumY, NumX)
- Type:
tuple or list
- name#
Name of the Material (e.g. ‘Polystyrene’)
- Type:
str
- copy()#
- class NRSS.morphology.Morphology(numMaterial, materials=None, PhysSize=None, config={'CaseType': 0, 'EAngleRotation': [0.0, 1.0, 0.0], 'Energies': [270.0], 'MorphologyType': 0}, create_cy_object=True, backend=None, backend_options=None, resident_mode=None, input_policy='coerce', output_policy='numpy', ownership_policy=None)#
Bases:
objectObject used to hold the components necessary for a complete NRSS morphology and its backend execution contract.
- input_mapping#
A dictionary to handle specific configuration input types
- Type:
dict
- numMaterial#
Number of materials present in the morphology
- Type:
int
- materials#
A dictionary of Material objects
- Type:
dict
- PhysSize#
The physical size of each cubic voxel’s three dimensions
- Type:
float
- NumZYX#
Number of voxels in the Z, Y, and X directions (NumZ, NumY, NumX)
- Type:
tuple or list
- config#
A dictionary of configuration parameters for CyRSoXS
- Type:
dict
- create_cy_object#
Boolean value that decides if the CyRSoXS objects are created upon instantiation
- Type:
bool
- simulated#
Boolean value that tracks whether or not the simulation has been run
- Type:
bool
- load_morph_hdf5(hdf5_file, create_cy_object=True)#
Class method that creates a Morphology object from a morphology HDF5 file
- create_inputData()#
Creates a CyRSoXS InputData object and populates it with parameters from self.config
- create_optical_constants()#
Creates a CyRSoXS RefractiveIndex object and populates it with optical constants from the materials dict
- create_voxel_data()#
Creates a CyRSoXS VoxelData object and populates it with the voxel information from the materials dict
- run(stdout=True, stderr=True, return_xarray=True, print_vec_info=False)#
Creates a CyRSoXS ScatteringPattern object if not already created, and submits all CyRSoXS objects to run the simulation
- scattering_to_xarray(return_xarray=True, print_vec_info=False)#
Copies the CyRSoXS ScatteringPattern arrays to an xarray in the format used by PyHyperScattering for further analysis
- property AlgorithmType#
- property CaseType#
- property EAngleRotation#
- property Energies#
- property EwaldsInterpolation#
- property MorphologyType#
- property PhysSize#
- property ReferenceFrame#
- property RotMask#
- property WindowingType#
- property authoritative_array_contract#
- property backend#
- property backend_array_contract#
- property backend_dtype#
- property backend_info#
- property backend_options#
- property backend_timings#
- check_materials(quiet=True)#
- property config#
- config_default = {'AlgorithmType': 0, 'CaseType': 0, 'EAngleRotation': [0.0, 1.0, 0.0], 'Energies': [270.0], 'EwaldsInterpolation': 1, 'MorphologyType': 0, 'ReferenceFrame': 1, 'RotMask': 0, 'WindowingType': 0}#
- config_to_inputData()#
- create_inputData()#
- create_optical_constants()#
- create_update_cy()#
- create_voxel_data()#
- property input_policy#
- load_config(config_file)#
- load_matfile(matfile)#
- classmethod load_morph_hdf5(hdf5_file, create_cy_object=False, backend=None, backend_options=None, resident_mode=None, input_policy='coerce', output_policy='numpy', ownership_policy=None)#
- property mixed_precision_mode#
- normalize_materials_for_backend(report_attr='last_backend_coercion_report')#
- property numMaterial#
- property output_policy#
- property ownership_policy#
- prepare()#
- refresh_backend_assessment()#
- release_runtime()#
- property resident_mode#
- run(stdout=True, stderr=True, return_xarray=True, print_vec_info=False, validate=False)#
- property runtime_compute_contract#
- property runtime_compute_dtype#
- property runtime_dtype#
- scattering_to_xarray(return_xarray=True, print_vec_info=False)#
- property simulated#
- update_optical_constants()#
- update_voxel_data()#
- validate_all(quiet=True)#
- visualize_materials(*args, **kwargs)#
Reads in morphology HDF5 file and checks that the format is consistent for CyRSoXS. Optionally plots and returns select quantities.
- Parameters:
z_slice (int) – Which z-slice of the array to plot for an XY view. Mutually exclusive with y_slice and x_slice.
y_slice (int) – Which y-slice of the array to plot for an XZ view. Mutually exclusive with z_slice and x_slice.
x_slice (int) – Which x-slice of the array to plot for a YZ view. Mutually exclusive with z_slice and y_slice.
subsample (int) – Number of voxels to display along the horizontal and vertical axes of the selected plane.
translate_x (int) – Number of voxels to translate the displayed window along the horizontal axis of the selected plane; meant for use with subsample.
translate_y (int) – Number of voxels to translate the displayed window along the vertical axis of the selected plane; meant for use with subsample.
vertical_slice_aspect (str) – Aspect handling for XZ and YZ views. Use ‘full’ to preserve the full returned panel including its original colorbar-inclusive width, or ‘square’ to center-crop the slice data to a square before plotting. XY views ignore this option.
screen_euler (bool) – Suppress visualization of euler angles where vfrac < screen_euler_vfrac or S < screen_euler_s; intended to hilight edges screen_euler_vfrac : float screen_euler_s : float
add_quiver (bool) – Adds lines to every voxel on the psi plot that indicate in-plane direction. Not recommended for resolutions larger than 128x128, best for resolutions 64x64 or lower.
quiver_bw (bool) – Intended to be used when add_quiver == True, when quiver_bw is True, the quiver arrows will be black and white instead of colored.
outputmat (list of ints) – Number of which materials to return
outputplot (list of strings) – Number of which plots to return, can include ‘vfrac’, ‘S’, ‘theta’, ‘psi’
outputaxes (bool) – If a plot is returned, include its axes
vfrac_range (list of tuples as [float, float]) – A custom range for vfrac colorbar
S_range (list of tuples as [float, float]) – A custom range for S colorbar
vfrac_cmap (str) – A custom substitution for vfrac colormap
S_cmap (str) – A custom substitution for vfrac colormap
runquiet (bool) – Boolean flag for running without plotting or outputting to console
batchMode (bool) – if true, prints console output and generates plots but doesnt show (provide exportDir for export)
plotstyle (str) – Use a light or dark background for plots. ‘dark’ - dark, ‘light’ - light
dpi (int) – The dpi at which the plot is generated. The default figure size is 9.1” x 13.65” unless overridden via Matplotlib rcParams.
histograms (bool) – When True, include the four full-volume histogram panels in interactive display mode.
histogram_mode (str) – Histogram calculation mode: ‘full’ always uses all voxels, ‘sample’ always uses a sample, and ‘auto’ switches to sampling when the voxel count exceeds histogram_sample_threshold.
histogram_sample_size (int) – Number of voxels to use when histogram_mode resolves to sampled histograms.
histogram_sample_threshold (int) – Voxel-count threshold above which histogram_mode=’auto’ switches to sampled histograms.
exportDir (str, optional) – if provided, export directory to save any generated figures into, by default, will respect dpi and save as png, use exportParams to override
exportParams (dict, optional) – additional params to unpack into matplotlib.pyplot.savefig. Overrides existing params. ex: exportParams = {‘dpi’:600, format=’svg’}
- Return type:
If outputmat and outputplot are correctly entered, will return an index list of images of the selected material and plot. Each list element will be a numpy array in RGB format that be displayed with imshow
- write_config()#
- write_constants(path=None)#
- write_to_file(fname, author='NIST')#
- property z_collapse_mode#
- class NRSS.morphology.OpticalConstants(energies, opt_constants=None, name='unknown')#
Bases:
objectObject to hold dielectric optical constants in a format compatible with CyRSoXS
- energies#
List of energies
- Type:
list or array
- opt_constants#
Dictionary of optical constants, where each energy is a key in the dict
- Type:
dict
- name#
String identifying the element or material for these optical constants
- Type:
str
- calc_constants(energies, reference_data, name='unkown')#
Interpolates optical constant data to the list of energies provided
- load_matfile(matfile, name='unknown')#
Creates an OpticalConstants object from a previously written MaterialX.txt file
- create_vacuum(energies)#
Convenience function to populate zeros for all optical constants
- classmethod calc_constants(energies, reference_data, name='unknown')#
- create_vacuum(energies)#
- classmethod load_matfile(matfile, name='unknown')#
- class NRSS.morphology.ParamSpec(name, *, bound=None, covariant=False, contravariant=False)#
Bases:
_Final,_Immutable,_TypeVarLikeParameter specification variable.
Usage:
P = ParamSpec('P')
Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable, a pattern commonly found in higher order functions and decorators. They are only valid when used in
Concatenate, or s the first argument toCallable, or as parameters for user-defined Generics. See class Generic for more information on generic types. An example for annotating a decorator:T = TypeVar('T') P = ParamSpec('P') def add_logging(f: Callable[P, T]) -> Callable[P, T]: '''A type-safe decorator to add logging to a function.''' def inner(*args: P.args, **kwargs: P.kwargs) -> T: logging.info(f'{f.__name__} was called') return f(*args, **kwargs) return inner @add_logging def add_two(x: float, y: float) -> float: '''Add two numbers together.''' return x + y
Parameter specification variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. These keyword arguments are valid, but their actual semantics are yet to be decided. See PEP 612 for details.
Parameter specification variables can be introspected. e.g.:
P.__name__ == ‘T’ P.__bound__ == None P.__covariant__ == False P.__contravariant__ == False
Note that only parameter specification variables defined in global scope can be pickled.
- property args#
- property kwargs#
- class NRSS.morphology.SFieldMode(value)#
Bases:
EnumSpecial contract values accepted for
Material.S.SFieldMode.ISOTROPICdeclares that the material is explicitly isotropic, so orientation fields are not needed. When this contract is used correctly, NRSS can avoid carrying fullS,theta, andpsiarrays for that material through the backend, which can dramatically reduce memory footprint and improve runtime.- ISOTROPIC = False#
- class NRSS.morphology.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)#
Bases:
_Final,_Immutable,_TypeVarLikeType variable.
Usage:
T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes
Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:
- def repeat(x: T, n: int) -> List[T]:
‘’’Return a list containing n references to x.’’’ return [x]*n
- def longest(x: A, y: A) -> A:
‘’’Return the longest of two strings.’’’ return x if len(x) >= len(y) else y
The latter example’s signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str.
At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Type variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables.
Type variables can be introspected. e.g.:
T.__name__ == ‘T’ T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes)
Note that only type variables defined in global scope can be pickled.
- NRSS.morphology.assess_array_for_backend(arr: Any, backend_name: str, field_name: str, material_id: int | None = None, backend_options: Mapping[str, Any] | None = None, resident_mode: str | None = None, contract: Mapping[str, Any] | None = None) ArrayPlan#
- NRSS.morphology.check_NumMat(f, morphology_type)#
Checks and validates the number of materials in the HDF5 file
- Parameters:
f (file object) –
morphology_type (int) – 0 - Euler, 1 - Vector
- Returns:
num_mat – Number of materials in file
- Return type:
int
- NRSS.morphology.coerce_array_for_backend(arr: Any, plan: ArrayPlan)#
- NRSS.morphology.get_backend_info(name: str) BackendInfo#
- NRSS.morphology.get_backend_runtime(backend_name: str) BackendRuntime#
- NRSS.morphology.get_namespace_module(namespace: str)#
- NRSS.morphology.inspect_array(arr: Any) dict[str, Any]#
- NRSS.morphology.is_isotropic_s_field_mode(value) bool#
- NRSS.morphology.morphology_visualizer(morphology, z_slice: int = 0, y_slice: int | None = None, x_slice: int | None = None, subsample: int | None = None, translate_x: int | None = None, translate_y: int | None = None, vertical_slice_aspect: str = 'square', screen_euler: bool = True, screen_euler_vfrac: float = 0.05, screen_euler_s: float = 0.05, add_quiver: bool = False, quiver_bw: bool = True, outputmat: list | None = None, outputplot: list | None = None, outputaxes: bool = True, vfrac_range: list | None = None, S_range: list | None = None, vfrac_cmap: str | None = None, S_cmap: str | None = None, runquiet: bool = False, batchMode: bool = False, plotstyle: str = 'light', dpi: int = 240, histograms: bool = True, histogram_mode: str = 'auto', histogram_sample_size: int = 100000, histogram_sample_threshold: int = 100000, exportDir: str | None = None, exportParams: dict | None = None)#
Reads in morphology HDF5 file and checks that the format is consistent for CyRSoXS. Optionally plots and returns select quantities.
- Parameters:
z_slice (int) – Which z-slice of the array to plot for an XY view. Mutually exclusive with y_slice and x_slice.
y_slice (int) – Which y-slice of the array to plot for an XZ view. Mutually exclusive with z_slice and x_slice.
x_slice (int) – Which x-slice of the array to plot for a YZ view. Mutually exclusive with z_slice and y_slice.
subsample (int) – Number of voxels to display along the horizontal and vertical axes of the selected plane.
translate_x (int) – Number of voxels to translate the displayed window along the horizontal axis of the selected plane; meant for use with subsample.
translate_y (int) – Number of voxels to translate the displayed window along the vertical axis of the selected plane; meant for use with subsample.
vertical_slice_aspect (str) – Aspect handling for XZ and YZ views. Use ‘full’ to preserve the full returned panel including its original colorbar-inclusive width, or ‘square’ to center-crop the slice data to a square before plotting. XY views ignore this option.
screen_euler (bool) – Suppress visualization of euler angles where vfrac < screen_euler_vfrac or S < screen_euler_s; intended to hilight edges screen_euler_vfrac : float screen_euler_s : float
add_quiver (bool) – Adds lines to every voxel on the psi plot that indicate in-plane direction. Not recommended for resolutions larger than 128x128, best for resolutions 64x64 or lower.
quiver_bw (bool) – Intended to be used when add_quiver == True, when quiver_bw is True, the quiver arrows will be black and white instead of colored.
outputmat (list of ints) – Number of which materials to return
outputplot (list of strings) – Number of which plots to return, can include ‘vfrac’, ‘S’, ‘theta’, ‘psi’
outputaxes (bool) – If a plot is returned, include its axes
vfrac_range (list of tuples as [float, float]) – A custom range for vfrac colorbar
S_range (list of tuples as [float, float]) – A custom range for S colorbar
vfrac_cmap (str) – A custom substitution for vfrac colormap
S_cmap (str) – A custom substitution for vfrac colormap
runquiet (bool) – Boolean flag for running without plotting or outputting to console
batchMode (bool) – if true, prints console output and generates plots but doesnt show (provide exportDir for export)
plotstyle (str) – Use a light or dark background for plots. ‘dark’ - dark, ‘light’ - light
dpi (int) – The dpi at which the plot is generated. The default figure size is 9.1” x 13.65” unless overridden via Matplotlib rcParams.
histograms (bool) – When True, include the four full-volume histogram panels in interactive display mode.
histogram_mode (str) – Histogram calculation mode: ‘full’ always uses all voxels, ‘sample’ always uses a sample, and ‘auto’ switches to sampling when the voxel count exceeds histogram_sample_threshold.
histogram_sample_size (int) – Number of voxels to use when histogram_mode resolves to sampled histograms.
histogram_sample_threshold (int) – Voxel-count threshold above which histogram_mode=’auto’ switches to sampled histograms.
exportDir (str, optional) – if provided, export directory to save any generated figures into, by default, will respect dpi and save as png, use exportParams to override
exportParams (dict, optional) – additional params to unpack into matplotlib.pyplot.savefig. Overrides existing params. ex: exportParams = {‘dpi’:600, format=’svg’}
- Return type:
If outputmat and outputplot are correctly entered, will return an index list of images of the selected material and plot. Each list element will be a numpy array in RGB format that be displayed with imshow
- NRSS.morphology.normalize_backend_options(backend_name: str, backend_options: Mapping[str, Any] | None = None) dict[str, Any]#
- NRSS.morphology.normalize_resident_mode(backend_name: str, resident_mode: str | None = None) str#
- NRSS.morphology.read_config(config_file)#
- NRSS.morphology.read_material(filename)#
- NRSS.morphology.resolve_backend_array_contract(backend_name: str, backend_options: Mapping[str, Any] | None = None, resident_mode: str | None = None) dict[str, Any]#
- NRSS.morphology.resolve_backend_name(preferred: str | None = None) str#
- NRSS.morphology.resolve_backend_runtime_contract(backend_name: str, backend_options: Mapping[str, Any] | None = None) dict[str, Any]#
- NRSS.morphology.to_python_bool(value: Any) bool#
- NRSS.morphology.wraps(wrapper: Callable[[P], T]) Callable[[Callable[[P], T]], Callable[[P], T]]#
A decorator to preserve the original function’s docstring.
- Parameters:
wrapper – The wrapper function.
- Returns:
A decorator that preserves the original function’s docstring.
- NRSS.morphology.write_hdf5(material_list, PhysSize, fname, MorphologyType=0, ordering='ZYX', author='NIST')#
Writes Euler or Vector Morphology format into CyRSoXS-compatible HDF5 file and returns the hdf5 filename
- Parameters:
material_list (lists) – List of material lists. Euler Ex. [[Mat_1_Vfrac, Mat_1_S, Mat_1_Theta, Mat_1_Psi],[Mat_2_Vfrac, Mat_2_S, Mat_2_Theta, Mat_2_Psi]] Vector Ex. [[Mat_1_alignment, Mat_1_unaligned],[Mat_2_alignment, Mat_2_unaligned]]
PhysSize (float) – Voxel size
fname (str or path) – name of hdf5 file to write
MorphologyType (int) – 0 - Euler 1 - Vector
ordering (str) – String denoting the axes ordering. ‘ZYX’ or ‘XYZ’
author (str) – Name of author writing the morphology
- Returns:
Name of hdf5 file written
- Return type:
fname
- NRSS.morphology.write_opts(optical_constants, material_num, path)#