Skip to content

API Reference

This section contains the auto-generated reference detailing the functions and modules available in EasyDiffraction.

Job

Bases: JobBase

This class is the base class for all diffraction specific jobs

calculator property writable

Get the calculator from the interface.

instrument property

Alias to self.parameters

theoretical_model property writable

For diffraction, the theoretical_model is the sample

add_analysis_from_file(file_url)

Add an analysis to the job from a CIF file. Just a wrapper around the Analysis class method.

add_datastore(datastore)

Add a datastore to the job.

add_experiment_from_file(file_url)

Add an experiment to the job from a CIF file. Just a wrapper around the Experiment class method.

add_experiment_from_string(cif_string)

Add an experiment to the job from a CIF string. Just a wrapper around the Experiment class method.

add_phase(id='', phase=None)

Add a phase to the Sample.

add_sample_from_file(file_url)

Deprecated. Use add_phase_from_file instead. Add a sample to the job from a CIF file. Just a wrapper around the Sample class method.

add_sample_from_string(cif_string)

Add a sample to the job from a CIF string. Just a wrapper around the Sample class method.

calculate_profile(x=None, simulation_name='', **kwargs)

Pull out necessary data from the datastore and calculate the profile.

calculate_theory(x, simulation_name='', **kwargs)

Implementation of the abstract method from JobBase. Just a wrapper around the profile calculation.

fit(**kwargs)

Fit the profile based on current phase and experiment.

from_cif_file(phase=None, experiment=None) classmethod

Create the job from a CIF file. Allows for instatiation of the job with a sample and experiment from CIF files.

:param phase: URL of the CIF file containing the sample information. :param experiment: URL of the CIF file containing the experiment information. note: both can be the same file e.g. job = Job.from_cif_file(phase="d1a_phase.cif", experiment="d1a_exp.cif") job = Job.from_cif_file("d1a.cif")

get_parent_name(unique_name)

Get the pretty name of the parameter.

is_notebook()

Check if the code is running in a Jupyter notebook.

print_data()

Print the datastore.

remove_phase(id)

Remove a phase from the Sample.

set_background(points)

Sets a background on the pattern.

set_job_from_file(file_url)

Set the job from a CIF file.

Based on keywords in the CIF file, the job type is determined, the job is modified and the data is loaded from the CIF file.

show_analysis_chart(show_legend=True)

Show the analysis chart.

show_crystal_structure(id=None)

Show the crystal structure.

show_experiment_chart(show_legend=True)

Show the experiment chart.

show_free_parameters()

Show only free parameters.

show_parameters()

Show all parameters (fixed and free).

show_simulation_chart(show_legend=True)

Show the simulation chart.

to_cif()

Convert the job to a CIF file.

update_exp_type()

Update the experiment type based on the job.

update_experiment_type()

Update the job type based on the experiment.

update_interface()

Update the interface based on the current job.

update_phase_scale()

Update the phase scale based on the experiment.

Phase

Bases: Phase

atom_sites property

Vanity method to alias atoms

download_from_repository(file_name, branch='master', destination='data')

This function downloads a file from the EasyDiffraction repository on GitHub. :param file_name: The name of the file to download :param branch: The branch of the repository to download from :param destination: The destination folder to save the file :return: None

calculators

wrapper_base

WrapperBase

Bases: ComponentSerializer

This class is a template and defines all properties that an interface should have.

__init_subclass__(is_abstract=False, **kwargs)

Initialise all subclasses so that they can be created in the factory

:param is_abstract: Is this a subclass which shouldn't be dded :type is_abstract: bool :param kwargs: key word arguments :type kwargs: dict :return: None :rtype: noneType

create(model) abstractmethod

Method to create an object in the calculator workspace and return it's ID. This ID will be used in the implicit get/set for properties.

:param model: :type model: :return: :rtype:

fit_func(x_array) abstractmethod

Function to perform a fit

:param x_array: points to be calculated at :type x_array: np.ndarray :return: calculated points :rtype: np.ndarray

