INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Build the object from Abinit ixc ( integer )
def from_abinit_ixc(cls, ixc): """Build the object from Abinit ixc (integer)""" ixc = int(ixc) if ixc >= 0: return cls(**cls.abinitixc_to_libxc[ixc]) else: # libxc notation employed in Abinit: a six-digit number in the form XXXCCC or CCCXXX #ixc = str(...
Build the object from ( type name ).
def from_type_name(cls, typ, name): """Build the object from (type, name).""" # Try aliases first. for k, nt in cls.defined_aliases.items(): if typ is not None and typ != nt.type: continue #print(name, nt.name) if name == nt.name: if len(k) == ...
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
def from_dict(cls, d): """ Makes XcFunc obey the general json interface used in pymatgen for easier serialization. """ return cls(xc=d.get("xc"), x=d.get("x"), c=d.get("c"))
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
def as_dict(self): """ Makes XcFunc obey the general json interface used in pymatgen for easier serialization. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} # print("in as_dict", type(self.x), type(self.c), type(self.xc)) i...
The type of the functional.
def type(self): """The type of the functional.""" if self.xc in self.defined_aliases: return self.defined_aliases[self.xc].type xc = (self.x, self.c) if xc in self.defined_aliases: return self.defined_aliases[xc].type # If self is not in defined_aliases, use LibxcFunc family ...
The name of the functional. If the functional is not found in the aliases the string has the form X_NAME + C_NAME
def name(self): """ The name of the functional. If the functional is not found in the aliases, the string has the form X_NAME+C_NAME """ if self.xc in self.defined_aliases: return self.defined_aliases[self.xc].name xc = (self.x, self.c) if xc in self.defined_alias...
Returns the voronoi_list needed for the VoronoiContainer object from a bson - encoded voronoi_list ( composed of vlist and bson_nb_voro_list ).: param vlist: List of voronoi objects: param bson_nb_voro_list: List of periodic sites involved in the Voronoi: return: The voronoi_list needed for the VoronoiContainer ( with ...
def from_bson_voronoi_list(bson_nb_voro_list, structure): """ Returns the voronoi_list needed for the VoronoiContainer object from a bson-encoded voronoi_list (composed of vlist and bson_nb_voro_list). :param vlist: List of voronoi objects :param bson_nb_voro_list: List of periodic sites involved in...
Set up of the voronoi list of neighbours by calling qhull: param indices: indices of the sites for which the Voronoi is needed: param voronoi_cutoff: Voronoi cutoff for the search of neighbours: raise RuntimeError: If an infinite vertex is found in the voronoi construction
def setup_voronoi_list(self, indices, voronoi_cutoff): """ Set up of the voronoi list of neighbours by calling qhull :param indices: indices of the sites for which the Voronoi is needed :param voronoi_cutoff: Voronoi cutoff for the search of neighbours :raise RuntimeError: If an ...
Initializes the angle and distance separations: param indices: indices of the sites for which the Voronoi is needed
def setup_neighbors_distances_and_angles(self, indices): """ Initializes the angle and distance separations :param indices: indices of the sites for which the Voronoi is needed """ self.neighbors_distances = [None] * len(self.structure) self.neighbors_normalized_distances...
Transforms the voronoi_list into a vlist + bson_nb_voro_list that are BSON - encodable.: return: [ vlist bson_nb_voro_list ] to be used in the as_dict method
def to_bson_voronoi_list2(self): """ Transforms the voronoi_list into a vlist + bson_nb_voro_list, that are BSON-encodable. :return: [vlist, bson_nb_voro_list], to be used in the as_dict method """ bson_nb_voro_list2 = [None] * len(self.voronoi_list2) for ivoro, voro in e...
Bson - serializable dict representation of the VoronoiContainer.: return: dictionary that is BSON - encodable
def as_dict(self): """ Bson-serializable dict representation of the VoronoiContainer. :return: dictionary that is BSON-encodable """ bson_nb_voro_list2 = self.to_bson_voronoi_list2() return {"@module": self.__class__.__module__, "@class": self.__class__.__...
Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using the as_dict method.: param d: dict representation of the VoronoiContainer object: return: VoronoiContainer object
def from_dict(cls, d): """ Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using the as_dict method. :param d: dict representation of the VoronoiContainer object :return: VoronoiContainer object """ structure = S...
Decorator for: class: Node methods. Raise SpectatorNodeError.
def check_spectator(node_method): """ Decorator for :class:`Node` methods. Raise `SpectatorNodeError`. """ from functools import wraps @wraps(node_method) def wrapper(*args, **kwargs): node = args[0] if node.in_spectator_mode: #raise node.SpectatorError("You should no...
Save the id of the last node created.
def save_lastnode_id(): """Save the id of the last node created.""" init_counter() with FileLock(_COUNTER_FILE): with AtomicFile(_COUNTER_FILE, mode="w") as fh: fh.write("%d\n" % _COUNTER)
Convert obj into Status.
def as_status(cls, obj): """Convert obj into Status.""" if obj is None: return None return obj if isinstance(obj, cls) else cls.from_string(obj)
Return a Status instance from its string representation.
def from_string(cls, s): """Return a `Status` instance from its string representation.""" for num, text in cls._STATUS2STR.items(): if text == s: return cls(num) else: raise ValueError("Wrong string %s" % s)
List of output files produces by self.
def products(self): """List of output files produces by self.""" _products = [] for ext in self.exts: prod = Product(ext, self.node.opath_from_ext(ext)) _products.append(prod) return _products
This function is called when we specify the task dependencies with the syntax:
def apply_getters(self, task): """ This function is called when we specify the task dependencies with the syntax: deps={node: "@property"} In this case the task has to the get `property` from `node` before starting the calculation. At present, the following properties are ...
Returns a dictionary with the variables that must be added to the input file in order to connect this: class: Node to its dependencies.
def connecting_vars(self): """ Returns a dictionary with the variables that must be added to the input file in order to connect this :class:`Node` to its dependencies. """ vars = {} for prod in self.products: vars.update(prod.connecting_vars()) return...
Returns the paths of the output files produced by self and its extensions
def get_filepaths_and_exts(self): """Returns the paths of the output files produced by self and its extensions""" filepaths = [prod.filepath for prod in self.products] exts = [prod.ext for prod in self.products] return filepaths, exts
Build a: class: Product instance from a filepath.
def from_file(cls, filepath): """Build a :class:`Product` instance from a filepath.""" # Find the abinit extension. for i in range(len(filepath)): if filepath[i:] in abi_extensions(): ext = filepath[i:] break else: raise ValueError(...
Initialize an instance of NodeResults from a Node subclass.
def from_node(cls, node): """Initialize an instance of `NodeResults` from a `Node` subclass.""" kwargs = dict( node_id=node.node_id, node_finalized=node.finalized, node_history=list(node.history), node_name=node.name, node_class=node.__class__....
This function registers the files that will be saved in GridFS. kwargs is a dictionary mapping the key associated to the file ( usually the extension ) to the absolute path. By default files are assumed to be in binary form for formatted files one should pass a tuple ( filepath t ).
def register_gridfs_files(self, **kwargs): """ This function registers the files that will be saved in GridFS. kwargs is a dictionary mapping the key associated to the file (usually the extension) to the absolute path. By default, files are assumed to be in binary form, for formatted fil...
Update a mongodb collection.
def update_collection(self, collection): """ Update a mongodb collection. """ node = self.node flow = node if node.is_flow else node.flow # Build the key used to store the entry in the document. key = node.name if node.is_task: key = "w" + str...
Node color as Hex Triplet https:// en. wikipedia. org/ wiki/ Web_colors#Hex_triplet
def color_hex(self): """Node color as Hex Triplet https://en.wikipedia.org/wiki/Web_colors#Hex_triplet""" def clamp(x): return max(0, min(int(x), 255)) r, g, b = np.trunc(self.color_rgb * 255) return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
Check whether the node is a instance of class_or_string. Unlinke the standard isinstance builtin the method accepts either a class or a string. In the later case the string is compared with self. __class__. __name__ ( case insensitive ).
def isinstance(self, class_or_string): """ Check whether the node is a instance of `class_or_string`. Unlinke the standard isinstance builtin, the method accepts either a class or a string. In the later case, the string is compared with self.__class__.__name__ (case insensitive). ...
Convert obj into a Node instance.
def as_node(cls, obj): """ Convert obj into a Node instance. Return: obj if obj is a Node instance, cast obj to :class:`FileNode` instance of obj is a string. None if obj is None """ if isinstance(obj, cls): return obj elif...
The name of the node ( only used for facilitating its identification in the user interface ).
def name(self): """ The name of the node (only used for facilitating its identification in the user interface). """ try: return self._name except AttributeError: if self.is_task: try: return self.pos_str ...
Return a relative version of the workdir
def relworkdir(self): """Return a relative version of the workdir""" if getattr(self, "workdir", None) is None: return None try: return os.path.relpath(self.workdir) except OSError: # current working directory may not be defined! return sel...
This method should be called once we have fixed the problem associated to this event. It adds a new entry in the correction history of the node.
def log_correction(self, event, action): """ This method should be called once we have fixed the problem associated to this event. It adds a new entry in the correction history of the node. Args: event: :class:`AbinitEvent` that triggered the correction. action (...
Add a list of dependencies to the: class: Node.
def add_deps(self, deps): """ Add a list of dependencies to the :class:`Node`. Args: deps: List of :class:`Dependency` objects specifying the dependencies of the node. or dictionary mapping nodes to file extensions e.g. {task: "DEN"} """ if isinstan...
Remove a list of dependencies from the: class: Node.
def remove_deps(self, deps): """ Remove a list of dependencies from the :class:`Node`. Args: deps: List of :class:`Dependency` objects specifying the dependencies of the node. """ if not isinstance(deps, (list, tuple)): deps = [deps] assert all(...
Returns a list with the status of the dependencies.
def deps_status(self): """Returns a list with the status of the dependencies.""" if not self.deps: return [self.S_OK] return [d.status for d in self.deps]
Return the list of nodes in the: class: Flow that depends on this: class: Node
def get_children(self): """ Return the list of nodes in the :class:`Flow` that depends on this :class:`Node` .. note:: This routine assumes the entire flow has been allocated. """ # Specialized branch for FileNode. if self.is_file: return self.fi...
Return the string representation of the dependencies of the node.
def str_deps(self): """Return the string representation of the dependencies of the node.""" lines = [] app = lines.append app("Dependencies of node %s:" % str(self)) for i, dep in enumerate(self.deps): app("%d) %s, status=%s" % (i, dep.info, str(dep.status))) ...
Return pandas DataFrame with the value of the variables specified in varnames. Can be used for task/ works/ flow. It s recursive!
def get_vars_dataframe(self, *varnames): """ Return pandas DataFrame with the value of the variables specified in `varnames`. Can be used for task/works/flow. It's recursive! .. example: flow.get_vars_dataframe("ecut", "ngkpt") work.get_vars_dataframe("acell", "...
Generate directory graph in the DOT language. The graph show the files and directories in the node workdir.
def get_graphviz_dirtree(self, engine="automatic", **kwargs): """ Generate directory graph in the DOT language. The graph show the files and directories in the node workdir. Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph> """ if eng...
The list of handlers registered for this node. If the node is not a Flow and does not have its own list of handlers the handlers registered at the level of the flow are returned.
def event_handlers(self): """ The list of handlers registered for this node. If the node is not a `Flow` and does not have its own list of `handlers` the handlers registered at the level of the flow are returned. This trick allows one to registered different handlers at the leve...
Install the EventHandlers for this Node. If no argument is provided the default list of handlers is installed.
def install_event_handlers(self, categories=None, handlers=None): """ Install the `EventHandlers for this `Node`. If no argument is provided the default list of handlers is installed. Args: categories: List of categories to install e.g. base + can_change_physics ...
Print to stream the event handlers installed for this flow.
def show_event_handlers(self, stream=sys.stdout, verbose=0): """Print to `stream` the event handlers installed for this flow.""" lines = ["List of event handlers installed:"] for handler in self.event_handlers: if verbose: lines.extend(handler.__class__.cls2str().spli...
Send signal from this node to all connected receivers unless the node is in spectator mode.
def send_signal(self, signal): """ Send signal from this node to all connected receivers unless the node is in spectator mode. signal -- (hashable) signal value, see `dispatcher` connect for details Return a list of tuple pairs [(receiver, response), ... ] or None if the node i...
Return the message after merging any user - supplied arguments with the message.
def get_message(self, metadata=False, asctime=True): """ Return the message after merging any user-supplied arguments with the message. Args: metadata: True if function and module name should be added. asctime: True if time string should be added. """ msg...
Returns a string with the history. Set metadata to True to have info on function and module.
def to_string(self, metadata=False): """Returns a string with the history. Set metadata to True to have info on function and module.""" return "\n".join(rec.get_message(metadata=metadata) for rec in self)
Log msg % args with the warning severity level
def warning(self, msg, *args, **kwargs): """Log 'msg % args' with the warning severity level""" self._log("WARNING", msg, args, kwargs)
Log msg % args with the critical severity level
def critical(self, msg, *args, **kwargs): """Log 'msg % args' with the critical severity level""" self._log("CRITICAL", msg, args, kwargs)
Low - level logging routine which creates a: class: HistoryRecord.
def _log(self, level, msg, args, exc_info=None, extra=None): """Low-level logging routine which creates a :class:`HistoryRecord`.""" if exc_info and not isinstance(exc_info, tuple): exc_info = sys.exc_info() self.append(HistoryRecord(level, "unknown filename", 0, msg, args, exc_info...
Parse libxc_docs. txt file return dictionary with mapping: libxc_id -- > info_dict
def parse_libxc_docs(path): """ Parse libxc_docs.txt file, return dictionary with mapping: libxc_id --> info_dict """ def parse_section(section): d = {} for l in section: key, value = l.split(":") key = key.strip() d[key] = value.strip() return int(d["Number"]), d d = Ordered...
Write json file with libxc metadata to path jpath.
def write_libxc_docs_json(xcfuncs, jpath): """Write json file with libxc metadata to path jpath.""" from copy import deepcopy xcfuncs = deepcopy(xcfuncs) # Remove XC_FAMILY from Family and XC_ from Kind to make strings more human-readable. for d in xcfuncs.values(): d["Family"] = d["Family"...
Main function.
def main(): """Main function.""" if "-h" in sys.argv or "--help" in sys.argv: print(__doc__) print("Usage: regen_libxcfunc.py path_to_libxc_docs.txt") return 0 try: path = sys.argv[1] except IndexError: print(__doc__) print("Usage: regen_libxcfunc.py path...
Generate a movie from a sequence of structures using vtk and ffmpeg.
def make_movie(structures, output_filename="movie.mp4", zoom=1.0, fps=20, bitrate="10000k", quality=1, **kwargs): """ Generate a movie from a sequence of structures using vtk and ffmpeg. Args: structures ([Structure]): sequence of structures output_filename (str): filename fo...
Rotate the camera view.
def rotate_view(self, axis_ind=0, angle=0): """ Rotate the camera view. Args: axis_ind: Index of axis to rotate. Defaults to 0, i.e., a-axis. angle: Angle to rotate by. Defaults to 0. """ camera = self.ren.GetActiveCamera() if axis_ind == 0: ...
Save render window to an image.
def write_image(self, filename="image.png", magnification=1, image_format="png"): """ Save render window to an image. Arguments: filename: filename to save to. Defaults to image.png. magnification: magnification. Use it...
Redraw the render window.
def redraw(self, reset_camera=False): """ Redraw the render window. Args: reset_camera: Set to True to reset the camera to a pre-determined default for each structure. Defaults to False. """ self.ren.RemoveAllViewProps() self.picker = None ...
Display the help for various keyboard shortcuts.
def display_help(self): """ Display the help for various keyboard shortcuts. """ helptxt = ["h : Toggle help", "A/a, B/b or C/c : Increase/decrease cell by one a," " b or c unit vector", "# : Toggle showing of polyhedrons", "-: Tog...
Add a structure to the visualizer.
def set_structure(self, structure, reset_camera=True, to_unit_cell=True): """ Add a structure to the visualizer. Args: structure: structure to visualize reset_camera: Set to True to reset the camera to a default determined based on the structure. ...
Zoom the camera view by a factor.
def zoom(self, factor): """ Zoom the camera view by a factor. """ camera = self.ren.GetActiveCamera() camera.Zoom(factor) self.ren_win.Render()
Display the visualizer.
def show(self): """ Display the visualizer. """ self.iren.Initialize() self.ren_win.SetSize(800, 800) self.ren_win.SetWindowName(self.title) self.ren_win.Render() self.iren.Start()
Add a site to the render window. The site is displayed as a sphere the color of which is determined based on the element. Partially occupied sites are displayed as a single element color though the site info still shows the partial occupancy.
def add_site(self, site): """ Add a site to the render window. The site is displayed as a sphere, the color of which is determined based on the element. Partially occupied sites are displayed as a single element color, though the site info still shows the partial occupancy. ...
Add text at a coordinate.
def add_text(self, coords, text, color=(0, 0, 0)): """ Add text at a coordinate. Args: coords: Coordinates to add text at. text: Text to place. color: Color for text as RGB. Defaults to black. """ source = vtk.vtkVectorText() source.Se...
Adds a line.
def add_line(self, start, end, color=(0.5, 0.5, 0.5), width=1): """ Adds a line. Args: start: Starting coordinates for line. end: Ending coordinates for line. color: Color for text as RGB. Defaults to grey. width: Width of line. Defaults to 1. ...
Adds a polyhedron.
def add_polyhedron(self, neighbors, center, color, opacity=1.0, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2): """ Adds a polyhedron. Args: neighbors: Neighbors of the polyhedron (the vertices). center: Th...
Adds a triangular surface between three atoms.
def add_triangle(self, neighbors, color, center=None, opacity=0.4, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2): """ Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be draw...
Adds bonds for a site.
def add_bonds(self, neighbors, center, color=None, opacity=None, radius=0.1): """ Adds bonds for a site. Args: neighbors: Neighbors of the site. center: The site in the center for all bonds. color: Color of the tubes representing the bonds ...
Convenience function which returns the unit vector aligned with the miller index.
def get_mi_vec(slab): """ Convenience function which returns the unit vector aligned with the miller index. """ mvec = np.cross(slab.lattice.matrix[0], slab.lattice.matrix[1]) return mvec / np.linalg.norm(mvec)
Gets the transformation to rotate the z axis into the miller index
def get_rot(slab): """ Gets the transformation to rotate the z axis into the miller index """ new_z = get_mi_vec(slab) a, b, c = slab.lattice.matrix new_x = a / np.linalg.norm(a) new_y = np.cross(new_z, new_x) x, y, z = np.eye(3) rot_matrix = np.array([np.dot(*el) for el in ...
converts a cartesian coordinate such that it is inside the unit cell.
def put_coord_inside(lattice, cart_coordinate): """ converts a cartesian coordinate such that it is inside the unit cell. """ fc = lattice.get_fractional_coords(cart_coordinate) return lattice.get_cartesian_coords([c - np.floor(c) for c in fc])
reorients a structure such that the z axis is concurrent with the normal to the A - B plane
def reorient_z(structure): """ reorients a structure such that the z axis is concurrent with the normal to the A-B plane """ struct = structure.copy() sop = get_rot(struct) struct.apply_operation(sop) return struct
Function that helps visualize the slab in a 2 - D plot for convenient viewing of output of AdsorbateSiteFinder.
def plot_slab(slab, ax, scale=0.8, repeat=5, window=1.5, draw_unit_cell=True, decay=0.2, adsorption_sites=True): """ Function that helps visualize the slab in a 2-D plot, for convenient viewing of output of AdsorbateSiteFinder. Args: slab (slab): Slab object to be visualized ...
This method constructs the adsorbate site finder from a bulk structure and a miller index which allows the surface sites to be determined from the difference in bulk and slab coordination as opposed to the height threshold.
def from_bulk_and_miller(cls, structure, miller_index, min_slab_size=8.0, min_vacuum_size=10.0, max_normal_search=None, center_slab=True, selective_dynamics=False, undercoord_threshold=0.09): """ This method construct...
This method finds surface sites by determining which sites are within a threshold value in height from the topmost site in a list of sites
def find_surface_sites_by_height(self, slab, height=0.9, xy_tol=0.05): """ This method finds surface sites by determining which sites are within a threshold value in height from the topmost site in a list of sites Args: site_list (list): list of sites from which to select su...
Assigns site properties.
def assign_site_properties(self, slab, height=0.9): """ Assigns site properties. """ if 'surface_properties' in slab.site_properties.keys(): return slab else: surf_sites = self.find_surface_sites_by_height(slab, height) surf_props = ['surface' if s...
Gets an extended surface mesh for to use for adsorption site finding by constructing supercell of surface sites
def get_extended_surface_mesh(self, repeat=(5, 5, 1)): """ Gets an extended surface mesh for to use for adsorption site finding by constructing supercell of surface sites Args: repeat (3-tuple): repeat for getting extended surface mesh """ surf_str = Structur...
Finds surface sites according to the above algorithm. Returns a list of corresponding cartesian coordinates.
def find_adsorption_sites(self, distance=2.0, put_inside=True, symm_reduce=1e-2, near_reduce=1e-2, positions=['ontop', 'bridge', 'hollow'], no_obtuse_hollow=True): """ Finds surface sites according to the above alg...
Reduces the set of adsorbate sites by finding removing symmetrically equivalent duplicates
def symm_reduce(self, coords_set, threshold=1e-6): """ Reduces the set of adsorbate sites by finding removing symmetrically equivalent duplicates Args: coords_set: coordinate set in cartesian coordinates threshold: tolerance for distance equivalence, used ...
Prunes coordinate set for coordinates that are within threshold
def near_reduce(self, coords_set, threshold=1e-4): """ Prunes coordinate set for coordinates that are within threshold Args: coords_set (Nx3 array-like): list or array of coordinates threshold (float): threshold value for distance """ unique_coord...
Finds the center of an ensemble of sites selected from a list of sites. Helper method for the find_adsorption_sites algorithm.
def ensemble_center(self, site_list, indices, cartesian=True): """ Finds the center of an ensemble of sites selected from a list of sites. Helper method for the find_adsorption_sites algorithm. Args: site_list (list of sites): list of sites indices (list...
Adds an adsorbate at a particular coordinate. Adsorbate represented by a Molecule object and is positioned relative to the input adsorbate coordinate.
def add_adsorbate(self, molecule, ads_coord, repeat=None, reorient=True): """ Adds an adsorbate at a particular coordinate. Adsorbate represented by a Molecule object, and is positioned relative to the input adsorbate coordinate. Args: molecule (Molecule): molecule ...
Helper function to assign selective dynamics site_properties based on surface subsurface site properties
def assign_selective_dynamics(self, slab): """ Helper function to assign selective dynamics site_properties based on surface, subsurface site properties Args: slab (Slab): slab for which to assign selective dynamics """ sd_list = [] sd_list = [[False,...
Function that generates all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/ width of precursor slab as an input
def generate_adsorption_structures(self, molecule, repeat=None, min_lw=5.0, reorient=True, find_args={}): """ Function that generates all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/width of pre...
Function that generates all adsorption structures for a given molecular adsorbate on both surfaces of a slab. This is useful for calculating surface energy where both surfaces need to be equivalent or if we want to calculate nonpolar systems.
def adsorb_both_surfaces(self, molecule, repeat=None, min_lw=5.0, reorient=True, find_args={}): """ Function that generates all adsorption structures for a given molecular adsorbate on both surfaces of a slab. This is useful for calculating surface energy whe...
Function that performs substitution - type doping on the surface and returns all possible configurations where one dopant is substituted per surface. Can substitute one surface or both.
def generate_substitution_structures(self, atom, target_species=[], sub_both_sides=False, range_tol=1e-2, dist_from_surf=0): """ Function that performs substitution-type doping on the surface and returns all po...
Reads the exciting input from a string
def from_string(data): """ Reads the exciting input from a string """ root=ET.fromstring(data) speciesnode=root.find('structure').iter('species') elements = [] positions = [] vectors=[] lockxyz=[] # get title title_in=str(ro...
List of types of specie. Only works for ordered structures. Disordered structures will raise TypeError.
def types_of_specie(self): """ List of types of specie. Only works for ordered structures. Disordered structures will raise TypeError. """ if not self.is_ordered: raise TypeError("""\ types_of_species cannot be used with disordered structures and partial occupancies. ...
Iterate over species grouped by type
def group_by_types(self): """Iterate over species grouped by type""" for t in self.types_of_specie: for site in self: if site.specie == t: yield site
Returns a tuple with the sequential indices of the sites that contain an element with the given chemical symbol.
def indices_from_symbol(self, symbol: str) -> tuple: """ Returns a tuple with the sequential indices of the sites that contain an element with the given chemical symbol. """ return tuple((i for i, specie in enumerate(self.species) if specie.symbol == symbol)...
Returns the site properties as a dict of sequences. E. g. { magmom: ( 5 - 5 ) charge: ( - 4 4 ) }.
def site_properties(self): """ Returns the site properties as a dict of sequences. E.g., {"magmom": (5,-5), "charge": (-4,4)}. """ props = {} prop_keys = set() for site in self: prop_keys.update(site.properties.keys()) for k in prop_keys: ...
( Composition ) Returns the composition
def composition(self): """ (Composition) Returns the composition """ elmap = collections.defaultdict(float) for site in self: for species, occu in site.species.items(): elmap[species] += occu return Composition(elmap)
Returns the net charge of the structure based on oxidation states. If Elements are found a charge of 0 is assumed.
def charge(self): """ Returns the net charge of the structure based on oxidation states. If Elements are found, a charge of 0 is assumed. """ charge = 0 for site in self: for specie, amt in site.species.items(): charge += getattr(specie, "oxi_s...
Returns angle specified by three sites.
def get_angle(self, i: int, j: int, k: int) -> float: """ Returns angle specified by three sites. Args: i: Index of first site. j: Index of second site. k: Index of third site. Returns: Angle in degrees. """ v1 = self[i].c...
Returns dihedral angle specified by four sites.
def get_dihedral(self, i: int, j: int, k: int, l: int) -> float: """ Returns dihedral angle specified by four sites. Args: i: Index of first site j: Index of second site k: Index of third site l: Index of fourth site Returns: ...
True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non - periodic Molecules while PBC is taken into account for periodic structures.
def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool: """ True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is ...
Adds a property to a site.
def add_site_property(self, property_name, values): """ Adds a property to a site. Args: property_name (str): The name of the property to add. values (list): A sequence of values. Must be same length as number of sites. """ if len(values) ...
Swap species.
def replace_species(self, species_mapping): """ Swap species. Args: species_mapping (dict): dict of species to swap. Species can be elements too. E.g., {Element("Li"): Element("Na")} performs a Li for Na substitution. The second species can be a ...
Add oxidation states.
def add_oxidation_state_by_element(self, oxidation_states): """ Add oxidation states. Args: oxidation_states (dict): Dict of oxidation states. E.g., {"Li":1, "Fe":2, "P":5, "O":-2} """ try: for site in self.sites: new_sp = ...
Add oxidation states to a structure by site.
def add_oxidation_state_by_site(self, oxidation_states): """ Add oxidation states to a structure by site. Args: oxidation_states (list): List of oxidation states. E.g., [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2] """ if len(oxidation_states) ...
Removes oxidation states from a structure.
def remove_oxidation_states(self): """ Removes oxidation states from a structure. """ for site in self.sites: new_sp = collections.defaultdict(float) for el, occu in site.species.items(): sym = el.symbol new_sp[Element(sym)] += occu...
Decorates the structure with oxidation state guessing using Composition. oxi_state_guesses ()
def add_oxidation_state_by_guess(self, **kwargs): """ Decorates the structure with oxidation state, guessing using Composition.oxi_state_guesses() Args: **kwargs: parameters to pass into oxi_state_guesses() """ oxid_guess = self.composition.oxi_state_guesses(...
Add spin states to a structure.
def add_spin_by_element(self, spins): """ Add spin states to a structure. Args: spisn (dict): Dict of spins associated with elements or species, e.g. {"Ni":+5} or {"Ni2+":5} """ for site in self.sites: new_sp = {} for sp, occu in s...
Add spin states to a structure by site.
def add_spin_by_site(self, spins): """ Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0] """ if len(spins) != len(self.sites): raise ValueError("Spin of all sites must be " ...
Removes spin states from a structure.
def remove_spin(self): """ Removes spin states from a structure. """ for site in self.sites: new_sp = collections.defaultdict(float) for sp, occu in site.species.items(): oxi_state = getattr(sp, "oxi_state", None) new_sp[Specie(sp.s...