app_io

This module provides classes for reading and writing various file formats used in crystallography and diffraction analysis.

class fpfunctions.app_io.DiffractionIO

Bases: ABC

Abstract Class for reading different types of diffraction pattern data and transforming to DiffractionPattern class.

static check_exist(filename: str) bool

Check if a file exists at the specified path.

Parameters:

filename – Path to the file to check

Returns:

True if the file exists

Raises:

FileNotFoundError – If the file does not exist

abstract read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.DiffractionIOXYS

Bases: DiffractionIO

IO class for XYS format .dat data

Data is formatted as: % Headers % x y s % …

read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.DiffractionIOFree

Bases: DiffractionIO

IO class for Free format .dat data

Data is formatted as: % Headers % 2tteta_init, 2theta_step, 2theta_max % Y0, Y1, Y2, …, YN

read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.DiffractionIOSocabim

Bases: DiffractionIO

IO class for Socabim format data

Data is formatted as: % Headers (containing information) % Y0 % Y1 % … % YN

read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.DiffractionIOXrdML

Bases: DiffractionIO

IO class for .xrdml data

Data is formatted as an XML file where

read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.DiffractionIOD1AD2B

Bases: DiffractionIO

IO class for .dat data for D1A D2B neutron diffractometers

read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.DiffractionIOD1BD20

Bases: DiffractionIO

IO class for .dat data for D1B D20 neutron diffractometers

read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.DiffractionIODMC

Bases: DiffractionIO

IO class for .dat data for DMC diffractometer at PSI

read_fromfile(filename: str) numpy.typing.NDArray.numpy.float64

Read a given XRD pattern from a file.

Parameters:

filename – Path to the file to read

Returns:

NumPy array containing the diffraction data

_abc_impl = <_abc._abc_data object>
class fpfunctions.app_io.IODiffractionFactory

Bases: object

Factory class, it initializes Reader objects depending on the received target file format

classmethod factory_method(fmt: str | None = None) DiffractionIO

Create and return a DiffractionIO object for the specified format.

Parameters:

fmt – Format of the diffraction data file

Returns:

DiffractionIO object for the specified format

Raises:

ValueError – If fmt is None or not implemented

static check_implemented(fmt: str) bool
class fpfunctions.app_io.CifReaderWriter

Bases: object

Class for reading and writing CIF (Crystallographic Information File) files.

This class provides methods for reading CIF files from a directory, cleaning them to avoid encoding issues, and extracting crystallographic data.

data

Dictionary containing CIF data

error

List of errors encountered during reading

summary

Summary of the CIF data

__init__()

Initialize the CifReaderWriter object.

static clean_cifs(dirname: str, filename: str) None

Clean CIF files to avoid codec encoding issues.

Errors usually occur with special characters in the comments, so eliminate all lines that start with #.

Parameters:
  • dirname – Directory containing the CIF file

  • filename – Name of the CIF file

static _parse_mp_hm_symbol(hm_symbol: str) str

Parse Hermann-Mauguin symbol from Materials Project.

This method processes Hermann-Mauguin symbols from the Materials Project to handle special formatting like underscores and slashes. It converts symbols like “P_1” to “P1” and handles more complex cases with multiple special characters.

Parameters:

hm_symbol – Hermann-Mauguin symbol to parse

Returns:

Parsed Hermann-Mauguin symbol with proper formatting

read_from_dir(dirname: str) None

Read all .cif files in a directory.

Parameters:

dirname – Directory containing CIF files

_get_data_summary() List

Get data summary depending on provider.

This method processes CIF data to extract key crystallographic information including chemical formula, space group, symmetry number, and cell parameters. It handles different formatting conventions from various providers (Materials Project, ICSD, COD) and performs necessary transformations to standardize the data.

The method also calculates crystal system and family information using the crysfml_forpy library based on the extracted parameters.

Returns:

  • A pandas DataFrame with the summarized crystallographic data

  • A list of identifiers that could not be processed due to errors

Return type:

List containing two elements

class fpfunctions.app_io.IrfIO(irf_url: str)

Bases: object

Class for reading IRF (Instrument Resolution Function) files.

This class parses IRF files to extract various parameters related to instrument resolution and geometry.

res

Resolution parameter

jobt

Job type parameter

wave

Wavelength parameters (tuple)

thrg

THRG parameters (tuple)

prof

Profile parameters (tuple)

chtm

CTHM parameter

asym

Asymmetry parameters (tuple)

rkk

RKK parameter

ilo

Geometry parameter

optional_ilo

Optional geometry parameter

irf_url

Path to the IRF file

__init__(irf_url: str)

Initialize the IrfIO object.

Parameters:

irf_url – Path to the IRF file

read_file() None

Read the IRF file and extract parameters.

read_res() None

Read the RES tag from the IRF file.

read_jobt() None

Read the JOBT tag from the IRF file.

read_wavelength() None

Read the WAVE tag from the IRF file.

read_thrg() None

Read the THRG tag from the IRF file.

read_prof() None

Read the PROF tag from the IRF file.

read_cthm() None

Read the CTHM tag from the IRF file.

read_asym() None

Read the ASYM tag from the IRF file.

read_rkk() None

Read the RKK tag from the IRF file.

read_geom() None

Read the GEOM tag from the IRF file.

class fpfunctions.app_io.BackgroundType(value)

Bases: Enum

Enumeration of background types for diffraction patterns.

POINTS

Background defined by anchor points

CHEBYSHEV

Background defined by Chebyshev polynomials

FOURIER

Background defined by Fourier filtering

POINTS = 1
CHEBYSHEV = 2
FOURIER = 3
class fpfunctions.app_io.PcrIO(path: str, jobid: str | None = None)

Bases: object

Class for reading and writing PCR (FullProf Control) files.

This class provides methods for reading, writing, and manipulating PCR files used by the FullProf refinement program. It supports both single pattern and multi-pattern PCR files.

custom_pcr

Dictionary containing PCR file data

multipattern

Boolean indicating if the PCR file is multi-pattern

path

Path to the directory containing the PCR file

background

Dictionary containing background data

jobid

Job identifier (filename without extension)

__init__(path: str, jobid: str | None = None)

Initialize the PcrIO object.

Parameters:
  • path – Path to the directory containing the PCR file

  • jobid – Job identifier (filename without extension). If None, the basename of the path is used.

prepare_buf(identifiers: List[str], dirname: str) None

Generate a buffer file (.buf) from CIF files in the selection section.