This links an atom to a model

:param model_name: Name of Phase :type model_name: str :param atom: Site object :type atom: Atom :return: :rtype:

remove_atom(model_name, atom) abstractmethod

This links an atom to a model

:param model_name: Name of Phase :type model_name: str :param atom: Site object :type atom: Atom :return: :rtype:

io

cif

CifParser

Parses a CIF file. Attempts to fix CIFs that are out-of-spec, but will issue warnings if corrections applied. These are also stored in the CifParser's errors attribute.

has_errors property

:return: Whether there are errors/warnings detected in CIF parsing.

number_of_cifs property

Get the number of cif's stored

:return: number of cif's stored :rtype: int

__init__(filename, occupancy_tolerance=1.0, site_tolerance=0.0001)

Parameters:

Name Type Description Default
filename str

CIF filename, bzipped or gzipped CIF files are fine too.

required
occupancy_tolerance float

If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1.

1.0
site_tolerance float

This tolerance is used to determine if two sites are sitting in the same position, in which case they will be combined to a single disordered site. Defaults to 1e-4.

0.0001
from_string(cif_string, occupancy_tolerance=1.0) classmethod

Creates a CifParser from a string.

:param cif_string: String representation of a CIF. :type cif_string: str :param occupancy_tolerance: :type occupancy_tolerance: :return: If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1. :rtype: CifParser

get_atoms(cif_index=0, atoms_class=None)

Generate the an atoms list with adp if available

:param cif_index: Which lattice do you want. There may be more than one. :type cif_index: int :return: Parsed atoms and adp :rtype: Atoms

get_lattice(cif_index=0, length_strings=('a', 'b', 'c'), angle_strings=('alpha', 'beta', 'gamma'), lattice_type=None)

Generate the lattice from the provided lattice parameters. In the absence of all six lattice parameters, the crystal system and necessary parameters are parsed

:param cif_index: Which lattice do you want. There may be more than one :type cif_index: int :param length_strings: Length parameters to be searched for :type length_strings: tuple :param angle_strings: Angle parameters to be searched for :type angle_strings: tuple :param lattice_type: Lattice system (Optional) :type lattice_type: str :return: Constructed lattice :rtype: Lattice

str2float(text)

Remove uncertainty brackets from strings and return the float.

cif_reader

value_from_loop_by_another_column(block, category, desired_column, another_column, another_value)

Retrieve a value from the desired column in a loop by matching another column's value.

Parameters:

Name Type Description Default
block Block

CIF block.

required
category str

CIF category name.

required
desired_column str

Desired column name.

required
another_column str

Column name to match the value.

required
another_value str

Value to match in another column.

required

Returns:

Name Type Description
str str | None

The value from the desired column if found, otherwise None.

job

analysis

analysis

Analysis

Bases: AnalysisBase

Diffraction-specific Experiment object.

available_minimizers property

Return a list of available minimizers, converted to a list of strings.

current_minimizer property writable

Return the current minimizer as a string.

calculate_profile(x=None, coord=None, **kwargs)

Calculate the profile based on current phase.

calculate_theory(x, **kwargs)

Implementation of the abstract method from JobBase. Just a wrapper around the profile calculation.

fit(x, y, e, **kwargs)

Fit the profile based on current phase and experiment.

from_cif(cif_file) staticmethod

Load the analysis from a CIF file

experiment

backgrounds

background
Background

Bases: BaseCollection

Background is a base class for which different types of backgrounds can be built. It functions as a pseudo list of elements which can be used to generate a background using the abstract calculate method. i.e. contents could be points in a point based background or polynomials in a curve background.

linked_experiment property writable

Get the experiment which the background is linked to :return: linked experiment name :rtype: Descriptor

__init__(*args, linked_experiment=None, **kwargs)

Initialisation routine called from super(). Each background has to be linked with an experiment

:param args: Optional elements which are making up the background :param linked_experiment: which experiment this background should be linked to :type linked_experiment: str :param kwargs: For serialisation

