The StructuresSet class¶
Initialization and methods¶
- class clusterx.structures_set.StructuresSet(parent_lattice=None, filepath=None, calculator=None, quick_parse=False, **sset_opts)¶
StructureSet class
Objects of this class contain a set of structures. This set can be used for various purposes, for instance as a training data set for cluster expansion, or as a validation set for cross validation. All the structures contained in a StructuresSet object must derive from a single ParentLattice object.
- Parameters:
- parent_latticeParentLattice
All the structures on a structures set must derive from the same parent lattice given here. This argument can be ommited if parsing from file (see below).
- filepathstr
if provided, the structures set is initialized from a structures_set file, as created by
StructuresSet.serialize()orStructuresSet.write_files(). In this case, theparent_latticeargument can be ommited (if present, it is overriden).- calculatorASE calculator object, default None
- quick_parsebool, default False
if True, it assumes that, in the file to be parsed (see
db_fname), the atom indices of the structures are the same as those of the supercell. Otherwise, the atom positions of structures and supercell are verified for every structure in the structures set being parsed. This leads to a slower parsing but safer if not sure how the file was built.
Examples
- add_structure(structure, folder='', **props)¶
Add a structure to the StructuresSet object
- Parameters:
- structureStructure
Structure object for the structure to be added.
- folderstr, default “”
optionally, path of the folder containing ab-initio runs. Paths are created automatically when calling
StructuresSet.write_files(). See related documentation for more details.- **propskeyword arguments
keyword arguments to be stored in the properties dictionary of a StructuresSet object.
- add_structures(structures=None, sort_key=None)¶
Add structures to the StructureSet object
- Parameters:
- structureslist of Structure, path to database file, or StructuresSet
Structures to be added
- sort_keylist of three int, default None
Only relevant if
structuresis a database file. Sort atomic positions after reading. For example, the value (2,1,0) will sort as: increasing z-coordinate first, increasing y-coordinate second, increasing x-coordinate third. Useful to get well ordered slab structures, for instance.
Notes
- calculate_energies(calculator, structure_fname='geometry.json')¶
Perform ab-initio calculation of energies using an ASE calculator.
The folders list as returned by
StructuresSet.get_folders()is iterated. The current working directory (cwd) is set to the actual folder in the loop. The structure in the filestructure_fnameis converted to anAtomsobject, whose calculator is set tocalulator. TheAtoms.get_potential_energy()method is called and the resulting total energy is stored in the filecwd/energy.dat.
- compute_property_values(property_name='energy', property_calc=None, rm_vacancies=True, update_db=True, **kwargs)¶
Return array of calculated property for all structures in the structures set.
- Parameters:
- property_namestr, default “energy”
Name of the property to be calculated. This is used as a key for the
self._propsdictionary. The property values can be recovered by calling the methodStructureSet.get_property_values(property_name)(see documentation).- property_calcfunction, default None
If none, the property value is calculated with the calculator object assigned to the structures set with the method
StructuresSet.set_calculator(). If not None, it must be a function with the following signature:my_function(i, structure, **kwargs)
where
iis the structure index,structureis the structure object for structure indexi, and**kwargsare any additional keyword arguments. The function must return a number.- rm_vacanciesbool, default True
Only takes effect if
property_funcisNone, i.e., when an ASE calculator (or derived calculator) is used. If True, the “Atoms.get_potential_energy()” method is applied to a copy of Structure.atoms object with vacancy sites removed, i.e., atom positions containing species with species number 0 or species symbol “X”.- update_dbbool, default True
Whether to update the database file (in case one is attached to the sset instance).
- **kwargskeyword argument list, arbitrary length
keyword arguments directly passed to
property_funcfunction. You may call this method as:sset_instance.calculate_property( property_name="my_prop", property_func="my_func", arg1=arg1, ..., argN=argN )
where
arg1toargNare the keyword arguments passed to themy_func(i, structure, **kwargs)function.
- energy_parser(folder, structure=None, **kwargs)¶
Read value stored in
energy.datfile.This is to be used as the default argument for the
read_propertyparameter of theStructureSet.read_property_values()method. Can be used as a template for reading different properties to be passed toStructureSet.read_property_values().- Parameters:
- iint
folder number
- folderstr
absolute or relative path of the folder containing the file/s to be read.
- structureStructure
structure object for structure index
i- **kwargskeyword arguments
Extra arguments needed for the property reading. See documentation of
StructureSet.read_property_values().
- classmethod from_file(filepath: str, quick_parse=False) Structure¶
Load a StructuresSet object from a serialized file.
Supports both SQLite and JSON-based serialization formats. The file is expected to have been created using the Structure.serialize() method.
Supported formats:
.db. : ASE-compatible SQLite database file.
.json : ASE-compatible JSON database file.
.xyz : extended xyz file.
- Parameters:
- filepathstr
Path to the serialized file. The format is inferred from the file extension.
- quick_parse
see __init__
- Returns:
- StructuresSet
A reconstructed StructuresSet object based on the contents of the file.
- Raises:
- ValueError
If the file extension is not supported.
- get_calculator()¶
Get Calculator object associated to the structures set.
- get_concentrations(site_type=0, sigma=1)¶
Get concentration values for a given site type
- get_db()¶
Get json database object corresponding to the list of folders containing structure files for ab-initio calculations as created by
StructureSet.write_files()
- get_db_fname()¶
Get file name of json database corresponding to the list of folders containing structure files for ab-initio calculations as created by
StructureSet.write_files()
- get_folders()¶
Get list of folders containing structure files for ab-initio calculations as created by
StructureSet.write_files()
- get_images(rm_vac=True, n=None)¶
Return array of Atoms objects from structures set.
- Parameters:
- rm_vacbool
whether the returned Atoms objects contain vacancies, i.e. atoms with species number 0 or chemical symbol X. If true, vacancy sites are eliminated in the returned Atoms objects
- nint
return the first
nstructures. IfNone, return all structures.
- get_natoms()¶
Return array of number of atoms of every strucure in the structures set.
- get_nstr()¶
Return number of structures in the structures set.
- get_parent_lattice()¶
Get ParentLattice object of structures set.
Returns the ParentLattice object from which all the structures in the StructuresSet object derive.
- get_predictions(cemodel)¶
Get predictions of CE model on structures set
Applies the given cluster expansion model to every structure in the structrues set and returns an array with the computed values.
- Parameters:
- cemodelModel
Cluster expansion model for which predictions want to be computed.
- get_property()¶
Get property dictionary of StructuresSet object
All the properties in a StructuresSet object, are stored in a dictionary with the following structure:
{"prop_name_1": [p10, p11, ...], "prop_name_2": [p20,p21, ..], ...}
where
"prop_name_i"is the name of the propertyi, andpijis the value of propertyifor structurej.This dictionary is returned by this method.
- get_property_names()¶
Return list of stored property names.
- get_property_values(property_name: str | List[str])¶
Return list of property values.
- Parameters:
- property_namestr | list of str
Name of the property or list of property names. If not sure, a list of property names can be obtained
StructuresSet.get_property_names().
- Returns:
- propsndarray
A python array with the property values. If property_name is list, return list of lists with property values, first axis is number of samples, second axis is property. Otherwise return simple list of property values.
- get_scell_indices()¶
Return array of supercell indices.
Every structure in a structure set, is a (“decorated”) supercell. The index of a supercell is an integer number, equal to the super cell volume in units of the parent cell volume.
This method returns an array of supercell indices, corresponding to each structure in the structures set.
- get_structure(sid)¶
Get one structure of the set
- Parameters:
- sidint
index of structure in the structure set.
- Returns:
- Structure object.
- get_structure_atoms(sid)¶
Return Atoms object for db row sid.
- get_structures()¶
Get all structures of the set
- Returns:
- list of Structure objects.
- get_subset(structure_indices=[], transfer_properties=True)¶
Return structures set instance containing a subset of structures of the original structures set
- Parameters:
- structure_indiceslist or array
indices of the structures in the original StructuresSet to be included in the subset.
- transfer_propertiesbool
if True (default), copy the properties from the original StructuresSet to the subset.
- parse_property_values(property_name='total_energy', write_to_file=True, property_parser=<function StructuresSet.energy_parser>, root='', update_json_db=True, **kwargs)¶
Read calculated property values from ab-inito output files
Read property values from ab-initio code output files. These files are contained in paths:
[[root] /] [prefix] id [suffix] / file_to_read
as created by
StructureSet.write_input_files(). The folders to be searched for energy values are those returned byStructureSet.get_folders(). These can be also obtained directly from the"metadata":{"folders":[ ... ]}elements of the json database file.The read property value is stored in the json-database of the StructuresSet object (i.e., that obtained from
StructureSet.get_db_fname()), under the key"data": {"properties": { ... }}dictionary for every structure. For instance:"data": {"properties": {"formation_energy_per_site": -0.05788398131602701, "total_energy": -9824740.09590308}},
where
"formation_energy_per_site"and"total_energy"here are the string value of the parameterproperty_namein the call toread_property_values().- Parameters:
- property_namestr
key for the
self._propsdictionary of property values- write_to_filebool
Whether to write property values to a file with name
property_name.dat.- property_parserfunction
Function to extract property value from ab-initio files. Return value must be scalar and signature is:
read_property(i,folder_path, structure = None, **kwargs)
where
iis the structure index,folder_pathis the path of the folder containing the relevant ab-initio files, structure is the structure object for structure indexi, and**kwargsare any additional keyword arguments.- rootstr
the root folder containing the subfolders with ab-initio data. See description above.
- update_json_dbbool, default True
Whether to update the json database file (in case one is attached to the sset instance).
- **kwargskeyword argument list, arbitrary length
keyword arguments directly passed to
read_propertyfunction. You may call this method as:sset_instance.read_property_values(read_property, arg1=arg1, ..., argN=argN)
where
arg1toargNare the keyword arguments passed to theread_property(folder_path,**kwargs)function.
- pop(index)¶
Pop (remove) Structure at specified index. Internal lists are updated, but lists with only Nones are not cleaned up.
- serialize(filepath='sset.db', ase_db_type=None, overwrite=False, rm_vac=False)¶
Serialize StructuresSet object
The serialization creates an ASE database object, with added metadata needed by CELL.
The format of the database is guessed from the filepath.
This file can be used to reconstruct a StructuresSet object, by initializing with:
StructuresSet(filepath="sset.db")
where “sset.db” is the file written in
filepath.The structures can be visualized using ASEs GUI. From the command line:
ase gui sset.db
To query the generated database in a browser you can do:
ase db -w sset.db
- Parameters:
- filepathstr
Output file name.
- ase_db_typestr or None, default None
Accepted values for the ASE database type:
'json': JSON format (saves to human readable json file.Serialization in this format can be extremely slow for medium to large sets)
'db': SQLite format (saves to a binary file)'postgresql': PostgreSQL database (server based)'mysql': MySQL database (server based)'aselmdb': ASE LMDB format (server based)
if None, ASE guesses from the name
- overwritebool, defauls is False
whether to overrite the serialized StructuresSet if it already exists.
Notes
- set_calculator(calc)¶
Assign calculator object to every structure in the structures set.
- Parameters:
- calcCalculator
- set_property_values(property_name='total_energy', property_vals=[], update_db=True)¶
Set property values
Set the property values.
If a folders’ json-database (as created by
StructuresSet.write_files()) exists, it is updated.- Parameters:
- property_namestr
Name of the property
- property_valsarray
Array of property values
- update_dbbool, default True
Whether to update the json database file (in case one is attached to the sset instance).
- set_property_values_from_files(property_name='property', property_file_name='property.dat', cwd='./')¶
Set property values read from files
Consider a
StructuresSetoject namedsset.The list of folders
sset.get_folders()is iterated and the value stored in the file namedproperty_file_nameis parsed and assigned to the corresponding sample in thesset. The name of the property isproperty_nameand can be recovered by callingsset.get_property_values(property_name).If an associated json database exists, it is updated with the new property.
- Parameters:
- property_namestr
The name used to label the property in the structures set. This label is then listed in
sset.get_property_names()and the property values for this label can be obtained by callingsset.get_property_values(property_name)- property_file_namestr
In every folder of the list
sset.get_folders()there must be a file namedproperty_file_namecontaining a real number with the value of the property
- write_input_files(root='.', prefix='', suffix='', fnames=None, formats=[], overwrite=True, rm_vac=False)¶
Create folders containing structure input files for ab-initio calculations.
Structure files are written to files with path:
[[root] /] [prefix] id [suffix] / [filename]
Where
root,prefix,suffix, andfilenameare explained below, andid+ 1 is the structure id in a created database with path:[[root] /] [prefix]id0-idN[suffix] . [json|db]
where
id0andidNare the smallest and largestidindices. The path of the created folders are stored in the database created byStructuresSet.write_files(), under, for instance:{ ... "key_value_pairs": {"folder": "./random_strs-14"}, ... }
- Parameters:
- rootstr
path to the root folder containing the set of created folders
- prefixstr
prefix for name of folder containing the files
- suffixstr
suffix for name of folder containing the files
- fnamesarray of Strings
Array of file names for files contaning the structure. If not set defaults to
geometry.json.- formatsarray of Strings, optional
Array of file formats corresponding to the file names in
fnames. Possible formats are listed in ase.io.write. If entirely ommited, or if an element of the array isNone, the format is guessed from the corresponding file name.- overwritebool
Whether to overrite content of existing folders.
- rm_vacbool
Vacancies are represented with chemical symbol
Xand atomic number 0. Output file formats will contain lines with atomic positions corresponding to vacancies. If you want them absent in the files, setremove_vacanciestoTrue.