API Reference#

Most important functions#

sqsgenerator.public.sqs_optimize(settings: Union[AttrDict, Dict], process: bool = True, minimal: bool = True, similar: bool = False, log_level: str = 'warning', fields: Tuple[str, ...] = ('configuration', 'parameters', 'objective'), make_structures: bool = False, structure_format: str = 'default', pass_structure: bool = False) Tuple[Dict[int, Dict[str, Any]], Dict[int, Union[float, List[float]]]][source]#

This function allows to simply generate SQS structures

Performs a SQS optimization loop. This function is meant for using sqsgenerator through Python. Prefer this function over pair_sqs_iteration(). It combines the functionalities of several low-level utility function.

  1. Generate default values for {settings} (process_settings())

  2. Execute the actual SQS optimization loop (pair_sqs_iteration())

  3. Process, convert the results (make_result_document())

  4. Build the structures from the optimization results (extract_structures())

An example output might look like the following:

{
    654984: {
        'configuration': ['Re', 'W', 'Re', 'W', 'Re', 'W', 'Re', 'W', 'Re', 'W', 'Re', 'W', 'Re', 'W']
        'objective': 0.0,
        # only present if make_structures=True
        # Atoms object if structure_format='ase'
        'structure': Atoms(symbols='ReWReWReWReWReWReWReW', pbc=True, cell=[6.33, 6.33, 6.33])
    }
}
Parameters:
  • settings (AttrDict or Dict) – the settings used for the SQS optimization

  • process (bool) – process the input {settings} dictionary (default is True)

  • minimal (bool) – Include only configurations with minimum objective function in the results (default is True)

  • similar (bool) – If the minimum objective is degenerate include also results with same parameters but different configuration (default is False)

  • log_level (str) – set’s the log level for the core C++ extension. Possible fields are “trace”, “debug”, “info”, “warning” and “error” (default is 'warning')

  • fields (Tuple[str, ...]) – output fields included in the result document. Possible fields are “configuration”, “parameters”, “objective” and “parameters” (default is ('configuration',))

  • make_structures (bool) – build structure objects from the optimization results (default is False

  • structure_format (str) –

    if {make_structures} was set to True it specifies the format of the build structures (default is 'default')

    • default”: Structure

    • pymatgenpymatgen.core.Structure

    • ase”: ase.atoms.Atoms

    • pyiron”: pyiron_atomistics.atomistics.structure.Atoms

Returns:

a dictionary with the specified fields as well as timing information. The keys of the result dictionary are the permutation ranks of the generated configuration. :param pass_structure: construct a Structure object and pass it to the callback. If True the callback exhibits a signature of cb(iteration: int, structure: :py:class:`Structure`, parameters :py:class:`SQSResult`, rank_id: int, thread_id: int). If set to False the callbacks signature is cb(iteration: int, parameters :py:class:`SQSResult`, rank_id: int, thread_id: int)

Return type:

Tuple[Dict[int, Dict[str, Any]], Dict[int, Union[float, List[float]]]]

sqsgenerator.public.sqs_analyse(structures: Iterable[Structure], settings: Optional[Union[AttrDict, Dict]] = None, process: bool = True, fields: Tuple[str, ...] = ('configuration', 'parameters', 'objective'), structure_format: str = 'default', append_structures: bool = False) Dict[int, Dict[str, Any]][source]#

Uses the given settings {settings} and an iterable of Structure() and compute the short-range-order parameters, objective function. By default the {fields} = (‘configuration’, ‘parameters’, ‘objective’) are included.

Parameters:
  • structures (Iterable[Union[Structure, :py:class`ase.atoms.Atoms`, pymatgen.core.Structure]]) – an iterable of structures to analyse

  • settings (AttrDict or Dict) – the settings used for the SQS optimization

  • process (bool) – process the input {settings} dictionary (default is True)

  • fields (Tuple[str, ...]) – output fields included in the result document. Possible fields are “configuration”, “parameters”, “objective” and “parameters” (default is ('configuration', 'parameters', 'objective'))

  • structure_format (str) –

    the input format of the items in {structures} (default is 'default')

    • default”: Structure

    • pymatgenpymatgen.core.Structure

    • ase”: ase.atoms.Atoms

    • pyiron”: pyiron_atomistics.atomistics.structure.Atoms

  • append_structures (bool) – append the initial {structures} to the analysed results (default is False)

Returns:

a dictionary with the specified fields as well as timing information. The keys of the result dictionary are the permutation ranks of the {structures}.

Return type:

Dict[int, Dict[str, Any]]

Helper functions#

sqsgenerator.public.process_settings(settings: AttrDict, params: Optional[Set[str]] = None, ignore: Iterable[str] = ()) AttrDict[source]#

Process an dict-like input parameters, according to the rules specified in the Input parameter documentation. This function should be used for processing user input. Therefore, exports the parser functions defined in sqsgenerator.settings.readers. To specify a specify subset of parameters the {params} argument is used. To {ignore} specific parameters pass a list of parameter names

Parameters:
  • settings (AttrDict) – the dict-like user configuration

  • params (Optional[Set, None]) – If specified only the subset of {params} is processed (default is None)

  • ignore (Iterable[str]) – a list/iterable of params to ignore (default is ())

Returns:

the processed settings dictionary

Return type:

AttrDict

sqsgenerator.public.read_settings_file(path: str, format: str = 'yaml') AttrDict[source]#

Reads a file expecting {format} as the file type. This method does not process the input paramters, but rather just reads, them from. To obtain default values for all parameters use process_settings()

Parameters:
  • path (str) – the file path

  • format (str) – the input file-type. Possible formats are yaml, json and pickle (default is 'yaml')

Returns:

the parsed settings

Return type:

AttrDict

sqsgenerator.public.export_structures(structures: ~typing.Dict[~typing.Any, ~typing.Any], format: str = 'cif', output_file: str = 'sqs.result', writer: ~typing.Union[~sqsgenerator.compat.Feature, str] = 'ase', compress: ~typing.Optional[str] = None, functor: ~typing.Callable[[~typing.Any], str] = <function identity>) NoReturn[source]#

Writes structures into files. The filename is specified by the keys of {structure} argument. The structures stored in the values will be written using the {writer} backend in {format}. If compress is specified the structures will be dumped into an archive with name {output_file}. The file-extension is chosen automatically.

Parameters:
  • structures (dict[Any, Structure]) – a mapping of filenames and Structures

  • format – output file format (default is 'cif')

  • output_file (str) – the prefix of the output archive name. File extension is chosen automatically. If {compress} is None this option is ignored (default is 'sqs.result')

  • writer (str) – the writer backend (default is 'ase')

  • compress (str or None) – compression algorithm ('zip', 'gz', 'bz2' or 'xz') used to store the structure files. If None the structures are written to plain files (default is None)

  • functor (Callable[[Any], Structure]) – a callable which maps the values of {structures} on a Structure (default is identity = lambda x: x)

sqsgenerator.public.make_rank(struct: Structure, rank: int, configuration: Optional[Iterable[str]] = None, which: Optional[Iterable[int]] = None) Structure[source]#

Uses the lattice and positions from {struct} and generates the {rank}-th permutation (in lexicographical order) of {configuration} and creates a new structure with it. If {which} is given, the selected lattices positions are used, therefore the length of {configuration} must match the length of {which}

Parameters:
  • struct (Structure) – the basis structure from which the new structure will be created

  • rank (int) – the index of the permutation sequence

  • configuration (Optional[Iterable[str]]) – the species sequence from which the {rank}-th permutation sequence. Use this parameter when you want to create a rank and simultaneously want to distribute new atomic species (default is None)

  • which (Optional[Iterable[int]]) – the indices of the lattice positions to choose (default is None)

Raises:
  • IndexError – if the length of {which} does not match the length of {configuration}

  • ValueError – if the rank is less than 1 or greater than the number of total_permutations()

Returns:

the structure with {rank}-th permutation sequence as configuration

Return type:

Structure

sqsgenerator.public.total_permutations(struct: Structure, which: Optional[Iterable[int]] = None) int[source]#

Compute the total number of total permutations, by looking at the configuration of {struct}. The number of of permutations are given by the multinomial coefficient. Let \(N_1, N_2, \ldots, N_m\) the number of the atoms of the \(m^{\text{th}}\) species. Therefore, one can generate

\[N_{\text{perms}} = \dfrac{N!}{\prod_m^M N_m} \quad \text{where} \quad \sum_m^M N_m = N\]

permutations in total

Parameters:
  • struct (Structure) – the structure with the configuration to calculate the number of total permutations

  • which (Optional[Iterable[int]]) – the indices of the lattice positions to choose (default is None)

Returns:

the rank of the structure of the sub-lattice selected by {which}

Return type:

int

sqsgenerator.public.rank_structure(struct: Structure, which: Optional[Iterable[int]] = None) int[source]#

Computes the index (in lexicographical order) of the configuration sequence. If {which} is specified only those sites are selected to compute the permutation rank

Parameters:
  • struct (Structure) – the structure which carries the configuration sequence

  • which (Optional[Iterable[int]]) – the indices of the lattice positions to choose (default is None)

Returns:

the index of the configuration sequence

Return type:

int

sqsgenerator.tools.sqsgen_minimize_multiple(it: Iterable[Dict[str, Any]], chunk_size: int = 1)[source]#

Runs multiple sqs_optimize() runs asynchronously, and merges the results. It will carry out an optimization for each input settings yielded from {it}. It selects only those results with the minimal objective function. This is useful when varying the cell shape

Parameters:
  • it (Iterable[Dict[str, Any]]) – input generator that produces settings for sqs_optimize_async()

  • chunk_size (int) – whether to split {it} into chunks of size {n}. Use this in combination when setting threads_per_rank manually. For values > 1 {it} will be split (default is 1)

Returns:

the best objective and the structures which minimize the objective function

Return type:

Tuple[float, List[sqsgenerator.public.structure]]

Conversion functions#

sqsgenerator.public.to_ase_atoms(structure: Structure)[source]#

Convert structure {structure} to a ase.Atoms object

Parameters:

structure (Structure) – the structure to convert

Returns:

the ase.Atoms object

Return type:

ase.Atoms

sqsgenerator.public.from_ase_atoms(atoms) Structure[source]#

Convert the ase.Atoms {structure} object to a sqsgenerator.core.Structure object

Parameters:

atoms (ase.Atoms) – the structure to convert

Returns:

the structure object

Return type:

Structure

sqsgenerator.public.to_pymatgen_structure(structure: Structure)[source]#

Convert structure {structure} to a pymatgen.core.Structure object

Parameters:

structure (Structure) – the structure to convert

Returns:

the pymatgen.core.Structure object

Return type:

pymatgen.core.Structure

sqsgenerator.public.from_pymatgen_structure(structure) Structure[source]#

Convert the pymatgen.core.Structure {structure} object to a sqsgenerator.core.Structure object

Parameters:

structure (pymatgen.core.Structure) – the structure to convert

Returns:

the structure object

Return type:

Structure

low-level API reference#

class sqsgenerator.public.IterationMode[source]#

The IterationMode is a simple enum class which indicates how sqsgenerator should sample the configurational space

random#

Instructs the program to use a Monte-Carlo based sampling of the configurational space

systematic#

Will cause sqsgenerator to systematically sample the configurational space. This setting is recommended only for relatively “small” structures. We strongly encourage you to use:

sqsgen compute total-permutations

to obtain the potential number of iterations needed. To roughly estimate the time on your local machine you can use:

sqsgen compute estimated-time
class sqsgenerator.public.Structure(lattice: ndarray, frac_coords: ndarray, symbols: List[str], pbc: Tuple[bool, bool, bool] = (True, True, True))[source]#

Structure class used to store structural information. This class is used by the core extension and is a wrapper around the extension internal sqsgenerator.core.core.Structure class. The class is designed to be array like, therefore it does not provide any setter functions. Internally this class uses fractional coordinates to represent structural information.

__init__(self, lattice: ndarray, frac_coords: ndarray, symbols: List[str], pbc: Tuple[bool, bool, bool] = (True, True, True))#

Constructs a new structure from raw data

Parameters:
  • lattice (np.ndarray) – the (3x3) lattice matrix. The three rows are interpreted as the lattice vectors a, b and c.

  • frac_coords (np.ndarray) – the fractional coordinates of the lattice positions as (3xN) array. Each row will be treated as a lattice position

  • symbols (List[str]) – a list of strings of length N specifying the atomic species which occupy the lattice positions

  • pbc (Tuple[bool, bool, bool]) – the coordinate axes for which periodic boundary conditions should be applied. Do not pass a value here. This feature is not yet implemented (default is (True, True, True))

Raises:

ValueError – if length of {frac_coords} and length of {symbols} do not match

property num_atoms#

The number of atoms in the structure

Returns:

the number of atoms

Return type:

int

property distance_matrix#

The distance matrix with dimensions {num_atoms} times {num_atoms}

Returns:

the distance matrix

Return type:

np.ndarray

property distance_vecs#

The distance vectors taking into account periodic boundary conditions between the lattice positions. The distance matrix is computed from this property.

Returns:

the vector of of shortest distances

Return type:

np.ndarray

property frac_coords#

A np.ndarray storing the position of the lattice position in fractional space.

Returns:

the fractional coordinates

Return type:

np.ndarray

property num_unique_species: int#

The number of unique elements in the structure object

Returns:

the number of elements

Return type:

int

property numbers: ndarray#

The ordinal numbers of the atoms sitting on the lattice positions

Returns:

array of ordinal numbers

Return type:

numpy.ndarray

slice_with_species(species: Iterable[str], which: Optional[Iterable[int]] = None)[source]#

Creates a new structure containing the lattice positions specified by {which}. The new structure is occupied by the atomic elements specified in {species}. In case {which} is None all lattice positions are assumed to be occupied with a new {species}. The new structure will only contain lattice positions specified in {which}.

Parameters:
  • species (Iterable[str]) – the atomic species specified by their symbols

  • which (Optional[Iterable[int]]) – the indices of the lattice positions to choose (default is None)

Returns:

the (subset) structure with new species

Return type:

Structure

Raises:

ValueError – if length of which is < 1 or length of {which} and {species} does not match

sorted()[source]#

Creates a new structure, where the lattice positions are ordered by the ordinal numbers of the occupying species

Returns:

the sorted Structure

Return type:

Structure

property symbols: ndarray#

A numpy.ndarray storing the symbols of the atomic species. E.g “Fe”, “Cr”, “Ni

Returns:

the array of symbols

Return type:

numpy.ndarray

to_dict() dict[source]#

Serializes the object into JSON/YAML serializable dictionary

Returns:

the JSON/YAML serializable dictionary

Return type:

Dict[str, Any]

property unique_species: Set[str]#

A set of symbols of the occurring species

Returns:

a set containing the symbol of the occurring species

Return type:

Set[str]

with_species(species, which=None)[source]#

Creates a new structure containing the lattice positions specified by {which}. The new structure is occupied by the atomic elements specified in {species}. In case {which} is None all lattice positions are assumed to be occupied with a new {species}. The new structure will only all lattice positions of the current structure, while on the positions specified by {which} are occupied with {species}

Parameters:
  • species (Iterable[str]) – the atomic species specified by their symbols

  • which (Optional[Iterable[int]]) – the indices of the lattice positions to choose (default is None)

Returns:

the structure with new species

Return type:

Structure

Raises:

ValueError – if length of which is < 1 or length of {which} and {species} does not match

sqsgenerator.public.make_supercell(structure: Structure, sa: int = 1, sb: int = 1, sc: int = 1) Structure[source]#

Creates a supercell of structure, which is repeated {sa}, {sb} and {sc} times

Parameters:
  • structure (Structure) – the structure to replicate

  • sa (int) – number of repetitions in directions of the first lattice vector (default is 1)

  • sb (int) – number of repetitions in directions of the second lattice vector (default is 1)

  • sc (int) – number of repetitions in directions of the third lattice vector (default is 1)

Returns:

the supercell structure

Return type:

Structure

sqsgenerator.public.make_result_document(settings: AttrDict, sqs_results: Iterable[SQSResult], timings: Optional[Dict[int, List[float]]] = None, fields: Tuple[str, ...] = ('configuration',)) AttrDict[source]#

Converts the sqsgenerator.core.SQSResults obtained from pair_sqs_results into a JSON/YAML serializable dictionary

Parameters:
  • settings (AttrDict) – the settings dictionary used to compute {sqs_results}

  • sqs_results (iterable of sqsgenerator.core.SQSResults) – the sqsgenerator.core.SQSResults calculated by pair_sqs_results

  • timings (Dict[int, float]) – a dictionary of thread timing information (default is None)

  • fields (Tuple[str, ...]) – the fields to include in the document. Can be either configuration, objective and/or parameters (default is ('configuration',))

Returns:

the JSON/YAML serializable document

Return type:

AttrDict

sqsgenerator.public.pair_sqs_iteration(settings: AttrDict, minimal: bool = True, similar: bool = False, log_level: str = 'warning', pass_structure: bool = False) Tuple[Iterable[SQSResult], Dict[int, List[float]]][source]#

Performs an SQS iteration using the {settings} configuration

Parameters:
  • settings (AttrDict) – the dict-like settings used for the iteration. Please refer to the Input parameter for further information

  • minimal (bool) – if the result vector contains sqsgenerator.core.SQSResult objects with different objective values, select only those with minimal value of the objective function (default is True)

  • similar (bool) – in case the result vector contains more than one structure with minimal objective, include also degenerate solutions (default is False)

  • log_level (str) – the log level of the core extension. Valid values are “trace”, “debug”, “info”, “warning” and “error”. Please use “trace” when you encounter a bug in the core extension and report an issue (default is "warning")

  • pass_structure (bool) – construct a Structure object and pass it to the callback. If True the callback exhibits a signature of cb(iteration: int, structure: :py:class:`Structure`, parameters :py:class:`SQSResult`, rank_id: int, thread_id: int). If set to False the callbacks signature is cb(iteration: int, parameters :py:class:`SQSResult`, rank_id: int, thread_id: int)

Returns:

the minimal configuration and the corresponding Short-range-order parameters as well as timing information

Return type:

Tuple[Iterable[SQSResult], Dict[int, float]]

sqsgenerator.public.extract_structures(results: AttrDict, base_structure: Optional[Structure] = None) Dict[int, Structure][source]#

Parses a dictionary of results and replaces the generated configuration with the actual structure

Parameters:
  • results (AttrDict) – the dict-like iteration results

  • base_structure – the structure to which the individual configuration are applied to. If None it tries to extract it from the results document by calling the “structure” attribute (default is None)

Returns:

a dictionary with ranks structure objects as values

Return type:

Dict[int, Structure]

sqsgenerator.public.expand_sqs_results(settings: AttrDict, sqs_results: Iterable[SQSResult], timings: Optional[Dict[int, List[float]]] = None, fields: Tuple[str, ...] = ('configuration',), inplace: bool = False) AttrDict[source]#

Serializes a list of SQSResult into a JSON/YAML serializable dictionary

Parameters:
  • settings (AttrDict) – the settings used to compute the {sqs_results}

  • sqs_results (Iterable[SQSResult]) – a iterable (list) of SQSResult

  • timings (Dict[int, float]) – a dict like information about the performance of the core routines. Keys refer to thread numbers. The values represent the average time the thread needed to analyse one configuration in µs (default is None)

  • fields (Tuple[str, ...]) – a tuple of fields to include. Allowed fields are “configuration”, “objective”, and “parameters” (default is ('configuration',))

  • inplace – update the input settings document instead of creating a new one (default is False)

class sqsgenerator.public.SQSResult[source]#