This method creates a buffer file that lists the CIF files to be used for generating a PCR file using the CIFs_to_PCR utility. It also copies the CIF files to the working directory if they are not already there.

Parameters:
  • identifiers – List of identifiers (filenames without .cif extension)

  • dirname – Directory containing the CIF files

prepare_c2pcr(data: List[DiffractionSignal], simulation: bool = False) None

Generate a configuration file (.c2pcr) for CIFs_to_PCR.

This method creates a configuration file that specifies the patterns and instrument parameters for generating a PCR file from CIF files.

Parameters:
  • data – List of diffraction pattern objects containing metadata

  • simulation – If True, creates a configuration for simulation mode instead of using actual data files

read_custom_pcr() bool

Read a PCR file, attempting both multipattern and single pattern formats.

This method first tries to read the PCR file as a multipattern format. If that fails, it attempts to read it as a single pattern format.

Returns:

True if the PCR file was successfully read, False otherwise

Return type:

bool

read_custom_pcr_singlepattern() None

Read a single pattern PCR file.

This method parses a single pattern PCR file and populates the custom_pcr dictionary with the extracted data. The PCR file is read line by line, with each section of the file being parsed according to the FullProf format.

Raises:
  • ValueError – If the PCR file is missing required sections or has an invalid format

  • KeyError – If a required key is missing in the parsed data

  • IndexError – If an index is out of range during parsing

static check_whitespace(line: List[str])

Sometimes Uiso value fields from CIF files are really big and CIF_to_PCR jams to columns into one because of formatting, we try to solve this issue here. Only provisionally, this should be fixed

read_custom_pcr_multipattern() None

Read a multi-pattern PCR file.

This method parses a multi-pattern PCR file and populates the custom_pcr dictionary with the extracted data. The PCR file is read line by line, with each section of the file being parsed according to the FullProf format.

Raises:
  • ValueError – If the PCR file is missing required sections or has an invalid format

  • KeyError – If a required key is missing in the parsed data

  • IndexError – If an index is out of range during parsing

save_background(ipatt: int | None = None)
edit_fromcif2pcr_to_custom(mode: BackgroundType = BackgroundType.POINTS, order: int | None = None, fourin: Tuple | None = None, excluded: List | None = None, ipatt: int | None = None, patt: DiffractionSignal | None = None)
write_pcr_custom(path: str | None = None) bool

Write a PCR file, attempting both multipattern and single pattern formats.

This method first tries to write the PCR file as a multipattern format. If that fails, it attempts to write it as a single pattern format.

Parameters:

path – Optional path where the PCR file will be written. If None, the file will be written to the default location using the jobid.

Returns:

True if the PCR file was successfully written, False otherwise

Return type:

bool

write_pcr_custom_singlepattern(path: str | None = None) None

Write a single pattern PCR file.

This method writes the PCR file in single pattern format, using the data stored in the custom_pcr dictionary. If the file already exists, it will be overwritten.

Parameters:

path – Optional path where the PCR file will be written. If None, the file will be written to the default location using the jobid.

Raises:
  • KeyError – If a required key is missing in the custom_pcr dictionary

  • ValueError – If a value in the custom_pcr dictionary is invalid

write_pcr_custom_multipattern(path: str | None = None) None

Write a multi-pattern PCR file.

This method writes the PCR file in multi-pattern format, using the data stored in the custom_pcr dictionary. If the file already exists, it will be overwritten.

Parameters:

path – Optional path where the PCR file will be written. If None, the file will be written to the default location using the jobid.

Raises:
  • KeyError – If a required key is missing in the custom_pcr dictionary

  • ValueError – If a value in the custom_pcr dictionary is invalid

  • IndexError – If an index is out of range during writing

exclude_patterns(vals: numpy.typing.NDArray.<class 'int'>)
get_patt_num()
get_flags_global(tag: str, ipatt: int | None = None) int | float

Get the value of a global flag from the PCR file.

This method retrieves the value of a global parameter identified by the tag. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • tag – The identifier of the flag to retrieve (e.g., ‘nph’, ‘job’, ‘nba’)

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The value of the specified flag as a number (int or float)

Raises:

KeyError – If the tag is not found in the _flag_tags dictionary or if the corresponding key is not in the custom_pcr dictionary

edit_flags_global(tag: str, val: int | float, ipatt: int | None = None) None

Edit the value of a global flag in the PCR file.

This method updates the value of a global parameter identified by the tag. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • tag – The identifier of the flag to edit (e.g., ‘nph’, ‘job’, ‘nba’)

  • val – The new value to set for the flag

  • ipatt – Optional pattern index for multi-pattern PCR files

Raises:

KeyError – If the tag is not found in the _flag_tags dictionary or if the corresponding key is not in the custom_pcr dictionary

get_shifts_global(tag: str, ipatt: int | None = None) int | float

Get the value of a global shift parameter from the PCR file.

This method retrieves the value of a shift parameter identified by the tag. For multi-pattern PCR files, the pattern index can be specified. The method automatically selects the appropriate shift tags based on the job type (TOF or default).

Parameters:
  • tag – The identifier of the shift parameter to retrieve (e.g., ‘zero’, ‘sycos’, ‘sysin’)

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The value of the specified shift parameter as a number (int or float)

Raises:

KeyError – If the tag is not found in the _shift_tags dictionary or if the corresponding key is not in the custom_pcr dictionary

edit_shifts_global(tag: str, val: int | float, ipatt: int | None = None) None

Edit the value of a global shift parameter in the PCR file.

This method updates the value of a shift parameter identified by the tag. For multi-pattern PCR files, the pattern index can be specified. The method automatically selects the appropriate shift tags based on the job type (TOF or default).

Parameters:
  • tag – The identifier of the shift parameter to edit (e.g., ‘zero’, ‘sycos’, ‘sysin’)

  • val – The new value to set for the shift parameter

  • ipatt – Optional pattern index for multi-pattern PCR files

Raises:

KeyError – If the tag is not found in the _shift_tags dictionary or if the corresponding key is not in the custom_pcr dictionary

replace_zero_more(ipatt: int | None = None) None

Add additional zero shift parameters to the PCR file.

This method enables the ‘more_zero’ flag and initializes the additional zero shift parameters (p0, cp, tau) with default values of zero. For multi-pattern PCR files, the pattern index can be specified.

Parameters:

ipatt – Optional pattern index for multi-pattern PCR files

Note

This adds the params5more section to the PCR file with default values.

remove_zero_more(ipatt: int | None = None) None