calculate(x_array) abstractmethod

Abstract method to actually calculate the background.

:param x_array: values to be calculated at :type x_array: np.ndarray :return: y-values of the calculated background :rtype: np.ndarray

BackgroundContainer

Bases: BaseCollection

Background container which will hold all the backgrounds for a given instance. Backgrounds can be of any type and have to be associated to an experiment. There can't be multiple backgrounds associated with an experiment!!

linked_experiments property

Get a list of experiments for which items are linked.

:return: :rtype:

__delitem__(key)

Remove a background from the list. Key can be an index or experiment name

:param key: Unique identifier of key to be removed :type key: int, str :return: None

__getitem__(idx)

Obtain an item in the list from either it's integer position or a slice object.

:param idx: Which item to retrieve :type idx: int :return: Background object :rtype: Background

__init__(*args, interface=None, **kwargs)

Constructor, with a link to an interface.

__repr__()

Simple representation of the object

:return: Simple representation of the object :rtype: str

append(item)

Add an element to the list

:param item: Background element :type item: Background

factorial
BackgroundFactor

Bases: BaseObj

This class describes a polynomial factor. It contains an amplitude and a power. i.e. for x, Ax^p

__init__(power, amp)

Construct a background factor.

:param power: Power to which x will be raised. :type power: Descriptor :param amp: Amplitude for which x will be multiplied by :type amp: Parameter

default() classmethod

Construct a default background factor with amplitude 1 and power 0

:return: Constructed background factor :rtype: BackgroundFactor

from_pars(power, amp) classmethod

Construct a background factor from a power and amplitude as an integer/float respectively.

:param power: Power to which x will be raised. :type power: int :param amp: Amplitude for which x will be multiplied by :type amp: float :return: Constructed background factor :rtype: BackgroundFactor

set(value)

Convenience function to set the background amplitude.

:param value: New amplitude value :type value: float :rtype: None

FactorialBackground

Bases: Background

Create a background which is constructed from a collection of background factors. Note that the background factors are not stored in order!! sorted_powers and sorted_amplitudes should be used to access these factors in the numerical order (based on increasing powers).

names property

Get the names of the factors in the collection.

:return: Names of the factors in the collection :rtype: List[str]

sorted_amplitudes property

Get the stored amplitudes based on the sorted powers

:return: Sorted amplitudes :rtype: np.ndarray

sorted_powers property

Get the stored powers as a sorted array

:return: Sorted powers :rtype: np.ndarray

__delitem__(idx)

Remove an item from the collection at index idx

:param idx: index of the item to be deleted :type idx: int

__getitem__(idx)

Return an item from the collection.

:param idx: index of item to be returned. :type idx: int :return: item at point idx :rtype: Union[Parameter, Descriptor, BaseObj, 'BaseCollection']

__index_contents()

Index the contents

__init__(*args, **kwargs)

Factorial based background constructor.

:param args: Background factors to be added to the background (optional) :type args: BackgroundFactor :param linked_experiment: Which experiment should this background be linked with. :type linked_experiment: str :param kwargs: Any additional kwargs

__repr__()

String representation of the background

:return: String representation of the background :rtype: str

append(item)

Add a background factor to the collection.

:param item: Background factor to be added. :type item: BackgroundFactor

calculate(x_array)

Generate a background from the stored background factors.

:param x_array: Points for which the background should be calculated. :type x_array: np.ndarray :return: Background points at the supplied x-positions. :rtype: np.ndarray

get_parameters()

" Redefine get_parameters so that the returned values are in the correct order

point
BackgroundPoint

Bases: BaseObj

This class describes a background point. It contains x position and y intensities. Note that the label for x varies with it's value!!!

__init__(x=0.0, y=0.0, name=None)

Construct a background point from a x-Descriptor any y-parameter.

:param x: x-position of the background point :type x: Descriptor :param y: Intensity/y-position of the background point :type y: Parameter :param name: Override the default naming. :type name: str

