NRSS.morphology#

exception NRSS.morphology.BackendUnavailableError#

Bases: BackendSelectionError

Raised 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: OpticalConstants

Object 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: object

Object 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.

  • subsample (int) – Number of voxels to display in X and Y

  • translate_x (int) – Number of voxels to translate image in x; meant for use with subsample

  • translate_y (int) – Number of voxels to translate image in y; meant for use with subsample

  • screen_euler (bool) – Suppress visualization of euler angles where vfrac < 0.05 or S < 0.05; intended to hilight edges

  • 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: object

Object 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#

Bases: object

Parameter specification variable.

The preferred way to construct a parameter specification is via the dedicated syntax for generic functions, classes, and type aliases, where the use of ‘**’ creates a parameter specification:

type IntFunc[**P] = Callable[P, int]

The following syntax creates a parameter specification that defaults to a callable accepting two positional-only arguments of types int and str:

type IntFuncDefault[**P = [int, str]] = Callable[P, int]

For compatibility with Python 3.11 and earlier, ParamSpec objects can also be created as follows:

P = ParamSpec('P')
DefaultP = ParamSpec('DefaultP', default=[int, str])

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 as the first argument to Callable, or as parameters for user-defined Generics. See class Generic for more information on generic types.

An example for annotating a decorator:

def add_logging[**P, T](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 can be introspected. e.g.:

>>> P = ParamSpec("P")
>>> P.__name__
'P'

Note that only parameter specification variables defined in the global scope can be pickled.

args#

Represents positional arguments.

has_default()#
kwargs#

Represents keyword arguments.

class NRSS.morphology.SFieldMode(*values)#

Bases: Enum

Special contract values accepted for Material.S.

SFieldMode.ISOTROPIC declares that the material is explicitly isotropic, so orientation fields are not needed. When this contract is used correctly, NRSS can avoid carrying full S, theta, and psi arrays for that material through the backend, which can dramatically reduce memory footprint and improve runtime.

ISOTROPIC = False#
class NRSS.morphology.TypeVar#

Bases: object

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bound and constrained type variables:

# S is a TypeVar bound to str
class StrSequence[S: str]:
    ...

# A is a TypeVar constrained to str or bytes
class StrOrBytesSequence[A: (str, bytes)]:
    ...

Type variables can also have defaults:

class IntDefault[T = int]:

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes
D = TypeVar('D', default=int)  # Defaults to int

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 and type alias definitions.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax and when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

has_default()#
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, subsample: int = None, translate_x: int = None, translate_y: int = None, screen_euler: bool = True, add_quiver: bool = False, quiver_bw: bool = True, outputmat: list = None, outputplot: list = None, outputaxes: bool = True, vfrac_range: list = None, S_range: list = None, vfrac_cmap: str = None, S_cmap: str = 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, exportParams: dict = 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.

  • subsample (int) – Number of voxels to display in X and Y

  • translate_x (int) – Number of voxels to translate image in x; meant for use with subsample

  • translate_y (int) – Number of voxels to translate image in y; meant for use with subsample

  • screen_euler (bool) – Suppress visualization of euler angles where vfrac < 0.05 or S < 0.05; intended to hilight edges

  • 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)#