Remove additional zero shift parameters from the PCR file.

This method disables the ‘more_zero’ flag and removes the additional zero shift parameters section from the PCR file. For multi-pattern PCR files, the pattern index can be specified.

Parameters:

ipatt – Optional pattern index for multi-pattern PCR files

Note

This removes the params5more section from the PCR file.

get_excluded(ipatt: int) numpy.typing.NDArray.numpy.float64 | None

Get the excluded regions for a pattern.

This method retrieves the excluded regions for a specific pattern. Excluded regions are ranges of scattering variable values that are excluded from the refinement.

Parameters:

ipatt – Pattern index

Returns:

NumPy array containing the excluded regions as pairs of scattering variable values, or None if no excluded regions are defined

replace_excluded(excluded: numpy.typing.NDArray.numpy.float64, ipatt: int | None = None) None

Replace the excluded regions for a pattern.

This method replaces the excluded regions for a specific pattern with the provided array. Excluded regions are ranges of scattering variable values that are excluded from the refinement.

Parameters:
  • excluded – NumPy array containing the excluded regions as pairs of scattering variable values

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

The method also updates the ‘nex’ flag to reflect the number of excluded regions.

remove_excluded(ipatt: int | None = None) None

Remove all excluded regions for a pattern.

This method removes all excluded regions for a specific pattern by setting the ‘nex’ flag to 0 and removing the excluded regions data from the PCR file.

Parameters:

ipatt – Optional pattern index for multi-pattern PCR files

Note

This completely removes all excluded regions for the pattern.

get_background(ipatt: int | None = None) List[numpy.typing.NDArray.numpy.float64 | BackgroundType] | None

Get the background data and type for a pattern.

This method retrieves the background data and determines its type (points, Chebyshev, or Fourier) based on the ‘nba’ flag value.

Parameters:

ipatt – Optional pattern index for multi-pattern PCR files

Returns:

A list containing the background data array and the BackgroundType enum value, or None if no background is defined

Note

The background type is determined by the ‘nba’ flag: - nba > 2: Points background (anchor points) - nba = -5: Chebyshev polynomial background - nba = -2: Fourier series background

transform_anchor_to_cheb(order: int, ipatt: int | None = None) None

Transform anchor points background to Chebyshev polynomial background.

This method converts a background defined by anchor points to a background defined by Chebyshev polynomials of the specified order. The conversion involves normalizing the x-coordinates, fitting a Chebyshev polynomial, and reshaping the coefficients into the format expected by FullProf.

Parameters:
  • order – Order of the Chebyshev polynomial to fit

  • ipatt – Optional pattern index for multi-pattern PCR files

Raises:

ValueError – If the background is not in anchor points format (shape[1] != 3)

Note

The method automatically replaces the background in the PCR file with the new Chebyshev polynomial background.

static expand_chebyshev_polinomial(x: numpy.typing.NDArray.numpy.float64, order: int) List[numpy.typing.NDArray.numpy.float64]

Expand Chebyshev polynomials for a given array of x values.

This method calculates the values of Chebyshev polynomials of the first kind for each value in the input array x. It computes polynomials from order 0 to order-1.

Parameters:
  • x – Array of x values in the range [-1, 1]

  • order – Number of Chebyshev polynomials to compute

Returns:

List of arrays, where each array contains the values of a Chebyshev polynomial evaluated at each point in x

Note

The implementation uses the trigonometric definition of Chebyshev polynomials: T_n(x) = cos(n * arccos(x))

NaN values that may occur at the boundaries (x = ±1) are replaced with 0.999999

transform_cheb_to_background(x: numpy.typing.NDArray.numpy.float64, ipatt: int | None = None) numpy.typing.NDArray.numpy.float64 | None

Transform Chebyshev polynomial coefficients to background values.

This method calculates background values at the specified x-coordinates using Chebyshev polynomial coefficients stored in the PCR file.

Parameters:
  • x – Array of x-coordinates where the background should be evaluated

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

Array of background values at the specified x-coordinates, or None if the background is not in Chebyshev format

Note

The method normalizes the x-coordinates to the range [-1, 1], extracts the non-zero coefficients, and calculates the background as a sum of Chebyshev polynomials multiplied by their coefficients.

transform_cheb_to_anchor(x: numpy.typing.NDArray.numpy.float64, ipatt: int | None = None, nba: int = 30) None

Transform Chebyshev polynomial background to anchor points background.

This method converts a background defined by Chebyshev polynomials to a background defined by anchor points. It samples the Chebyshev background at regular intervals to create anchor points.

Parameters:
  • x – Array of x-coordinates where the background should be evaluated

  • ipatt – Optional pattern index for multi-pattern PCR files

  • nba – Number of anchor points to generate (default: 30)

Note

The method automatically replaces the background in the PCR file with the new anchor points background. The anchor points are evenly spaced along the x-axis, with the first and last points excluded.

If the background cannot be transformed (e.g., if it’s not in Chebyshev format), the method does nothing.

replace_background(background: numpy.typing.NDArray.numpy.float64, ipatt: int | None = None, mode: BackgroundType = BackgroundType.POINTS) None

Replace the background in the PCR file with a new background.

This method updates the background data in the PCR file with the provided array. The background can be in one of three formats: anchor points, Chebyshev polynomials, or Fourier series.

Parameters:
  • background – Array containing the new background data

  • ipatt – Optional pattern index for multi-pattern PCR files

  • mode – Type of background (POINTS, CHEBYSHEV, or FOURIER)

Raises:

ValueError – If the shape of the background array doesn’t match the expected shape for the specified background type

Note

The method also updates the ‘nba’ flag in the PCR file to reflect the new background type: - For POINTS: nba = number of anchor points - For CHEBYSHEV: nba = -5 - For FOURIER: nba = -2

remove_background(ipatt: int | None = None) None

Remove the background from the PCR file.

This method removes the background data from the PCR file and sets the ‘nba’ flag to 0, indicating that no background is defined.

Parameters:

ipatt – Optional pattern index for multi-pattern PCR files

Note

This completely removes the background data from the PCR file. To replace the background with a different one, use the replace_background method instead.

edit_background_code(opt: bool = False, ipatt: int | None = None) None

Edit the background code flags in the PCR file.

This method modifies the refinement flags for background parameters. For POINTS background type, it sets the third column (refinement flags) to either 1.0 (refine) or 0.0 (fix) for each anchor point. For CHEBYSHEV background type, it sets the refinement flags for the polynomial coefficients.