set(value)

Convenience function to set the background intensity.

:param value: New intensity/y-position value :type value: float :rtype: None

PointBackground

Bases: Background

Create a background which is constructed from a collection of background points. Note that the background points are not stored in order!! x_sorted_points and y_sorted_points should be used to access these points in the numerical order.

names property

Get the names of the points in the collection.

:return: Names of the points in the collection :rtype: List[str]

x_sorted_points property

Get the stored x-values as a sorted array

:return: Sorted x-values :rtype: np.ndarray

y_sorted_points property

Get the stored y-values based on the sorted x-values

:return: Sorted y-values :rtype: np.ndarray

__delitem__(idx)

Remove an item from the collection at index idx

:param idx: index of the item to be deleted :type idx: int

__getitem__(idx)

Return an item from the collection.

:param idx: index of item to be returned. :type idx: int :return: item at point idx :rtype: Union[Parameter, Descriptor, BaseObj, 'BaseCollection']

__init__(*args, linked_experiment=None, **kwargs)

Point based background constructor.

:param args: Background points to be added to the background (optional) :type args: BackgroundPoint :param linked_experiment: Which experiment should this background be linked with. :type linked_experiment: str :param kwargs: Any additional kwargs

__repr__()

String representation of the background

:return: String representation of the background :rtype: str

append(item)

Add a background point to the collection.

:param item: Background point to be added. :type item: BackgroundPoint

calculate(x_array)

Generate a background from the stored background points.

:param x_array: Points for which the background should be calculated. :type x_array: np.ndarray :return: Background points at the supplied x-positions. :rtype: np.ndarray

get_parameters()

" Redefine get_parameters so that the returned values are in the correct order

common

DataContainer

Bases: ComponentSerializer

as_dict(skip=None)

:return: Json-able dictionary representation.

from_dict(d) classmethod

:param d: Dict representation. :return: Species.

data_container

DataContainer

Bases: ComponentSerializer

as_dict(skip=None)

:return: Json-able dictionary representation.

from_dict(d) classmethod

:param d: Dict representation. :return: Species.

experiment

Experiment

Bases: ExperimentBase

Diffraction-specific Experiment object.

cif property

Returns a CIF representation of the experiment. (pattern, background, instrument, data points etc.)

e property

Returns the error data as xarray

x property

Returns the x-axis data as xarray

y property

Returns the y-axis experimental data as xarray

y_alpha property

Returns the y-axis experimental data as xarray

y_beta property

Returns the y-axis experimental data as xarray

background_as_cif(background=None, is_tof=False) staticmethod

Returns a CIF representation of the background.

cw_param_as_cif(parameters=None, pattern=None) staticmethod

Returns a CIF representation of the CW instrument parameters

exp_data_as_cif()

Returns a CIF representation of the experimental datapoints x,y,e.

from_cif(cif_file) staticmethod

Load the experiment from a CIF file

from_cif_block(block, experiment_name=None)

Load a CIF file and extract the experiment data. This includes - the pattern parameters - the instrumental parameters - the phase parameters - the data points - the background

from_cif_file(file_url, experiment_name=None)

Load a CIF file into the experiment.

from_cif_strig(cif_string) staticmethod

Load the experiment from a string

from_cif_string(cif_string, experiment_name=None)

Load a CIF string into the experiment.

from_xye_file(file_url, experiment_name=None)

Load an xye file into the experiment. All instrumental parameters are set to default values, defined in the Instrument1DCWParameters class.

tof_param_as_cif(pattern=None, parameters=None) staticmethod

Returns a CIF representation of the TOF instrument parameters

experiment_type

ExperimentType

Specification of the diffraction job type.

Available types are: sample type: powder: pd (Default) single crystal: sc beam type: continuous wave: cwl (Default) time-of-flight: tof dimensionality: 1D: 1d (Default) 2D: 2d radiation type: neutrons: neut (Default) x-ray: xray polarization: unpolarized: unp (Default) polarized: pol longitudinal polarized: lpa spherical polarimetry: snp

