This page documents the PyARPES API by generation from signatures and docstrings. You can use this and the source code to supplement the remainder of the PyARPES documentation.
Please note that this is not a complete API documentation page. Less used and internal APIs are not documented here.
Data-loading functions#
|
Loads a piece of data using available plugins. |
|
Provides sample data for executable documentation. |
ExampleData() |
Xarray_extensions#
Establishes the PyARPES data model by extending the xarray types.
This is another core part of PyARPES. It provides a lot of extensions to what comes out of the box in xarray. Some of these are useful generics, generally on the .T extension, others collect and manipulate metadata, interface with plotting routines, provide functional programming utilities, etc.
If f is an ARPES spectrum, then f.S should provide a nice representation of your data in a Jupyter cell. This is a complement to the text based approach that merely printing f offers. Note, as of PyARPES v3.x.y, the xarray version has been bumped and this representation is no longer necessary as one is provided upstream.
The main accessors are .S, .G, and .F.
- The .S accessor:
The .S accessor contains functionality related to spectroscopy. Utilities which only make sense in this context should be placed here, while more generic tools should be placed elsewhere.
- The .G. accessor:
This a general purpose collection of tools which exists to provide conveniences over what already exists in the xarray data model. As an example, there are various tools for simultaneous iteration of data and coordinates here, as well as for vectorized application of functions to data or coordinates.
- The .F accessor:
This is an accessor which contains tools related to interpreting curve fitting results. In particular there are utilities for vectorized extraction of parameters, for plotting several curve fits, or for selecting “worst” or “best” fits according to some measure.
The .S accessor#
- class arpes.xarray_extensions.accessor.property.ARPESAngleProperty[source]#
Bases:
Generic[DataType]Class for Angle related property.
- _obj#
ARPES data
- Type:
XrTypes
Note
This class should not be called directly.
- property sample_angles[source]#
The angle (\(\beta,\,\theta,\,\chi,\,\phi,\,\psi,\,\alpha\)) values.
- Returns: tuple[xr.DataArray | float, …]
beta, theta, chi, phi, psi, alpha
- class arpes.xarray_extensions.accessor.property.ARPESPhysicalProperty[source]#
Bases:
Generic[DataType]Class for ARPES physical properties.
- _obj#
ARPES data
- Type:
XrTypes
Note
This class should not be called directly.
- property analyzer_work_function[source]#
The work function of the analyzer, if present in metadata.
otherwise, use appropriate value.
Note
Use this value for k-conversion.
- property experimental_conditions[source]#
hv, polarization, temperature.
Use this property in plotting/annotations.py/conditions
- Type:
The experimental condition
- property hv[source]#
The photon energy for excitation.
- Returns: float | xr.DataArray
Photon energy in eV unit. (for hv_map type, xr.DataArray is returned.)
- property inner_potential[source]#
The inner potential, if present in metadata. Otherwise, 10 eV is assumed.
- property sherman_function[source]#
Sherman function from attributes.
- Returns: float
Sharman function
- Raises: ValueError
When no Sherman function related value is found.
Todo
Test, Consider if it should be in “S”
- class arpes.xarray_extensions.accessor.property.ARPESInfoProperty[source]#
Bases:
ARPESPhysicalProperty[DataType]Class for Information Property.
- _obj#
ARPES data
- Type:
arpes._typing.base.DataType
Note
This class should not be called directly.
- property beamline_info[source]#
Information about the beamline or light source used for a measurement.
- property daq_info[source]#
General information about the acquisition settings for an ARPES experiment.
- property endstation[source]#
Alias for the location attribute used to load the data.
- Returns:
The name of loader/location which was used to load data.
- property experiment_info[source]#
Experiment information property, such as temperature, pressure, etc.
- property scan_info[source]#
Scan information, measurement data/time, scan type, and sample name, etc.
- property scan_name[source]#
The scan name.
- Returns: (str)
If “scan” or “file” is set in attrs, return the file name. If they are not set, return “id” if “id” is set.
- class arpes.xarray_extensions.accessor.property.ARPESProvenanceProperty[source]#
Bases:
Generic[DataType]Class for Provenance related property.
- property history[source]#
Retrieves the complete processing history (provenance) of the xarray object.
This property extracts nested provenance records stored in the _obj.attrs[“provenance”] attribute. It unwraps these records from the most recent operation back to the original data, forming a chronological list of processing steps.
The provenance information is expected to be stored in a nested dictionary structure where each step has a parents_provenance key pointing to the previous step(s). This method flattens that hierarchical structure into a linear list.
- Returns:
A list of dictionaries, where each dictionary represents a processing step (Provenance record) in the history of the dataset, ordered from the most recent to the oldest. An empty list is returned if no provenance is recorded or if it’s invalid.
- Return type:
list[Provenance]
- Warns:
UserWarning –
If the provenance attribute is found to be a string type, indicating an older or malformed provenance record.
If multiple parents are encountered in a parents_provenance list, as only the first parent will be considered and others ignored.
Examples
Assuming ds is an xr.Dataset with provenance recorded:
>>> # Example setup for a Dataset with nested provenance >>> from arpes_analyzer.history import Provenance # Hypothetical import >>> ds = xr.Dataset() >>> ds.attrs['provenance'] = { ... 'step_name': 'filter', ... 'params': {'kernel_size': 3}, ... 'parents_provenance': { ... 'step_name': 'normalize', ... 'params': {'method': 'max'}, ... 'parents_provenance': { ... 'step_name': 'load_data', ... 'params': {'file': 'data.h5'} ... } ... } ... } >>> accessor = YourARPESAccessor(ds) >>> history_list = accessor.history >>> for entry in history_list: ... print(entry['step_name']) filter normalize load_data
>>> # Example with no provenance >>> ds_no_prov = xr.Dataset() >>> accessor_no_prov = YourARPESAccessor(ds_no_prov) >>> accessor_no_prov.history []
>>> # Example with string provenance (warns) >>> ds_str_prov = xr.Dataset() >>> ds_str_prov.attrs['provenance'] = "Old string provenance record." >>> accessor_str_prov = YourARPESAccessor(ds_str_prov) >>> # This will print a warning and return ['Old string provenance record.'] >>> accessor_str_prov.history ['Old string provenance record.']
- class arpes.xarray_extensions.accessor.property.ARPESOffsetProperty[source]#
Bases:
ARPESAngleProperty[DataType]Class for offset value property.
- _obj#
ARPES data
- Type:
arpes._typing.base.DataType
Note
This class should not be called directly.
- apply_offsets(offsets)[source]#
Applies and records angular offsets to the xarray object’s attributes.
This method iterates through a dictionary of angle types and their corresponding offset values, storing each offset in the _obj.attrs dictionary. The attribute key is formatted as “{angle_type}_offset”.
These offsets are typically used to correct or define the zero-point for various angular dimensions (e.g., k-parallel, polar angle theta).
- Parameters:
offsets (dict[ANGLE, float]) – A dictionary where keys are ANGLE enum members (or similar type representing angle dimensions, e.g., “k_parallel”, “theta”) and values are the float offsets to be applied.
- Returns:
- This method modifies the _obj.attrs in-place and does not
return any value.
- Return type:
None
- Raises:
AssertionError – If the internal _obj is not an instance of xarray.Dataset or xarray.DataArray.
Examples
Assuming ds is an xr.Dataset and ANGLE.K_PARALLEL is defined:
>>> ds_accessor = YourAccessorClass(ds) >>> ds_accessor.apply_offsets({ANGLE.K_PARALLEL: 0.05, ANGLE.THETA: -0.1}) >>> ds.attrs['k_parallel_offset'] 0.05 >>> ds.attrs['theta_offset'] -0.1
- property is_slit_vertical[source]#
Infers whether the scan is taken on an analyzer with vertical slit.
Caveat emptor: this assumes that the alpha coordinate is not some intermediate value.
- Returns:
True if the alpha value is consistent with a vertical slit analyzer. False otherwise.
- property iter_own_symmetry_points[source]#
An iterator property that yields high-symmetry points and their coordinates.
This property provides a convenient way to iterate over the high-symmetry points associated with the current dataset’s Brillouin zone or band structure, along with their corresponding coordinate dictionaries. It relies on the symmetry_points() method (which is assumed to be defined elsewhere within this class or a related one) to retrieve the mapping of symmetry point names to their coordinates.
- Yields:
tuple[HIGH_SYMMETRY_POINTS, dict[str, float]] –
- The symmetry-point
name together with a dictionary of coordinate values for that point.
Examples
>>> # Assume ds_accessor.symmetry_points() returns: >>> # {HIGH_SYMMETRY_POINTS.GAMMA: {'kx': 0.0, 'ky': 0.0}, >>> # HIGH_SYMMETRY_POINTS.X_POINT: {'kx': 1.0, 'ky': 0.0}} >>> for point_name, coords in ds_accessor.iter_own_symmetry_points: ... print(f"Symmetry Point: {point_name}, Coordinates: {coords}")
- property logical_offsets[source]#
The logical offsets of the sample position.
- Returns:
dict object of long_[x, y, z] + physical_long_[x, y, z]
Todo
- Consering if this is really suitable way?
While this variable used just in MAESTRO.py which I haven’t used, to keep consistensy with other plugins the following change seems to be reasonable.
coords[“long_x”] should be coosrds[“x”] ?
coords[“physical_long_x”] seems to be just x_offset.
- symmetry_points()[source]#
Return the dict object about symmetry point such as G-point in the ARPES data.
The original version was something complicated, but the coding seemed to be in process and the purpose was unclear, so it was streamlined considerably.
- Returns (dict[HIGH_SYMMETRY_POINTS, dict[str, float]]):
Dict object representing the symmetry points in the ARPES data.
- Raises:
RuntimeError – When the label of high symmetry_points in arr.attrs[symmetry_points] is not in HIGH_SYMMETRY_POINTS declared in _typing.py
Examples
symmetry_points = {“G”: {“phi”: 0.405}}
- class arpes.xarray_extensions.accessor.property.ARPESPropertyBase[source]#
Bases:
ARPESInfoProperty[DataType],ARPESOffsetProperty[DataType],ARPESProvenanceProperty[DataType]Base class for ARPES Property.
- property is_kspace[source]#
Infers whether the scan is k-space converted or not.
Because of the way this is defined, it will return true for XPS spectra, which I suppose is true but trivially.
- Returns:
True if the data is k-space converted. False otherwise.
- class arpes.xarray_extensions.accessor.property.ARPESProperty[source]#
Bases:
ARPESPropertyBase[DataType]Class for ARPES property.
- class arpes.xarray_extensions.accessor.base.ARPESDataArrayAccessorBase(xarray_obj)[source]#
Bases:
ARPESAccessorBase[DataArray]Base class for accessors specifically designed for xarray.DataArray objects in PyARPES.
This class extends ARPESAccessorBase and provides methods tailored for single-variable ARPES data, such as inferring background subtraction status and performing advanced selections around specific data points.
- property is_subtracted[source]#
Infers whether a given data is subtracted.
- Returns (bool):
Return True if the data is subtracted.
- select_around(point, radius, *, mode='sum')[source]#
Selects and integrates a region around a one dimensional point.
This method is useful to do a small region integration, especially around point on a path of a k-point of interest. See also the companion method select_around_data.
- Parameters:
point – The point where the selection should be performed.
radius – The radius of the selection in each coordinate. If dimensions are omitted, a standard sized selection will be made as a compromise.
safe – If true, infills radii with default values. Defaults to True.
mode – How the reduction should be performed, one of “sum” or “mean”. Defaults to “sum”
- Returns:
The binned selection around the desired point.
- select_around_data(points, radius=None, *, mode='sum')[source]#
Performs a binned selection around a point or points.
Can be used to perform a selection along one axis as a function of another, integrating a region in the other dimensions.
Example
As an example, suppose we have a dataset with dimensions (‘eV’, ‘kp’, ‘T’,) and we also by fitting determined the Fermi momentum as a function of T, kp_F(‘T’), stored in the dataset kFs. Then we could select momentum integrated EDCs in a small window around the fermi momentum for each temperature by using
>>> edcs = full_data.S.select_around_data(points={'kp': kFs}, radius={'kp': 0.04})
The resulting data will be EDCs for each T, in a region of radius 0.04 inverse angstroms around the Fermi momentum.
- Parameters:
points – The set of points where the selection should be performed.
radius – The radius of the selection in each coordinate. If dimensions are omitted, a standard sized selection will be made as a compromise.
mode – How the reduction should be performed, one of “sum” or “mean”. Defaults to “sum”
- Returns:
The binned selection around the desired point or points.
- class arpes.xarray_extensions.accessor.spectroscopy.ARPESDataArrayAccessor(xarray_obj)[source]#
Bases:
ARPESDataArrayAccessorBaseSpectrum related accessor for xr.DataArray.
- correct_coords(correction_types)[source]#
Correct the coordinates of the DataArray in place.
- Parameters:
correction_types (CoordsOffset | Sequence[CoordsOffset, ...]) – The types of corrections to apply.
- corrected_coords(correction_types)[source]#
Apply the specified coordinate corrections to the DataArray.
- Parameters:
correction_types (CoordsOffset | Sequence[CoordsOffset]) – The types of corrections to apply.
- Returns:
The corrected DataArray.
- Return type:
xr.DataArray
- fermi_edge_reference_plot(pattern='{}.png', out='', **kwargs)[source]#
Provides a reference plot for a Fermi edge reference.
This function generates a reference plot for a Fermi edge, which can be useful for analyzing energy spectra. It calls the fermi_edge_reference function and passes any additional keyword arguments to it for plotting customization. The output file name can be specified using the out argument, with a default name pattern.
- Parameters:
pattern (str) – A string pattern for the output file name. The pattern can include placeholders that will be replaced by the label or other variables. Default is “{}.png”.
out (str | Path) – The path for saving the output figure. If set to None or False, no figure will be saved. If a boolean True is passed, it will use the pattern to generate the filename.
kwargs – Additional arguments passed to the fermi_edge_reference function for customizing the plot.
- Returns:
The path to the saved figure (if out is provided), or the Axes object of the plot.Provides a reference plot for a Fermi edge reference.
- Return type:
Path | Axes
- fs_plot(pattern='{}.png', **kwargs)[source]#
Provides a reference plot of the approximate Fermi surface.
- plot(*args, **kwargs)[source]#
Utility delegate to xr.DataArray.plot which rasterizes`.
- Parameters:
rasterized (bool) – if True, rasterized (Not vector) drawing
args – Pass to xr.DataArray.plot
kwargs – Pass to xr.DataArray.plot
- reference_plot(**kwargs)[source]#
Generates a reference plot for this piece of data according to its spectrum type.
- Parameters:
kwargs – pass to referenced_scans_for_**
- Raises:
NotImplementedError – If there is no standard approach for plotting this data.
- Returns:
The axes which were used for plotting.
- class arpes.xarray_extensions.accessor.spectroscopy.ARPESDatasetAccessor(xarray_obj)[source]#
Bases:
ARPESAccessorBase[Dataset]Spectrum related accessor for xr.Dataset.
- __getattr__(item)[source]#
Forward attribute access to the spectrum, if necessary.
- Parameters:
item – Attribute name
- Returns:
The attribute after lookup on the default spectrum
- fat_sel(widths=None, method='mean', **kwargs)[source]#
Performs a ‘fat’ selection, integrating data over small regions specified by widths.
This method allows for integrating a selection over a small coordinate region (defined by widths or keyword arguments), effectively reducing noise by averaging or summing over nearby slices. The resulting dataset will be normalized by the number of slices integrated over if method=”mean”.
- Parameters:
widths (dict[Hashable, float] | None, optional) – A dictionary specifying the width of the integration window for each dimension. Keys are dimension names (Hashable), and values are float widths. Overrides any widths specified in kwargs. Defaults to None, in which case selections.fat_sel might use default widths.
method (ReduceMethod, optional) – The reduction method to apply within the selection window. Can be “mean” (default) or “sum”.
**kwargs (float) – Keyword arguments that can define specific selection points (e.g., eV=1.5) or widths (e.g., eV_width=0.1). Note: Using *_width in kwargs for specifying widths is deprecated. Prefer the widths dictionary argument.
- Returns:
The xarray.DataArray or xarray.Dataset after the ‘fat’ selection and reduction have been applied. The dimensions for which a width was specified will effectively be reduced or removed.
- Return type:
XrTypes
Note
The widths argument is the preferred way to specify integration widths. Using *_width through kwargs is deprecated and may be removed in future versions.
- make_spectrum_reference_plots(prefix='', **kwargs)[source]#
Creates photocurrent normalized + unnormalized figures.
Creates:
The reference plots for the photocurrent normalized spectrum
The normalized total cycle intensity over scan DoF, i.e. cycle vs scan DOF integrated over E, phi
For delay scans
Fermi location as a function of scan DoF, integrated over phi
Subtraction scans
- Parameters:
prefix – A prefix inserted into filenames to make them unique.
kwargs – Passed to plotting routines to provide user control over plotting behavior
- mean_other(dim_or_dims, *, keep_attrs=False)[source]#
Calculates the mean over all dimensions except those specified.
This is a convenience method for xarray.Dataset.mean() or xarray.DataArray.mean() that inverts the selection of dimensions. Instead of specifying dimensions to average along, you specify dimensions to keep.
- Parameters:
dim_or_dims (list[str] | str) – A list of dimension names to keep, or a single dimension name string. The mean operation will be performed over all other dimensions not in this list/string.
keep_attrs (bool, optional) – If True, attributes (.attrs) will be preserved on the returned object. Defaults to False.
- Returns:
A new xarray object (Dataset or DataArray) with the data averaged along the specified “other” dimensions. Its dimensions will only include those listed in dim_or_dims.
- Return type:
DataType
- Raises:
AssertionError – If dim_or_dims is not a list (note: the type hint allows str but the assertion explicitly checks for list). This discrepancy should be resolved for consistency. For now, the docstring reflects the assertion.
Examples
>>> data = xr.DataArray(np.arange(12).reshape(2, 2, 3), dims=['x', 'y', 'z']) >>> accessor = ARPESAccessorBase(data) >>> accessor.mean_other(dim_or_dims=['x']) # Averages over 'y' and 'z' <xarray.DataArray (x: 2)> array([2.5, 8.5]) Coordinates: * x (x) int64 0 1 >>> accessor.mean_other(dim_or_dims=['y', 'z']) # Averages over 'x' <xarray.DataArray (y: 2, z: 3)> array([[2.5, 3.5, 4.5], [5.5, 6.5, 7.5]]) Coordinates: * y (y) int64 0 1 * z (z) int64 1 2 3
- reference_plot(**kwargs)[source]#
Creates reference plots for a dataset.
A bit of a misnomer because this actually makes many plots. For full datasets, the relevant components are:
Temperature as function of scan DOF
Photocurrent as a function of scan DOF
Photocurrent normalized + unnormalized figures, in particular
The reference plots for the photocurrent normalized spectrum
- The normalized total cycle intensity over scan DoF, i.e. cycle vs scan DOF integrated
over E, phi
For delay scans
Fermi location as a function of scan DoF, integrated over phi
Subtraction scans
For spatial scans
energy/angle integrated spatial maps with subsequent measurements indicated
energy/angle integrated FS spatial maps with subsequent measurements indicated
- Parameters:
kwargs – Passed to plotting routines to provide user control
- property spectra[source]#
Collects the variables which are likely spectra.
- Returns:
The subset of the data_vars which have dimensions indicating that they are spectra.
- property spectrum[source]#
Isolates a single spectrum from a dataset.
This is a convenience method which is typically used in startup for tools and analysis routines which need to operate on a single piece of data. Historically, the handling of Dataset and Dataarray was a mess in previous pyarpes. Most of the current pyarpes methods/function are sufficient to treat DataArray as the main object. (The few exceptions are S.modelfit, whose return value is a Dataset, which is reasonable.) For backward compatibility, the return of load_data is still a Dataset, so in many cases, using this property for a DataArray will provide a more robust analysing environment.
In practice, we filter data variables by whether they contain “spectrum” in the name before selecting the one with the largest pixel volume. This is a heuristic which tries to guarantee we select ARPES data above XPS data, if they were collected together.
- Returns:
A spectrum found in the dataset, if one can be isolated.
In the case that several candidates are found, a single spectrum is selected among the candidates.
Attributes from the parent dataset are assigned onto the selected array as a convenience.
Todo: Need test
- sum_other(dim_or_dims, *, keep_attrs=False)[source]#
Calculates the sum over all dimensions except those specified.
This is a convenience method for xarray.Dataset.sum() or xarray.DataArray.sum() that inverts the selection of dimensions. Instead of specifying dimensions to sum along, you specify dimensions to keep.
- Parameters:
dim_or_dims (list[str]) – A list of dimension names to keep. The sum operation will be performed over all other dimensions not in this list.
keep_attrs (bool, optional) – If True, attributes (.attrs) will be preserved on the returned object. Defaults to False.
- Returns:
A new xarray object (Dataset or DataArray) with the data summed along the specified “other” dimensions. Its dimensions will only include those listed in dim_or_dims.
- Return type:
DataType
- Raises:
AssertionError – If dim_or_dims is not a list.
Examples
>>> data = xr.DataArray(np.ones((2, 3, 4)), dims=['x', 'y', 'z']) >>> accessor = ARPESAccessorBase(data) >>> accessor.sum_other(dim_or_dims=['x']) # Sums over 'y' and 'z' <xarray.DataArray (x: 2)> array([12., 12.]) Dimensions without coordinates: y, z Coordinates: * x (x) int64 0 1 >>> accessor.sum_other(dim_or_dims=['y', 'z']) # Sums over 'x' <xarray.DataArray (y: 3, z: 4)> array([[2., 2., 2., 2.], [2., 2., 2., 2.], [2., 2., 2., 2.]]) Dimensions without coordinates: x Coordinates: * y (y) int64 0 1 2 * z (z) int64 0 1 2 3
The .G accessor#
Available as methods via .G accessor.
- class arpes.xarray_extensions.accessor.base.GenericAccessorBase[source]#
Bases:
Generic[DataType]Class for general-purpose utility methods for xarray.Dataset and xarray.DataArray objects.
This class offers functionalities such as coordinate manipulation, applying functions to data regions, and iterating over coordinates, which can be broadly useful across different types of scientific data.
- coordinatize(as_coordinate_name=None)[source]#
Copies data into a coordinate’s data, with an optional renaming.
If you think of an array as a function c => f(c) from coordinates to values at those coordinates, this function replaces f by the identity to give c => c
Remarkably, coordinatize is a word.
For the most part, this is only useful when converting coordinate values into k-space “forward”.
- Parameters:
as_coordinate_name – A new coordinate name for the only dimension. Defaults to None.
- Returns:
An array which consists of the mapping c => c.
Todo
Test
- enumerate_iter_coords(dim_names=())[source]#
Return an iterator for pixel and physical coordinates.
- Aargs:
dir_names (Sequence[Hashable]): Dimension names for iterateion.
- Yields:
Iteratoring the data like – ((0, 0), {‘phi’: -0.2178031280148764, ‘eV’: 9.0}) which shows the relationship between pixel position and physical (like “eV” and “phi”).
- iter_coords(dim_names=(), *, reverse=False)[source]#
Iterator for coordinates along the axis.
- Parameters:
dim_names (Sequence[Hashable]) – Dimensions for iteration.
reverse – return the “reversivle” iterator.
- Yields:
Iterator of the physical position like (“eV” and “phi”) {‘phi’: -0.2178031280148764, ‘eV’: 9.002}
- class arpes.xarray_extensions.accessor.general.GenericDatasetAccessor(xarray_obj)[source]#
Bases:
GenericAccessorBase[Dataset]A collection of generic accessors for xarray.Dataset objects.
This accessor provides utility methods for filtering data variables, and transforming meshgrid coordinates within an xarray Dataset.
- Usage:
Register this accessor using @xr.register_dataset_accessor(“G”). Then, you can access its methods via the .G attribute on any xarray.Dataset: ds.G.filter_vars(…) or ds.G.shift_meshgrid(…).
- apply_over(fn, *, copy=True, selections=None, **selections_kwargs)[source]#
Applies a function to a data region and updates the dataset with the result.
- Parameters:
fn (Callable) – The function to apply.
copy (bool, optional) – If True, operates on a deep copy of the data. If False, modifies the data in-place. Defaults to True.
selections (Incomplete) – Keyword arguments specifying the region of the data to select.
**selections_kwargs – Selection keys and values as keyword arguments.
- Returns:
The dataset after the function has been applied.
- Return type:
XrTypes
Todo
Add tests.
- filter_coord(coordinate_name, sieve)[source]#
Filters a dataset along a coordinate.
Sieve should be a function which accepts a coordinate value and the slice of the data along that dimension.
Internally, the predicate function sieve is applied to the coordinate and slice to generate a mask. The mask is used to select from the data after iteration.
An improvement here would support filtering over several coordinates.
- Parameters:
coordinate_name – The coordinate which should be filtered.
sieve – A predicate to be applied to the coordinate and data at that coordinate.
- Returns:
A subset of the data composed of the slices which make the sieve predicate True.
Todo
Test
- filter_vars(f)[source]#
Filters data variables based on the specified condition and returns a new dataset.
This method iterates through the data variables of the Dataset and applies a user-defined filtering function. Only variables for which the function returns True will be included in the new Dataset. The original Dataset remains unchanged.
- Parameters:
f (Callable[[Hashable, xr.DataArray], bool]) – A predicate function that takes two arguments: the name (hashable key) of a data variable and its corresponding xr.DataArray. It must return True to include the variable in the filtered dataset, or False to exclude it.
- Returns:
- A new xarray.Dataset containing only the data variables
that satisfied the filtering condition. The attributes of the original dataset are preserved.
- Return type:
xr.Dataset
Examples
>>> import xarray as xr >>> ds = xr.Dataset( ... {"temp": (("x", "y"), [[1, 2], [3, 4]]), ... "pressure": (("x", "y"), [[5, 6], [7, 8]])} ... ) >>> # Filter variables whose names start with 't' >>> filtered_ds = ds.G.filter_vars(lambda k, v: k.startswith("t")) >>> print(filtered_ds) <xarray.Dataset> Dimensions: (x: 2, y: 2) Data variables: temp (x, y) int64 1 2 3 4 >>> # Filter variables with more than 2 elements >>> filtered_ds = ds.G.filter_vars(lambda k, v: v.size > 2) >>> print(filtered_ds) <xarray.Dataset> Dimensions: (x: 2, y: 2) Data variables: temp (x, y) int64 1 2 3 4 pressure (x, y) int64 5 6 7 8
See also
xarray.Dataset.drop_vars(): To explicitly remove variables by name.
- round_coordinates(coords_to_round, *, as_indices=False)[source]#
Rounds specified coordinates to their nearest existing values in the dataset.
This method takes a dictionary of target coordinate values and finds the closest actual coordinate values present in the xarray object along those dimensions using method=”nearest”. It can optionally return these rounded coordinates as their integer indices.
- Parameters:
coords_to_round (dict[str, list[float] | NDArray[np.floating]]) – A dictionary where keys are dimension names (strings) and values are the target coordinate points (floats or arrays of floats) to be rounded to the nearest existing coordinate in the dataset.
as_indices (bool, optional) – If True, the rounded coordinates are returned as their integer indices within the respective dimensions. If False (default), the actual float coordinate values are returned.
- Returns:
A dictionary mapping dimension names to their rounded coordinate values (float) or their corresponding integer indices (int), depending on the as_indices parameter. Only dimensions specified in coords_to_round will be included in the output.
- Return type:
dict[str, float | int]
- Raises:
AssertionError – If the internal _obj is not an xarray.DataArray or xarray.Dataset.
Examples
>>> data = xr.DataArray(np.arange(10), dims=['x'], coords={'x': np.linspace(0, 9, 10)}) >>> accessor = GenericAccessorBase(data) >>> accessor.round_coordinates({'x': [3.1]}) {'x': 3.0} >>> accessor.round_coordinates({'x': [3.9]}, as_indices=True) {'x': 4} >>> data_md = xr.DataArray(np.random.rand(5,5), dims=['a', 'b'], ... coords={'a': np.arange(5), 'b': np.arange(5,10)}) >>> accessor_md = GenericAccessorBase(data_md) >>> accessor_md.round_coordinates({'a': [2.2], 'b': [6.8]}) {'a': 2.0, 'b': 7.0}
- scale_meshgrid(dims, scale)[source]#
Scales the meshgrid coordinates for specified dimensions.
This method applies a multiplicative scaling to the coordinates of the specified dimensions. Similar to shift_meshgrid, this is designed for datasets where coordinates represent a meshgrid.
- Parameters:
dims (tuple[str, ...]) – A tuple of strings specifying the names of the dimensions whose coordinates will be scaled.
scale (float | NDArray[np.floating]) – The amount(s) by which to scale the coordinates. A float applies the same scale factor to every dimension. A one-dimensional array applies one factor per dimension, and a two-dimensional square array is treated as a linear transformation matrix.
- Returns:
- A new xarray.Dataset with the coordinates of the
specified dimensions scaled by the given amount(s). The original Dataset remains unchanged.
- Return type:
xr.Dataset
- Raises:
AssertionError – If an invalid scale amount is provided (e.g., an array with an incorrect shape).
- shift_meshgrid(dims, shift)[source]#
Shifts the meshgrid coordinates for specified dimensions.
This method applies an additive shift to the coordinates of the specified dimensions. It’s particularly useful when your coordinates represent a meshgrid (e.g., from np.meshgrid or xr.Dataset.meshgrid). The transformation is applied to the underlying coordinate arrays, resulting in a new Dataset with shifted coordinates.
- Parameters:
dims (tuple[str, ...]) – A tuple of strings specifying the names of the dimensions whose coordinates will be shifted. These dimensions should typically form a meshgrid.
shift (NDArray[np.floating] | float) – The amount(s) by which to shift the coordinates. A float applies the same scalar shift to every dimension. A one-dimensional array applies one shift value per dimension in dims.
- Returns:
- A new xarray.Dataset with the coordinates of the
specified dimensions shifted by the given amount(s). The original Dataset remains unchanged.
- Return type:
xr.Dataset
- Raises:
AssertionError – If an invalid shift amount is provided (e.g., an array with an incorrect shape).
- transform_meshgrid(dims, transform)[source]#
Transforms the given meshgrid coordinates by an arbitrary function or matrix.
This is the core method for applying complex transformations to meshgrid coordinates. It takes a collection of dimension names whose coordinates form a meshgrid, stacks their values into a single NumPy array, applies a user-defined transformation (either a function or a linear transformation matrix), and then updates the original coordinates in a new Dataset.
The transformation operates on a reshaped view of the coordinate data. Specifically, for N dimensions, the coordinate arrays (e.g., X, Y, Z) are stacked along a new last axis. If the original coordinates are (M1, M2, …, MN) for dims d1, d2, …, dN, then the stacked array will have shape (M1, M2, …, MN, N). Each “row” in the last axis represents a coordinate vector [coord_d1, coord_d2, …, coord_dN] at a specific grid point.
- Parameters:
dims (Collection[str]) – A list or tuple of strings representing the names of the dimensions whose coordinates should be transformed. These dimensions are assumed to form a meshgrid. The order of dimensions in this collection matters, as it defines the order of columns in the stacked coordinate array passed to transform.
transform (NDArray[np.floating] | Callable[[NDArray[np.floating]], NDArray[np.floating]]) – The transformation to apply to the stacked meshgrid coordinates. This can be either a two-dimensional NumPy array representing a linear transformation matrix with shape (len(dims), len(dims)), or a callable that accepts and returns an array with shape (…, len(dims)) for arbitrary non-linear transformations.
- Returns:
- A new xarray.Dataset object with the specified
meshgrid coordinates updated after applying the transformation. The original Dataset is not modified.
- Return type:
xr.Dataset
- Raises:
AssertionError – If the input transform matrix has an incorrect shape.
ValueError – If the transform callable does not return an array of the expected shape.
- class arpes.xarray_extensions.accessor.general.GenericDataArrayAccessor(xarray_obj)[source]#
Bases:
GenericAccessorBase[DataArray]A collection of generic accessors for xarray.DataArray objects.
This accessor provides utility methods for common operations on xarray.DataArray, including finding maximum value coordinates, reshaping, creating meshgrids, handling outliers, generating animations, and applying custom transformations.
- Usage:
Register this accessor using @xr.register_dataarray_accessor(“G”). Then, you can access its methods via the .G attribute on any xarray.DataArray: da.G.argmax_coords() or da.G.ravel().
- as_movie(time_dim='delay', *, out=None, **kwargs)[source]#
Create an animation or save images showing the DataArray’s evolution over time.
This method creates a time-based visualization of an xarray.DataArray, either as an animation or as a sequence of images saved to disk. The time_dim parameter specifies the dimension used for the temporal progression.
- Parameters:
time_dim (str, optional) – The name of the dimension representing time or progression in the DataArray. Defaults to “delay”.
out (str , optional) – Determines the output format. If a string is provided, it is used as the base name for the output file or directory. otherwise, the animation is returned without saving.
kwargs (optional) – Additional keyword arguments passed to the plot_movie function. These can customize the appearance of the generated images or animation.
- Returns:
If out is specified (as a string or True), returns a Path to the saved file.
If out is False or an empty string, returns a matplotlib.animation.FuncAnimation object.
- Return type:
Path | animation.FuncAnimation
- Raises:
AssertionError – If the underlying object is not an xarray.DataArray.
AssertionError – If out is not a valid string when required.
Example:
import xarray as xr # Create a sample DataArray with a time dimension data = xr.DataArray( [[[i + j for j in range(10)] for i in range(10)] for _ in range(5)], dims=("delay", "x", "y"), coords={"delay": range(5), "x": range(10), "y": range(10)}, ) # Generate an animation animation = data.G.as_movie(time_dim="delay")
- clean_outliers(clip=0.5)[source]#
Clip outliers in the DataArray by limiting values to a specified percentile range.
This method modifies the values of an xarray.DataArray to ensure that they fall within a specified range defined by percentiles. Any value below the lower percentile is set to the lower limit, and any value above the upper percentile is set to the upper limit.
- Parameters:
clip (float, optional) –
The percentile range to use for clipping. The lower and upper bounds are determined by the clip value and its complement:
Lower bound: clip percentile.
Upper bound: (100 - clip) percentile.
- For example, if clip=0.5, the lower 0.5% and upper 99.5% of the data will be
clipped. Default is 0.5.
Returns: xr.DataArray: A new DataArray with outliers clipped to the specified range.
- Raises:
AssertionError – If the underlying object is not an xarray.DataArray.
Todo
Add unit tests to ensure the method behaves as expected.
- map(fn, **kwargs)[source]#
Applies the specified function to the values of an xarray and returns a new DataArray.
- Parameters:
fn (Callable) – The function to apply to the xarray values.
kwargs – Additional arguments to pass to the function.
- Returns:
A new DataArray with the function applied to the values.
- Return type:
xr.DataArray
- map_axes(axes, fn, dtype=None)[source]#
Apply a function along specified axes of the DataArray, creating a new DataArray.
This method iterates over the coordinates of the specified axes, applies the provided function to each coordinate, and assigns the result to the corresponding position in the output DataArray. Optionally, the data type of the output array can be specified.
- Parameters:
axes (list[str] | str) – The axis or axes along which to iterate and apply the function.
fn (Callable[[DataType, dict[str, float]], DataType]) – Function that takes the selected data and its coordinates as input and returns the transformed data.
dtype (DTypeLike, optional) – The desired data type for the output DataArray. If not specified, the type is inferred from the function’s output.
- Returns:
A new DataArray with the function applied along the specified axes.
- Return type:
xr.DataArray
- Raises:
TypeError – If the input arguments or operations result in a type mismatch.
Example:
Todo
Add tests to validate the behavior with complex axes configurations.
Optimize performance for high-dimensional DataArrays.
- meshgrid(*, as_dataset=False)[source]#
Creates a meshgrid from the DataArray’s dimensions and includes its values.
optionally returning it as an xarray.Dataset.
This method is useful for reconstructing meshgrid-like coordinate arrays from a DataArray’s dimensions, similar to numpy.meshgrid. It also includes the original DataArray’s values, preserving their multi-dimensional shape.
- Parameters:
as_dataset (bool, optional) – If True, the result is returned as an xarray.Dataset where coordinate arrays and the data array are represented as DataArray objects with explicit dimensions. If False (default), the result is a dictionary of NumPy arrays.
- Returns:
If as_dataset is False: A dictionary where keys are dimension names and “data”, and values are multi-dimensional NumPy arrays representing the meshgrid coordinates and the original data values.
If as_dataset is True: An xarray.Dataset containing DataArray objects for each meshgrid coordinate and the original data, with dimensions explicitly named (e.g., “x”, “y”, “z” for the meshgrid, and the original dims for “data”).
- Return type:
dict[Hashable, NDArray[np.floating]] | xr.Dataset
Examples
>>> import xarray as xr >>> import numpy as np >>> data = xr.DataArray( ... [[1, 2], [3, 4]], ... coords={"x": [10, 20], "y": [100, 200]}, ... dims=("x", "y") ... ) >>> # As a dictionary of NumPy arrays >>> meshed_dict = data.G.meshgrid() >>> print("x_meshgrid:\\n", meshed_dict["x"]) x_meshgrid: [[10 20] [10 20]] >>> print("y_meshgrid:\\n", meshed_dict["y"]) y_meshgrid: [[100 100] [200 200]] >>> print("data:\\n", meshed_dict["data"]) data: [[1 2] [3 4]]
>>> # As an xarray.Dataset >>> meshed_ds = data.G.meshgrid(as_dataset=True) >>> print(meshed_ds) <xarray.Dataset> Dimensions: (x: 2, y: 2) Coordinates: x_coord (x, y) int64 10 20 10 20 y_coord (x, y) int64 100 100 200 200 Data variables: data (x, y) int64 1 2 3 4 >>> print(meshed_ds["x_coord"]) # Note the internal renaming <xarray.DataArray 'x_coord' (x: 2, y: 2)> array([[10, 20], [10, 20]]) Coordinates: * x (x) int64 10 20 * y (y) int64 100 200
See also
numpy.meshgrid: The core NumPy function for creating coordinate grids. ~.GenericDataArrayAccessor.ravel: For flattening the data and coordinates.
- ravel()[source]#
Converts to a flat representation where the coordinate values are also present.
Extremely valuable for plotting a dataset with coordinates, X, Y and values Z(X,Y) on a scatter plot in 3D.
By default the data is listed under the key ‘data’.
- Returns:
A dictionary mapping between coordinate names and their coordinate arrays. Additionally, there is a key “data” which maps to the .values attribute of the array.
- shift_by(other, shift_axis='', by_axis='', *, extend_coords=False, shift_coords=False)[source]#
Shifts the data along the specified axis.
Currently, only supports shifting by a one-dimensional array.
- Parameters:
other (xr.DataArray | NDArray) – Data to shift by. Only supports one-dimensional array.
shift_axis (str) – The axis to shift along, which is 1D.
by_axis (str) – The dimension name of other. Ignored when other is an xr.DataArray.
extend_coords (bool) – If True, the coords expands. Default is False.
shift_coords (bool) – Whether to shift the coordinates as well. The arg will be removed, because it is not unique way to shift from the “other”. Currently it uses mean value of “other”.
- Returns:
The shifted xr.DataArray.
- Return type:
xr.DataArray
Todo
Add tests.Data shift along the axis.
Note
zero_nans is removed. Use DataArray.fillna(0), if needed.
- shift_coords_by(shift_values)[source]#
Shifts the coordinates by the specified values.
- Parameters:
shift_values (dict[str, float]) – A dictionary where keys are coordinate names and values
shift. (are the amounts to)
- Returns:
The DataArray with shifted coordinates.
- Return type:
xr.DataArray
- transform(axes, transform_fn, dtype=None, *args, **kwargs)[source]#
Applies a vectorized operation across a subset of array axes.
Transform has similar semantics to matrix multiplication, the dimensions of the output can grow or shrink depending on whether the transformation is size preserving, grows the data, shrinks the data, or leaves in place.
Examples
As an example, let us suppose we have a function which takes the mean and variance of the data:
[dimension], coordinate_value -> [{‘mean’, ‘variance’}]
And a dataset with dimensions [X, Y]. Then calling transform maps to a dataset with the same dimension X but where Y has been replaced by the length 2 label {‘mean’, ‘variance’}. The full dimensions in this case are [‘X’, {‘mean’, ‘variance’}].
>>> data.G.transform('X', f).dims ["X", "mean", "variance"]
Please note that the transformed axes always remain in the data because they are iterated over and cannot therefore be modified.
The transform function transform_fn must accept the coordinate of the marginal at the currently iterated point.
- Parameters:
axes – Dimension/axis or set of dimensions to iterate over
transform_fn – Transformation function that takes a DataArray into a new DataArray
dtype – An optional type hint for the transformed data. Defaults to None.
args – args to pass into transform_fn
kwargs – kwargs to pass into transform_fn
- Raises:
TypeError – When the underlying object is an xr.Dataset instead of an xr.DataArray. This is due to a constraint related to type inference with a single passed dtype.
- Returns:
The data consisting of applying transform_fn across the specified axes.
Todo
Test
- with_values(new_values, *, keep_attrs=True)[source]#
Copy with new array values.
Easy way of creating a DataArray that has the same shape as the calling object but data populated from the array new_values.
Notes: This method is applicable only for xr.DataArray. (Not xr.Dataset)
- Parameters:
new_values – The new values which should be used for the data.
keep_attrs (bool) – If True, attributes are also copied.
- Returns:
A copy of the data with new values but identical dimensions, coordinates, and attrs.
ToDo: Test
The .F accessor#
Available as methods via .F accessor.
- class arpes.xarray_extensions.accessor.fit.ARPESDatasetFitToolAccessor(xarray_obj)[source]#
Bases:
objectProvides ARPES spectral fitting inspection and query tools for xarray.Dataset.
A custom accessor for xarray.Dataset objects, providing tools for inspecting and querying results from spectral fitting operations on ARPES data.
This accessor is registered under the name “F”, allowing users to access its methods via xr.Dataset.F.<method_name>.
- _obj#
The xarray Dataset instance to which this accessor is attached.
- Type:
xr.Dataset
- fit_dimensions(spectral_name='spectrum')[source]#
Returns the dimensions which were broadcasted across, as opposed to fit across.
This is a sibling property to broadcast_dimensions.
- Returns:
The list of the dimensions which were not used in any individual fit. For example, a broadcast of MDCs across energy on a dataset with dimensions [“eV”, “kp”] would produce [“eV”].
- save_fit(path, **kwargs)[source]#
Wrapper of xarray_lmfit.save_fit.
Save the result dataset to a netCDF file, which can be loaded by using standard xarray.load_dataset()
- Parameters:
path – Path to save the fit results
**kwargs – Passed to xarray.Dataset.to_netcdf
- show(**kwargs)[source]#
Displays an interactive fit inspection tool for visualizing spectral fitting results.
This method leverages an external fit_inspection function to generate a visual interface that allows users to examine the quality of fits, individual components, and residuals across different dimensions of the dataset.
- Parameters:
**kwargs (Unpack[ProfileViewParam]) – Arbitrary keyword arguments that are passed directly to the fit_inspection function. These typically control the appearance and behavior of the profile view, such as plotting parameters or selection criteria.
- Returns:
- An object representing the interactive layout of the
fit inspection tool. The exact type and behavior depend on the implementation of fit_inspection.
- Return type:
AdjointLayout
Note
The fit_inspection function is expected to be defined elsewhere and capable of interpreting the structure of the fitted ARPES data within the _obj Dataset.
- class arpes.xarray_extensions.accessor.fit.ARPESFitToolsAccessor(xarray_obj)[source]#
Bases:
objectUtilities related to examining curve fits.
modelfit_results or [var]_modelfit_results (When Dataset.S.modelfit is applied.)
- property band_names[source]#
Collects the names of the bands from a multiband fit.
Heuristically, a band is defined as a dispersive peak so we look for prefixes corresponding to parameter names which contain “center”.
- Returns:
The collected prefix names for the bands.
For instance, if the param name “a_center”, the return value would contain “a_”.
- mean_square_error()[source]#
Calculates the mean square error of the fit across fit axes.
Producing a scalar metric of the error for all model result instances in the collection.
- order_stacked_fits(*, ascending=False)[source]#
Produces an ordered collection of lmfit.ModelResult instances.
For multidimensional broadcasts, the broadcasted dimensions will be stacked for ordering to produce a 1D array of the results.
- Parameters:
ascending – Whether the results should be ordered according to ascending mean squared error (best fits first) or descending error (worst fits first).
- Returns:
An xr.DataArray instance with stacked axes whose values are the ordered models.
Todo
Test
- p(param_name)[source]#
Collects the value of a parameter from curve fitting.
Across an array of fits, walks parameters to collect the value assigned by the fitting routine.
- Parameters:
param_name – The parameter name we are trying to collect
- Returns:
An xr.DataArray containing the value found by the fitting routine.
The output array is infilled with np.nan if the fit did not converge/ the fit result is None.
- Memo:
Work after xarray-lmfit migration.
- param_as_dataset(param_name)[source]#
Maps from lmfit.ModelResult to a Dict parameter summary.
- Parameters:
param_name – The parameter which should be summarized.
- Returns:
“value” and “error” which are the fit value and standard error on the parameter requested.
- Return type:
A dataset consisting of two arrays
- property parameter_names[source]#
Collects the parameter names for a multidimensional fit.
Assumes that the model used is the same for all
lmfit.ModelResults so that we can merely extract the parameter names from a single non-null result.- Returns:
A set of all the parameter names used in a curve fit.
Todo
Test
- Memo:
Work after xarray-lmfit migration.
- plot_param(param_name, **kwargs)[source]#
Creates a scatter plot of a parameter from a multidimensional curve fit.
- Parameters:
param_name – The name of the parameter which should be plotted
kwargs – Passed to plotting routines to provide user control figsize=, color=, markersize=,
- s(param_name)[source]#
Collects the standard deviation of a parameter from fitting.
Across an array of fits, walks parameters to collect the standard error assigned by the fitting routine.
- Parameters:
param_name – The parameter name we are trying to collect
- Returns:
An xr.DataArray containing the floating point value for the fits.
The output array is infilled with np.nan if the fit did not converge/ the fit result is None.
- Memo:
Work after xarray-lmfit migration.
Momentum Conversion#
Exact Forward Transforms#
|
Forward converts all the individual coordinates of the data array. |
Utilities#
Provides a Pythonic interface to fast gridded linear interpolation. |
|
|
Converts from the full set of standard PyARPES angles to momentum. |
Conversion Implementations#
You do not need to call these directly, but they are good references for anyone looking to implement a different kind of coordinate transform.
Infrastructure code to support a new coordinate conversion routine. |
|
A momentum converter for single ARPES (kp) cuts. |
|
Implements volumetric momentum conversion for kx-ky scans. |
|
Implements single angle photon energy scans. |
General Analysis#
Axis Methods#
|
Rebins the data onto a different (smaller) shape. |
|
Symmetrizes data across an axis. |
Clips the data so that only regions where there is substantial weight are included. |
|
|
Normalizes the intensity. |
|
Sorts slices of data along axis_name so that they lie in order. |
Experimental Resolution Modeling#
Gives the quadrature sum estimate of the resolution of an ARPES spectrum. |
|
Calculates the thermal broadening from the temperature on the data. |
|
Estimates the energy resolution of the analyzer. |
Self-Energy#
|
Converts MDC fit results into the self energy. |
Fits for the self energy of a dataset containing a single band. |
|
Estimates the bare band from a fitted dispersion. |
|
Calculates the quasiparticle mean free path in meters (meters!). |
Derivatives#
|
Like curvature, performs a second derivative. |
|
Provides "curvature" analysis for band locations. |
|
Implements the minimum gradient approach to defining the band in a diffuse spectrum. |
Smoothing and Filtering#
|
Coordinate aware scipy.ndimage.filters.gaussian_filter. |
|
Coordinate aware scipy.ndimage.uniform_filter. |
Implements a Savitzky Golay filter with given window size. |
|
|
Apply Savitzky-Golay filter to an xarray.DataArray along multiple dimensions. |
Deconvolution#
|
Deconvolves data by a given point spread function (PSF). |
|
Deconvolves data by a given point spread function using the Richardson-Lucy (RL) method. |
|
Produces a 1-dimensional gaussian point spread function for use in deconvolve_rl. |
|
Produces an n-dimensional gaussian point spread function for use in deconvolve_rl. |
Masks#
|
Applies a logical mask, i.e. one given in terms of polygons, to a specific piece of data. |
|
Performs broadcasted masking along a given dimension. |
|
Converts a mask definition in terms of the underlying polygon to a True/False mask array. |
Converts a polygon into a mask definition. |
Fermi Surface Pockets#
|
Produces radial slices along a Fermi surface through a pocket. |
|
Collects EDCs around a pocket. |
Produces EDCs distributed radially along a vector from the pocket center. |
|
|
Estimates pocket center, anisotropy, principal vectors, and extent. |
Background Removal#
Shirley Backgrounds#
Calculates a shirley background iteratively over the full energy range energy_range. |
|
Calculates and removes a Shirley background from a spectrum. |
Convex Hull Backgrounds#
Calculates background using the convex hull of the data (intensity as a Z axis). |
|
Removes a background according to calculate_background_hull. |
Incoherent Backgrounds#
Removes counts above the Fermi level. |
|
|
Shifts the coordinates by the specified values. |
Array Alignment#
Subpixel Correlation Based Alignment#
|
Returns the unitful offset of b in a for ndarrays. |
Machine Learning#
ML Based Decompositions#
Change the basis of multidimensional data according to sklearn decomposition classes. |
|
|
Change the basis of multidimensional data according to sklearn decomposition classes. |
|
Change the basis of multidimensional data according to sklearn decomposition classes. |
Change the basis of multidimensional data according to sklearn decomposition classes. |
|
|
Change the basis of multidimensional data according to sklearn decomposition classes. |
Deep Learning and PyTorch#
Utilities for interpretation of results akin to those in fast.ai.
Provides utilities to interpret predictions of a model. |
|
Provides tools to introspect model performance on a single item. |
IO tools.
Reads data from a relatively portable binary format. |
|
|
Converts data to a relatively portable binary format. |
Transform pipelines.
Represents a reversible identity transform. |
|
A reversible anonymous function, so long as the caller supplies an inverse. |
|
|
Like torchvision.transforms.Compose but it operates on data & target in each transform. |
Data Generation#
Here are tools for simulating ARPES from theoretical models, including finite statistics, resolution modeling, and detector effects.
|
Samples events from a probability distribution. |
|
Converts a point cloud (list of xy pairs) to an array representation. |
|
Implements the Marginal Fermi Liquid spectral function, more or less. |
Implements the "phase coherence" model for the BSSCO spectral function. |
|
Detector effects are callables that map a spectrum into a new transformed one. |
|
|
Implements power law detector nonlinearities. |
Data Loading Plugins#
Implements data loading for the Lanzara group "Main Chamber". |
|
Implements data loading for the Lanzara group Spin-ToF. |
|
Implements data loading for ANTARES at SOLEIL. |
|
|
Data loading for the nano-ARPES beamline "Spectromicroscopy Elettra". |
Loads data from exported .nc format saved by xarray. |
|
Sequentially tries different loading plugins. |
|
Implements data loading at the ALS HERS beamline. |
|
Implements loading exported HDF files for ARPES data from Igor. |
|
A generic file loader for PXT files. |
|
The Kaindl Tr-ARPES high harmonic generation setup. |
|
Implements data loading at the microARPES endstation of ALS's MAESTRO. |
|
Implements data loading at the nanoARPES endstation of ALS's MAESTRO. |
|
Implements loading text files from the MB Scientific text file format. |
|
The MERLIN ARPES Endstation at the Advanced Light Source. |
|
Provides data loading for the Lanzara group experimental ARToF. |
|
Class for PHOIBOS 100 controlled by using prodigy. |
|
Implements loading xy text files from the Specs Prodigy software. |
Curve Fitting#
General Curve Fitting Utilities#
|
Turns an lmfit.model.ModelResult into a dictionary with initial guesses. |
Models#
Utilities related to curve-fitting of ARPES data and xarray format data.
Definitions of models involving Fermi edges. |
|
Definitions of models involving Dirac points, graphene, graphite. |
|
Definitions of band shape. |
|
Common implementations of peaks, backgrounds for other models. |
|
Some miscellaneous model definitions. |
|
Curve fitting models with two independent variables. |
Plotting#
Interactive Utilities: holoviews Based#
Public plotting API with lazy imports to avoid circular dependencies.
|
Creates an interactive UI to visualize concatenation along the phi axis. |
|
Generates an interactive 2D profile view with cross-sectional analysis. |
|
Displays interactive visualization of fitted ARPES data with residuals. |
|
An interactive smoothing UI for xarray DataArray using Panel and HoloViews. |
|
An interactive differentiation UI for xarray DataArray using Panel and HoloViews. |
General Utilities/Matplotlib Quality of Life#
An incomplete list of useful plotting utilities from arpes.utilities.plotting.
|
Provides workspace and date scoped path generation for plots. |
|
The PyARPES preferred figure saving routine. |
|
Generates a square-ish set of axes and hides the extra ones. |
Make a Axes instance completely invisible. |
|
|
Removes colorbars from given (or current) matplotlib figure. |
|
Makes thick, visually striking borders on a matplotlib plot. |
Context manager that retains axis limits. |
|
|
Convenience method to plot an array with a mask over some other data. |
|
Plots a mask by using a fixed color and transparency. |
|
Conditionally escapes a string based on the matplotlib settings. |
|
Attaches better display axis labels for all axes. |
|
Makes a summary plot with different marginal plots represented. |
Interactive Utilities: Matplotlib Based#
Stack Plots#
|
Generates a stack plot with all the lines distinguished by offset (and color). |
|
Generates a stack plot with all the lines distinguished by color rather than offset. |
|
Makes a stack plot (scatters version). |
Spin-ARPES Plots#
|
Plots a simple spin polarized spectrum using curves for the up and down components. |
|
Plots a spin spectrum using total intensity. |
|
Plots a spin difference spectrum. |
Count-based and ToF Plots#
|
Makes a fill-between line plot with error bars from associated statistical errors. |
|
Makes a scatter plot of data with error bars generated from associated statistical errors. |
Reference Plots#
|
Helpfully plots data against a reference scanning dataset. |
|
Plots the spatial content of a dataset, useful as a quick reference. |
Curve Fitting Plots#
|
Performs a straightforward plot of the data, residual, and fit to an axis. |
|
Plots several fits onto a grid of axes. |
|
Creates a scatter plot of a parameter from a broadcast_fit result. |
False Color Plots#
|
Plots a spectrum in false color after conversion to R, G, B arrays. |
Plotting with Brillouin Zones#
|
A dimension agnostic tool used to plot ARPES data onto a Brillouin zone. |
|
A higher order function to plot a Brillouin zone over a plot. |
|
Plots a 2D cut plane onto a Brillouin zone. |
Plot Annotations#
|
Annotates a cut location onto a plot. |
|
Annotates a point or high symmetry location into a plot. |
Renders information about the experimental conditions onto a set of axes. |