Parameters:
  • opt – If True, enable refinement of background parameters. If False, fix background parameters.

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

For POINTS background type with opt=True, the method will set refinement flags to 0.0 for anchor points within excluded regions.

get_irf(ipatt: int | None = None) str

Get the IRF (Instrument Resolution Function) file path from the PCR file.

This method retrieves the path to the IRF file specified in the PCR file. For multi-pattern PCR files, the pattern index can be specified.

Parameters:

ipatt – Optional pattern index for multi-pattern PCR files

Returns:

Path to the IRF file as a string

replace_irf(filename: str, ipatt: int | None = None) None

Replace the IRF (Instrument Resolution Function) file path in the PCR file.

This method updates the path to the IRF file in the PCR file. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • filename – New path to the IRF file

  • ipatt – Optional pattern index for multi-pattern PCR files

get_names(ipatt: int | None = None) str | None

Get the pattern name from the PCR file.

This method retrieves the name of a diffraction pattern from the PCR file. Only applicable for multi-pattern PCR files.

Parameters:

ipatt – Pattern index for multi-pattern PCR files

Returns:

The pattern name as a string, or None if not a multi-pattern PCR file or if ipatt is None

replace_names(filename: str, ipatt: int | None = None) None

Replace the pattern name in the PCR file.

This method updates the name of a diffraction pattern in the PCR file. Only applicable for multi-pattern PCR files.

Parameters:
  • filename – New name for the pattern

  • ipatt – Pattern index for multi-pattern PCR files

read_ids() List[str]

Get the identifiers of all phases in the PCR file.

This method retrieves the names of all phases defined in the PCR file, removing the ‘.cif’ extension if present.

Returns:

List of phase identifiers (strings)

read_site_labels(identifier: str) List[str] | None

Get the labels of all atomic sites in a phase.

This method retrieves the labels of all atomic sites defined in a specific phase.

Parameters:

identifier – Phase identifier

Returns:

List of atomic site labels, or None if the phase has no sites

read_site_elements(identifier: str) List[str] | None

Get the unique element types in a phase.

This method retrieves the unique element types defined in a specific phase.

Parameters:

identifier – Phase identifier

Returns:

List of unique element types, or None if the phase has no sites

remove_sites(identifier: str) None

Remove all atomic sites from a phase.

This method removes all atomic sites from a specific phase and updates the ‘nat’ flag to 0.

Parameters:

identifier – Phase identifier

get_flags_phase(identifier: str, tag: str, ipatt: int | None = None) int | float

Get the value of a phase-specific flag from the PCR file.

This method retrieves the value of a parameter for a specific phase identified by the tag. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the flag to retrieve (e.g., ‘nat’, ‘jbt’, ‘irf’)

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The value of the specified flag as a number (int or float)

Raises:

KeyError – If the tag is not found in the _phase_tags dictionary or if the corresponding key is not in the custom_pcr dictionary

edit_flags_phase(identifier: str, tag: str, val: int | float, ipatt: int | None = None) None

Edit the value of a phase-specific flag in the PCR file.

This method updates the value of a parameter for a specific phase identified by the tag. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the flag to edit (e.g., ‘nat’, ‘jbt’, ‘irf’)

  • val – The new value to set for the flag

  • ipatt – Optional pattern index for multi-pattern PCR files

Raises:

KeyError – If the tag is not found in the _phase_tags dictionary or if the corresponding key is not in the custom_pcr dictionary

add_phase_more(identifier: str) None

Add additional phase parameters to the PCR file.

This method enables the ‘more_phase’ flag and initializes the additional phase parameters with default values. The parameters added depend on whether the PCR file is multi-pattern or single pattern.

Parameters:

identifier – Phase identifier

Note

This adds the params1more section to the PCR file with default values.

remove_phase_more(identifier: str) None

Remove additional phase parameters from the PCR file.

This method disables the ‘more_phase’ flag and removes the additional phase parameters section from the PCR file, including any BVS (Bond Valence Sum) related parameters.

Parameters:

identifier – Phase identifier

Note

This removes the params1more section, bvs, and bvs_ions sections from the PCR file.

get_phase_volume(identifier: str, ipatt: int | None = None) float

Calculate the unit cell volume for a phase.

This method retrieves the cell parameters (a, b, c, alpha, beta, gamma) for a specific phase and calculates the unit cell volume using the crysfml_forpy library.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The unit cell volume in cubic Angstroms

Note

The calculation is performed using the crysfml_forpy library’s get_crystal_volume function, which handles all crystal systems.

Warning

This method requires manually installing CrysFML and building the fortran source located in src/fortran

TODO: Include PyCrysFML2008 libraries directly

add_phshifts(identifier: str, ipatt: int | None = None) None

Add phase-specific shift parameters to the PCR file.

This method enables the ‘phshift’ flag and initializes the phase-specific shift parameters (zero, sycos, sysin) with default values of zero. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

This adds the shifts section to the PCR file with default values. For multi-pattern PCR files, the shifts are added to the specific pattern. For single pattern PCR files, the shifts are added to the phase.

remove_phshifts(identifier: str, ipatt: int | None = None) None

Remove phase-specific shift parameters from the PCR file.

This method disables the ‘phshift’ flag and removes the phase-specific shift parameters section from the PCR file. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

This removes the shifts section from the PCR file. For multi-pattern PCR files, the shifts are removed from the specific pattern. For single pattern PCR files, the shifts are removed from the phase.

add_bvs(identifier: str) None

Add Bond Valence Sum (BVS) parameters to the PCR file.

This method enables the ‘jdi’ flag to 3 (enabling BVS calculations) and initializes the BVS parameters with default values.

Parameters:

identifier – Phase identifier

Note

This adds the bvs section to the PCR file with default values. The BVS parameters are initialized with values of 3.0 for both parameters, which are typically the minimum and maximum bond valence sum values to consider.

remove_bvs(identifier: str) None

Remove Bond Valence Sum (BVS) parameters from the PCR file.

This method disables the ‘jdi’ flag (setting it to 0) and removes the BVS parameters section from the PCR file, including any BVS ions information.

Parameters:

identifier – Phase identifier

Note

This removes both the bvs and bvs_ions sections from the PCR file.

get_init_oxistate(identifier: str) List[List[str]] | None

Load elements from a phase and obtain their oxidation states.

This method retrieves the elements present in a phase and determines their common oxidation states from the ATOM_LIST dictionary. It then formats these elements with their oxidation states for use in BVS calculations.

Parameters:

identifier – Phase identifier