String-based specification can be provided in any order, in any combination. Example: a = ExperimentType("pd-cwl-unp-1d-xray") b = ExperimentType("cwl-unp-neut") c = ExperimentType("tof")

init_flags()

Initialize the job type flags

to_typestr()

Convert the job type to a string

validate()

Validate the job type

simulation

Sample

Bases: TheoreticalModelBase

Diffraction-specific Experiment object.

from_cif(cif_file) staticmethod

Load the sample from a CIF file

job

DiffractionJob

Bases: JobBase

This class is the base class for all diffraction specific jobs

calculator property writable

Get the calculator from the interface.

instrument property

Alias to self.parameters

theoretical_model property writable

For diffraction, the theoretical_model is the sample

add_analysis_from_file(file_url)

Add an analysis to the job from a CIF file. Just a wrapper around the Analysis class method.

add_datastore(datastore)

Add a datastore to the job.

add_experiment_from_file(file_url)

Add an experiment to the job from a CIF file. Just a wrapper around the Experiment class method.

add_experiment_from_string(cif_string)

Add an experiment to the job from a CIF string. Just a wrapper around the Experiment class method.

add_phase(id='', phase=None)

Add a phase to the Sample.

add_sample_from_file(file_url)

Deprecated. Use add_phase_from_file instead. Add a sample to the job from a CIF file. Just a wrapper around the Sample class method.

add_sample_from_string(cif_string)

Add a sample to the job from a CIF string. Just a wrapper around the Sample class method.

calculate_profile(x=None, simulation_name='', **kwargs)

Pull out necessary data from the datastore and calculate the profile.

calculate_theory(x, simulation_name='', **kwargs)

Implementation of the abstract method from JobBase. Just a wrapper around the profile calculation.

fit(**kwargs)

Fit the profile based on current phase and experiment.

from_cif_file(phase=None, experiment=None) classmethod

Create the job from a CIF file. Allows for instatiation of the job with a sample and experiment from CIF files.

:param phase: URL of the CIF file containing the sample information. :param experiment: URL of the CIF file containing the experiment information. note: both can be the same file e.g. job = Job.from_cif_file(phase="d1a_phase.cif", experiment="d1a_exp.cif") job = Job.from_cif_file("d1a.cif")

get_parent_name(unique_name)

Get the pretty name of the parameter.

is_notebook()

Check if the code is running in a Jupyter notebook.

print_data()

Print the datastore.

remove_phase(id)

Remove a phase from the Sample.

set_background(points)

Sets a background on the pattern.

set_job_from_file(file_url)

Set the job from a CIF file.

Based on keywords in the CIF file, the job type is determined, the job is modified and the data is loaded from the CIF file.

show_analysis_chart(show_legend=True)

Show the analysis chart.

show_crystal_structure(id=None)

Show the crystal structure.

show_experiment_chart(show_legend=True)

Show the experiment chart.

show_free_parameters()

Show only free parameters.

show_parameters()

Show all parameters (fixed and free).

show_simulation_chart(show_legend=True)

Show the simulation chart.

to_cif()

Convert the job to a CIF file.

update_exp_type()

Update the experiment type based on the job.

update_experiment_type()

Update the job type based on the experiment.

update_interface()

Update the interface based on the current job.

update_phase_scale()

Update the phase scale based on the experiment.

model

phase

Phase

Bases: Phase

atom_sites property

Vanity method to alias atoms

old_sample

old_sample

Sample

Bases: BaseObj

cif property

Returns a CIF representation of the sample.

phases_as_cif()

Returns a CIF representation of the phases names and scales.

utils

download_from_repository(file_name, branch='master', destination='data')

This function downloads a file from the EasyDiffraction repository on GitHub. :param file_name: The name of the file to download :param branch: The branch of the repository to download from :param destination: The destination folder to save the file :return: None