Returns:

[cations, anions], where:
  • cations: List of cation elements with their oxidation states (e.g., “Fe+3”)

  • anions: List of anion elements with their oxidation states (e.g., “O-2”)

Returns None if no elements are found in the phase

Return type:

A list containing two lists

Note

This method uses the first (most common) oxidation state from the ATOM_LIST dictionary for each element.

TODO: Obtain most stable combinations for the Ewald sum

static format_element_strings(elem: str) str

Format element symbols to have the first letter capitalized.

This method ensures that element symbols are properly formatted with the first letter capitalized and the rest lowercase, which is the standard format for element symbols in the ATOM_LIST dictionary.

Parameters:

elem – Element symbol to format

Returns:

Properly formatted element symbol (e.g., “fe” -> “Fe”)

add_bvs_ions(identifier: str) None

Add Bond Valence Sum (BVS) ions information to the PCR file.

This method enables the BVS flag in the PCR file and adds the ions information (cations and anions) with their oxidation states. It also sets the correct parameter identifiers (‘spc’ tag) for each atom in the phase.

Parameters:

identifier – Phase identifier

Note

This method uses the get_init_oxistate method to determine the oxidation states of the elements in the phase. It then adds this information to the PCR file and updates the special positions for each atom.

remove_bvs_ions(identifier: str) None

Remove Bond Valence Sum (BVS) ions information from the PCR file.

This method disables the BVS flag in the PCR file and removes the ions information (cations and anions) from the phase. It also resets the ‘spc’ tag for each atom in the phase to zero.

Parameters:

identifier – Phase identifier

Note

This method removes the ‘bvs_ions’ section from the PCR file and calls set_zero_spc to reset the special positions for all atoms in the phase.

replace_bvs_cations(identifier: str, text: str) None

Replace the cations list in the Bond Valence Sum (BVS) ions information.

This method updates the cations list in the BVS ions information for a specific phase and updates the count of cations accordingly.

Parameters:
  • identifier – Phase identifier

  • text – Space-separated string of cation elements with their oxidation states (e.g., “Fe+3 Mn+2”)

Note

This method also updates the ‘nions’ count to reflect the new number of cations in the list.

replace_bvs_anions(identifier: str, text: str) None

Replace the anions list in the Bond Valence Sum (BVS) ions information.

This method updates the anions list in the BVS ions information for a specific phase and updates the count of anions accordingly.

Parameters:
  • identifier – Phase identifier

  • text – Space-separated string of anion elements with their oxidation states (e.g., “O-2 F-1”)

Note

This method also updates the ‘nions’ count to reflect the new number of anions in the list.

set_zero_spc(identifier: str) None

Reset the ‘spc’ tag for all atoms in a phase to zero.

This method sets the ‘spc’ parameter to 0 for all atomic sites in the specified phase. This is typically used when disabling BVS calculations.

Parameters:

identifier – Phase identifier

Note

The ‘spc’ parameter is used in BVS calculations to identify which atoms correspond to which ions in the BVS ions list.

set_correct_spc(identifier: str) None

Set the correct special positions (spc) for atoms in a phase for BVS calculations.

This method assigns appropriate ‘spc’ values to each atom in the phase based on its element type and the ions defined in the BVS ions list. The ‘spc’ value links each atom to a specific ion in the BVS ions list.

Parameters:

identifier – Phase identifier

Note

The method extracts element names from the cations and anions lists, then assigns each atom a ‘spc’ value that corresponds to its position in the ions list. If multiple atoms of the same element exist, they are assigned ‘spc’ values in a cyclic manner.

add_anisotropic_site(identifier: str, atom: str) None

Add anisotropic thermal parameters to an atomic site.

This method enables anisotropic thermal displacement parameters for a specific atomic site by setting the ‘nt’ parameter to 2 and initializing the anisotropic parameters (b11, b22, b33, b12, b13, b23) with default values.

Parameters:
  • identifier – Phase identifier

  • atom – Atomic site label

Note

The anisotropic thermal parameters are initialized with default values and their refinement flags (codes) are set to 0.0 (fixed).

remove_anisotropic_site(identifier: str, atom: str) None

Remove anisotropic thermal parameters from an atomic site.

This method disables anisotropic thermal displacement parameters for a specific atomic site by setting the ‘nt’ parameter to 0 and removing the anisotropic parameters from the PCR file.

Parameters:
  • identifier – Phase identifier

  • atom – Atomic site label

Note

This method removes both the anisotropic parameters and their refinement flags from the PCR file, reverting the site to isotropic thermal displacement.

get_profile_phase(identifier: str, tag: str, ipatt: int | None = None) int | float | None

Get the value of a profile parameter for a phase.

This method retrieves the value of a profile parameter identified by the tag for a specific phase. For multi-pattern PCR files, the pattern index can be specified. The method handles different types of parameters including strain parameters, size parameters, and Lorentzian strain parameters.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the profile parameter to retrieve

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The value of the specified profile parameter as a number (int or float), or None if the parameter is not found

Note

This method automatically selects the appropriate profile tags based on the job type (TOF or default) and handles special cases for strain and size anisotropy parameters.

edit_profile_phase(identifier: str, tag: str, val: int | float, ipatt: int | None = None) None

Edit the value of a profile parameter for a phase.

This method updates the value of a profile parameter identified by the tag for a specific phase. For multi-pattern PCR files, the pattern index can be specified. The method handles different types of parameters including strain parameters, size parameters, and Lorentzian strain parameters.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the profile parameter to edit

  • val – The new value to set for the profile parameter

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

This method automatically selects the appropriate profile tags based on the job type (TOF or default) and handles special cases for strain and size anisotropy parameters. If the parameter is not found, the method silently returns without making changes.

_get_strain_anisotropy(identifier: str, tag: str, ipatt: int | None = None) float | None

Get the value of a strain anisotropy parameter for a phase.

This method retrieves the value of a strain anisotropy parameter identified by the tag for a specific phase. For multi-pattern PCR files, the pattern index can be specified. The method handles different strain models based on the crystal symmetry.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the strain parameter to retrieve

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The value of the specified strain parameter as a float, or None if the parameter is not found or if strain anisotropy is not enabled

Note

This method is used internally by get_profile_phase and should not be called directly. The available strain parameters depend on the strain model, which is determined by the crystal symmetry and the ‘straintag’ parameter.

_edit_strain_anisotropy(identifier: str, tag: str, val: int | float, ipatt: int | None = None) None

Edit the value of a strain anisotropy parameter for a phase.

This method updates the value of a strain anisotropy parameter identified by the tag for a specific phase. For multi-pattern PCR files, the pattern index can be specified. The method handles different strain models based on the crystal symmetry.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the strain parameter to edit

  • val – The new value to set for the strain parameter

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

This method is used internally by edit_profile_phase and should not be called directly. The available strain parameters depend on the strain model, which is determined by the crystal symmetry and the ‘straintag’ parameter. If the parameter is not found or if strain anisotropy is not enabled, the method silently returns without making changes.

_get_size_anisotropy(identifier: str, tag: str, ipatt: int | None = None) float | None

Get the value of a size anisotropy parameter for a phase.

This method retrieves the value of a size anisotropy parameter identified by the tag for a specific phase. For multi-pattern PCR files, the pattern index can be specified. The method handles different size models based on the crystal symmetry.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the size parameter to retrieve

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The value of the specified size parameter as a float, or None if the parameter is not found or if size anisotropy is not enabled

Note

This method is used internally by get_profile_phase and should not be called directly. The available size parameters depend on the size model, which is determined by the crystal symmetry and the ‘sizetag’ parameter.

_edit_size_anisotropy(identifier: str, tag: str, val: int | float, ipatt: int | None = None) None

Edit the value of a size anisotropy parameter for a phase.

This method updates the value of a size anisotropy parameter identified by the tag for a specific phase. For multi-pattern PCR files, the pattern index can be specified. The method handles different size models based on the crystal symmetry.

Parameters:
  • identifier – Phase identifier

  • tag – The identifier of the size parameter to edit

  • val – The new value to set for the size parameter

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

This method is used internally by edit_profile_phase and should not be called directly. The available size parameters depend on the size model, which is determined by the crystal symmetry and the ‘sizetag’ parameter. If the parameter is not found or if size anisotropy is not enabled, the method silently returns without making changes.

remove_size_model(identifier: str, ipatt: int | None = None) None

Remove the size anisotropy model for a phase.

This method disables the size anisotropy model for a specific phase by setting the ‘sizetag’ parameter to 0 and removing the size harmonics parameters from the PCR file. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

This method removes all size harmonics parameters from the PCR file, effectively disabling size anisotropy for the phase.

add_size_model(identifier: str, ipatt: int | None = None) None

Add a size anisotropy model for a phase.

This method enables the size anisotropy model for a specific phase by setting the ‘sizetag’ parameter to a value appropriate for the crystal symmetry and initializing the size harmonics parameters with default values of zero. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

The method automatically selects the appropriate size model based on the Laue class of the crystal. Different crystal symmetries require different sets of spherical harmonics parameters to describe the size anisotropy.

The size model is initialized with all parameters set to zero, which corresponds to isotropic size broadening. The parameters can be modified later using the edit_profile_phase method.

Warning

This method requires manually installing CrysFML and building the fortran source located in src/fortran

TODO: Include PyCrysFML2008 libraries directly

remove_strain_model(identifier: str, ipatt: int | None = None) None

Remove the strain anisotropy model for a phase.

This method disables the strain anisotropy model for a specific phase by setting the ‘straintag’ parameter to 0, the ‘str’ flag to 0, and removing the strain harmonics parameters from the PCR file. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

This method removes all strain harmonics parameters and the Lorentzian strain parameter from the PCR file, effectively disabling strain anisotropy for the phase.

add_strain_model(identifier: str, ipatt: int | None = None) None

Add a strain anisotropy model for a phase.

This method enables the strain anisotropy model for a specific phase by setting the ‘str’ flag to 1, setting the ‘straintag’ parameter to a value appropriate for the crystal symmetry, and initializing the strain harmonics parameters with default values of zero. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

The method automatically selects the appropriate strain model based on the Laue class of the crystal. Different crystal symmetries require different sets of strain parameters to describe the strain anisotropy.

The strain model is initialized with all parameters set to zero, which corresponds to isotropic strain broadening. The parameters can be modified later using the edit_profile_phase method.

The method also initializes the Lorentzian strain parameter with a default value of zero.

Warning

This method requires manually installing CrysFML and building the fortran source located in src/fortran

TODO: Include PyCrysFML2008 libraries directly

get_laue(identifier: str, ipatt: int | None = None) str

Get the Laue class of a phase.

This method determines the Laue class of a phase based on its Hermann-Mauguin symbol and cell parameters. The Laue class is a classification of crystal symmetry based on the point group of the crystal.

Parameters:
  • identifier – Phase identifier

  • ipatt – Optional pattern index for multi-pattern PCR files

Returns:

The Laue class as a string (e.g., ‘mmm’, ‘-3m1’, ‘m-3m’)

Note

This method handles special cases for trigonal and monoclinic systems:

  • For trigonal systems, it distinguishes between rhombohedral (‘-3R’, ‘-3mR’) and hexagonal (‘-3’, ‘-3m1’, ‘-31m’) settings.

  • For monoclinic systems, it determines the unique axis (‘12/m1’, ‘112/m’).

The Laue class is used to determine the appropriate strain and size models for the phase.

Warning

This method requires manually installing CrysFML and building the fortran source located in src/fortran

TODO: Include PyCrysFML2008 libraries directly

count_site_phase(identifier: str) int

Count the number of atomic sites in a phase.

Parameters:

identifier – Phase identifier

Returns:

The number of atomic sites in the phase

get_site_phase(identifier: str, atom: str, tag: str) float | str

Get the value of a parameter for an atomic site in a phase.

Parameters:
  • identifier – Phase identifier

  • atom – Atomic site label

  • tag – The identifier of the parameter to retrieve (e.g., ‘x’, ‘y’, ‘z’, ‘biso’, ‘occ’)

Returns:

The value of the specified parameter as a number (float) or string

Note

The method automatically converts numeric values to float using the fast_real function. Non-numeric values (e.g., element symbols) are returned as strings.

edit_site_phase(identifier: str, atom: str, val: int | float | str, tag: str) None

Edit the value of a parameter for an atomic site in a phase.

Parameters:
  • identifier – Phase identifier

  • atom – Atomic site label

  • val – The new value to set for the parameter

  • tag – The identifier of the parameter to edit (e.g., ‘x’, ‘y’, ‘z’, ‘biso’, ‘occ’)

Note

The method automatically converts the value to a string before storing it in the PCR file.

add_site_phase(identifier: str, atom: str) None

Add a new atomic site to a phase.

This method adds a new atomic site with default parameters to the specified phase. The site is initialized with zero coordinates, zero thermal parameter, and full occupancy. Anisotropic thermal parameters are also initialized with default values.

Parameters:
  • identifier – Phase identifier

  • atom – Label for the new atomic site

Note

The method automatically updates the ‘nat’ flag in the PCR file to reflect the new number of atomic sites in the phase.

remove_site_phase(identifier: str, atom: str) None

Remove an atomic site from a phase.

This method removes the specified atomic site from the phase and updates the ‘nat’ flag to reflect the new number of atomic sites.

Parameters:
  • identifier – Phase identifier

  • atom – Label of the atomic site to remove

Note

The method does not reindex the remaining atomic sites, so there may be gaps in the atom indices after removal. Use reformat_atom_keys to fix this.

replace_global_vary(vary: List[str] | str, ipatt: int | None = None) None

Replace the global VARY command in the PCR file.

This method updates the global VARY command, which specifies which parameters should be refined during the Rietveld refinement. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • vary – Either a list of parameter names to vary, or a complete VARY command string

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

If a list is provided, the method automatically formats it as a VARY command. If a string is provided, it is used as-is (should start with “VARY”).

replace_global_fix(fix: List[str] | str, ipatt: int | None = None) None

Replace the global FIX command in the PCR file.

This method updates the global FIX command, which specifies which parameters should be fixed (not refined) during the Rietveld refinement. For multi-pattern PCR files, the pattern index can be specified.

Parameters:
  • fix – Either a list of parameter names to fix, or a complete FIX command string

  • ipatt – Optional pattern index for multi-pattern PCR files

Note

If a list is provided, the method automatically formats it as a FIX command. If a string is provided, it is used as-is (should start with “FIX”).

replace_phase_commands(identifier: str, commands: str) None

Replace a phase-specific COMMANDS in the PCR file.

This method updates the COMMANDS section for a phase

Parameters:
  • identifier – Phase identifier

  • commands – Complete COMMAND string

add_phase_commands(identifier: str, commands: str) None

Add a new phase-specific COMMAND to the PCR file.

Parameters:
  • identifier – Phase identifier

  • commands – Complete COMMAND string to append to the existing list

clear_fix_vary_commands() None

Remove all phase dependent and global COMMANDS from the PCR file.

Note

This is useful when you want to start with a clean slate for refinement strategy, removing all previous refinement instructions.

get_limits(ire: int) List[str]

Get the refinement limits for a specific limit entry.

This method retrieves the refinement limits (min/max constraints) for a specific limit entry in the PCR file. Limits are used to constrain parameter values during refinement.

Parameters:

ire – Index of the limit entry to retrieve

Returns:

List of strings representing the limit entry

count_limits() int

Count the number of refinement limit entries in the PCR file.

This method counts how many limit entries are defined in the PCR file. Limits are used to constrain parameter values during refinement.

Returns:

Number of limit entries in the PCR file

add_limits(vals: List[str]) None

Add a new refinement limit entry to the PCR file.

This method adds a new limit entry to constrain parameter values during refinement and updates the ‘nre’ flag to reflect the new number of limit entries.

Parameters:

vals – List of strings representing the limit entry to add

Note

The format of the limit entry depends on the parameter being constrained. Typically, it includes the parameter name, minimum value, and maximum value.

replace_limits(ire: int, vals: str) None

Replace an existing refinement limit entry in the PCR file.

This method updates a specific limit entry with new values.

Parameters:
  • ire – Index of the limit entry to replace

  • vals – Space-separated string containing the new limit values

Note

The string is automatically split into a list before storing in the PCR file. The format of the limit entry depends on the parameter being constrained.

remove_limits() None

Remove all refinement limit entries from the PCR file.

This method removes all limit entries from the PCR file and resets the ‘nre’ flag to 0, effectively removing all parameter constraints from the refinement.

remove_limits_one() None

Remove the last refinement limit entry from the PCR file.

This method removes only the last limit entry from the PCR file and decrements the ‘nre’ flag accordingly. This is useful when you want to remove just the most recently added constraint while keeping others.

get_restraint(ili: int) dict

Get a specific restraint entry from the PCR file.

This method retrieves a restraint entry from the PCR file. Restraints are used to add soft constraints to the refinement, such as bond distances or angles.

Parameters:

ili – Index of the restraint entry to retrieve

Returns:

Dictionary containing the restraint values and coefficients

count_restraint() int

Count the number of restraint entries in the PCR file.

This method counts how many restraint entries are defined in the PCR file. Restraints are used to add soft constraints to the refinement, such as bond distances or angles.

Returns:

Number of restraint entries in the PCR file

add_restraint(vals: List[List[str]]) None

Add a new restraint entry to the PCR file.

This method adds a new restraint entry to constrain structural parameters during refinement and updates the ‘nli’ flag to reflect the new number of restraint entries.

Parameters:

vals – List containing two lists of strings: - vals[0]: Values for the restraint (parameter identifiers) - vals[1]: Coefficients for the restraint (target values and weights)

Note

Restraints are soft constraints that penalize deviations from target values during refinement, such as bond distances, angles, or other geometric parameters.

replace_restraint_vals(ili: int, vals: str) None

Replace the values of a specific restraint entry in the PCR file.

This method updates the parameter identifiers for a specific restraint entry.

Parameters:
  • ili – Index of the restraint entry to modify

  • vals – Space-separated string containing the new parameter identifiers

Note

The string is automatically split into a list before storing in the PCR file.

replace_restraint_coeff(ili: int, coeff: str) None

Replace the coefficients of a specific restraint entry in the PCR file.

This method updates the target values and weights for a specific restraint entry.

Parameters:
  • ili – Index of the restraint entry to modify

  • coeff – Space-separated string containing the new coefficients (target values and weights)

Note

The string is automatically split into a list before storing in the PCR file. Coefficients typically include target values for the restrained parameters and their associated weights (importance in the refinement).

remove_restraint() None

Remove all restraint entries from the PCR file.

This method removes all restraint entries from the PCR file and resets the ‘nli’ flag to 0, effectively removing all soft constraints from the refinement.

remove_restraint_one() None

Remove the last restraint entry from the PCR file.

This method removes only the last restraint entry from the PCR file and decrements the ‘nli’ flag accordingly. This is useful when you want to remove just the most recently added restraint while keeping others.

read_hm_symbol(identifier: str) str

Get the Hermann-Mauguin symbol for a specific phase.

This method retrieves the space group symbol in Hermann-Mauguin notation for the specified phase from the PCR file.

Parameters:

identifier – Phase identifier

Returns:

The Hermann-Mauguin symbol as a string

check_phase_exists(identifier: str) bool

Check if a phase with the given identifier exists in the PCR file.

This method verifies whether a phase with the specified identifier is present in the PCR file.

Parameters:

identifier – Phase identifier to check

Returns:

True if the phase exists, False otherwise

remove_phase(identifier: str) None

Remove a phase from the PCR file.

This method removes a phase with the specified identifier from the PCR file, updates the phase numbering, and decrements the global phase count.

Parameters:

identifier – Phase identifier to remove

get_phase(identifier: str) dict

Get the data for a specific phase from the PCR file.

This method retrieves all data associated with a specific phase identified by its identifier from the PCR file.

Parameters:

identifier – Phase identifier to retrieve

Returns:

Dictionary containing all data for the specified phase

add_phase(phase: dict) None

Add a new phase to the PCR file.

This method adds a new phase to the PCR file using the provided phase data dictionary and increments the global phase count.

Parameters:

phase – Dictionary containing the phase data to add, including all necessary parameters such as name, space group, atomic positions, and profile parameters

reformat_phase_keys() None

Reformat phase dictionary keys to ensure sequential numbering.

Renames phase dictionary keys to go in increments of 1 after removing phases.

reformat_atom_keys(identifier: str) None

Reformat atom dictionary keys to ensure sequential numbering.

Parameters:

identifier – Phase identifier whose atom keys should be reformatted

class fpfunctions.app_io.MicIO(path: str, jobid: str)

Bases: object

Class for reading MIC (Microstructural Information) files.

This class provides methods for reading and parsing MIC files generated by FullProf, which contain information about peak shapes, crystallite sizes, and microstrains.

path

Path to the directory containing the MIC file

jobid

Job identifier (filename without extension)

__init__(path: str, jobid: str) None

Initialize the MicIO object.

Parameters:
  • path – Path to the directory containing the MIC file

  • jobid – Job identifier (filename without extension)

read_fromfile(iphas: int, ipatt: int | None = None) List[numpy.typing.NDArray.numpy.float64 | Tuple[float, float] | None]

Read microstructural information from a MIC file.

Parameters:
  • iphas – Phase index

  • ipatt – Optional pattern index for multi-pattern refinements

Returns:

  • FWHM information as a NumPy array

  • Average crystallite size as a tuple (value, standard deviation) or None

  • Average microstrain as a tuple (value, standard deviation) or None

Return type:

List containing

class fpfunctions.app_io.SumIO(path: str, jobid: str | None = None)

Bases: object

Class for reading SUM (Summary) files generated by FullProf.

This class provides methods for reading and parsing SUM files, which contain refinement results including cell parameters, reliability factors, and phase fractions.

path

Path to the directory containing the SUM file

jobid

Job identifier (filename without extension)

__init__(path: str, jobid: str | None = None) None

Initialize the SumIO object.

Parameters:
  • path – Path to the directory containing the SUM file

  • jobid – Job identifier (filename without extension). If None, the basename of the path is used.

parse_all_info(pcr: PcrIO) dict | None

Parse all information from a SUM file.

This method extracts all refinement results from a FullProf SUM file, including cell parameters, atomic positions, profile parameters, reliability factors, and phase fractions.

Parameters:

pcr – PcrIO object containing PCR file information

Returns:

Dictionary containing all parsed information, or None if parsing fails

parse_cell_params(pcr: PcrIO, identifiers: List[str]) dict | None

Extract cell parameters from the parsed SUM file.

This method retrieves the cell parameters (a, b, c, alpha, beta, gamma) for each phase and pattern from the parsed SUM file data.

Parameters:
  • pcr – PcrIO object containing PCR file information

  • identifiers – List of phase identifiers to extract parameters for

Returns:

Dictionary containing cell parameters organized by pattern and phase, or None if parsing fails

parse_rwp(pcr: PcrIO) dict | None

Extract Rwp values from the parsed SUM file.

This method retrieves the weighted profile R-factor (Rwp) values for each pattern from the parsed SUM file data.

Parameters:

pcr – PcrIO object containing PCR file information

Returns:

Dictionary mapping pattern indices to Rwp values, or None if parsing fails

parse_chi2(pcr: PcrIO) dict | None

Extract Chi² values from the parsed SUM file.

This method retrieves the goodness-of-fit (Chi²) values for each pattern from the parsed SUM file data.

Parameters:

pcr – PcrIO object containing PCR file information

Returns:

Dictionary mapping pattern indices to Chi² values, or None if parsing fails

parse_volume_fractions(pcr: PcrIO, identifiers: List[str]) dict | None

Extract weight fractions from the parsed SUM file.

This method retrieves the weight fraction values for each phase and pattern from the parsed SUM file data.

Parameters:
  • pcr – PcrIO object containing PCR file information

  • identifiers – List of phase identifiers to extract fractions for

Returns:

Dictionary containing weight fractions organized by pattern and phase, or None if parsing fails

parse_r_bragg(pcr: PcrIO, identifiers: List[str]) dict | None

Extract R-Bragg factors from the parsed SUM file.

This method retrieves the Bragg R-factors for each phase and pattern from the parsed SUM file data.

Parameters:
  • pcr – PcrIO object containing PCR file information

  • identifiers – List of phase identifiers to extract R-factors for

Returns:

Dictionary containing R-Bragg factors organized by pattern and phase, or None if parsing fails

class fpfunctions.app_io.PrfIO(path: str, jobid: str)

Bases: object

Class for reading PRF (Profile) files generated by FullProf.

This class provides methods for reading and parsing PRF files, which contain calculated and observed diffraction patterns, reflection positions, and other information from FullProf refinements.

patterns

NumPy array containing the diffraction pattern data

nphase

Number of phases in the refinement

reflections

DataFrame containing reflection information (h, k, l, position)

excluded

NumPy array containing excluded regions

zerovalue

Zero shift value

jobpath

Path to the directory containing the PRF file

jobid

Job identifier (filename without extension)

__init__(path: str, jobid: str) None

Initialize the PrfIO object.

Parameters:
  • path – Path to the directory containing the PRF file

  • jobid – Job identifier (filename without extension)

read_data(ipatt: int | None = None) None

Read and parse data from a PRF file.

This method reads the PRF file, extracting diffraction pattern data, reflection positions, excluded regions, and other information.

Parameters:

ipatt – Optional pattern index for multi-pattern refinements