text
stringlengths
81
112k
Relax a structure and compute the energy using Buckingham potential. Args: structure: pymatgen.core.structure.Structure gulp_cmd: GULP command if not in standard place keywords: GULP first line keywords valence_dict: {El: valence}. Needed if the structure is not charge n...
Generates GULP input string corresponding to pymatgen structure. Args: structure: pymatgen Structure object cell_flg (default = True): Option to use lattice parameters. fractional_flg (default = True): If True, fractional coordinates are used. Else, cartesian...
Specifies GULP library file to read species and potential parameters. If using library don't specify species and potential in the input file and vice versa. Make sure the elements of structure are in the library file. Args: file_name: Name of GULP library file Retur...
Gets a GULP input for an oxide structure and buckingham potential from library. Args: structure: pymatgen.core.structure.Structure keywords: GULP first line keywords. library (Default=None): File containing the species and potential. uc (Default=True): Un...
Generate species, buckingham, and spring options for an oxide structure using the parameters in default libraries. Ref: 1. G.V. Lewis and C.R.A. Catlow, J. Phys. C: Solid State Phys., 18, 1149-1161 (1985) 2. T.S.Bush, J.D.Gale, C.R.A.Catlow and P.D. Battle, ...
Gets a GULP input with Tersoff potential for an oxide structure Args: structure: pymatgen.core.structure.Structure periodic (Default=False): Flag denoting whether periodic boundary conditions are used library (Default=None): File containing the species and po...
Generate the species, tersoff potential lines for an oxide structure Args: structure: pymatgen.core.structure.Structure def tersoff_potential(self, structure): """ Generate the species, tersoff potential lines for an oxide structure Args: structure: pymatgen.co...
Run GULP using the gin as input Args: gin: GULP input string Returns: gout: GULP output string def run(self, gin): """ Run GULP using the gin as input Args: gin: GULP input string Returns: gout: GULP output string ...
Print to the given string, the documentation for the events and the associated handlers. def autodoc_event_handlers(stream=sys.stdout): """ Print to the given string, the documentation for the events and the associated handlers. """ lines = [] for cls in all_subclasses(EventHandler): ...
Return the list of handler classes. def get_event_handler_classes(categories=None): """Return the list of handler classes.""" classes = [c for c in all_subclasses(EventHandler) if c not in _ABC_EVHANDLER_CLASSES] return classes
Convert obj into a subclass of AbinitEvent. obj can be either a class or a string with the class name or the YAML tag def as_event_class(obj): """ Convert obj into a subclass of AbinitEvent. obj can be either a class or a string with the class name or the YAML tag """ if is_string(obj): ...
The baseclass of self. def baseclass(self): """The baseclass of self.""" for cls in _BASE_CLASSES: if isinstance(self, cls): return cls raise ValueError("Cannot determine the base class of %s" % self.__class__.__name__)
Add an event to the list. def append(self, event): """Add an event to the list.""" self._events.append(event) self._events_by_baseclass[event.baseclass].append(event)
Set the value of _run_completed. def set_run_completed(self, boolean, start_datetime, end_datetime): """Set the value of _run_completed.""" self._run_completed = boolean if (start_datetime, end_datetime) != (None, None): # start_datetime: Sat Feb 28 23:54:27 2015 # end_...
Wall-time of the run as `timedelta` object. def run_etime(self): """Wall-time of the run as `timedelta` object.""" if self.start_datetime is None or self.end_datetime is None: return None return self.end_datetime - self.start_datetime
Parse the given file. Return :class:`EventReport`. def parse(self, filename, verbose=0): """ Parse the given file. Return :class:`EventReport`. """ run_completed, start_datetime, end_datetime = False, None, None filename = os.path.abspath(filename) report = EventReport(f...
This method is used when self.parser raises an Exception so that we can report a customized :class:`EventReport` object with info the exception. def report_exception(self, filename, exc): """ This method is used when self.parser raises an Exception so that we can report a customized :cl...
Return the number of times the event associated to this handler has been already fixed in the :class:`Task`. def count(self, task): """ Return the number of times the event associated to this handler has been already fixed in the :class:`Task`. """ return len([c for c in...
Sets the stable charges and transition states for a series of defect entries. This function uses scipy's HalfspaceInterection to oncstruct the polygons corresponding to defect stability as a function of the Fermi-level. The Halfspace Intersection constructs N-dimensional hyperplanes, in ...
List all unstable entries (defect+charge) in the DefectPhaseDiagram def all_unstable_entries(self): """ List all unstable entries (defect+charge) in the DefectPhaseDiagram """ all_stable_entries = self.all_stable_entries return [e for e in self.entries if e not in all_stable_ent...
Give list of all concentrations at specified efermi in the DefectPhaseDiagram args: chemical_potentials = {Element: number} is dictionary of chemical potentials to provide formation energies for temperature = temperature to produce concentrations from fermi_level: (float) is ...
Suggest possible charges for defects to computee based on proximity of known transitions from entires to VBM and CBM Args: tolerance (float): tolerance with respect to the VBM and CBM to ` continue to compute new charges def suggest_charges(self, tolerance=0.1)...
Solve for the Fermi energy self-consistently as a function of T and p_O2 Observations are Defect concentrations, electron and hole conc Args: bulk_dos: bulk system dos (pymatgen Dos object) gap: Can be used to specify experimental gap. Will be useful if th...
Convert object into Xcfunc. def asxc(cls, obj): """Convert object into Xcfunc.""" if isinstance(obj, cls): return obj if is_string(obj): return cls.from_name(obj) raise TypeError("Don't know how to convert <%s:%s> to Xcfunc" % (type(obj), str(obj)))
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 f...
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 == n...
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__.__n...
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_alia...
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.de...
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 VoronoiConta...
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_lis...
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 n...
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. :retur...
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_bso...
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 VoronoiContaine...
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_spe...
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 stri...
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: 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 supported: - @structure def apply_get...
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 ...
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] ...
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:] ...
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), ...
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"). ...
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_tas...
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) re...
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 ...
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 def as_node(cls, obj): """ Convert obj into a Node instance. Return: obj if obj is a ...
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 AttributeErro...
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 ...
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 (str): Human-readable string with info on the action perfomed ...
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"} def add_deps(self, deps): """ Add a list of dependencies to ...
Remove a list of dependencies from the :class:`Node`. Args: deps: List of :class:`Dependency` objects specifying the dependencies of the node. def remove_deps(self, deps): """ Remove a list of dependencies from the :class:`Node`. Args: deps: List of :class:`De...
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` .. note:: This routine assumes the entire flow has been allocated. def get_children(self): """ Return the list of nodes in the :class:`Flow` that depends on this :class:`Node` .. note:: ...
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): ...
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", "usepawu") def get_vars_dataframe(self, *varnames): "...
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> def get_graphviz_dirtree(self, engine="automatic", **kwargs): """ Generate directory graph ...
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 level of the Task for testing purposes. By...
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 handlers: explicit list of :class:`EventHandler` instances. This...
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...
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 is in spectator mode. if any receiver raise...
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. def get_message(self, metadata=False, asctime=True): """ Return the message aft...
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.app...
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 ...
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 i...
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_l...
Generate a movie from a sequence of structures using vtk and ffmpeg. Args: structures ([Structure]): sequence of structures output_filename (str): filename for structure output. defaults to movie.mp4 zoom (float): A zoom to be applied to the visualizer. Defaults to 1.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. def rotate_view(self, axis_ind=0, angle=0): """ Rotate the camera view. Args: axis_ind: Index of axis to rotate. ...
Save render window to an image. Arguments: filename: filename to save to. Defaults to image.png. magnification: magnification. Use it to render high res images. image_format: choose between jpeg, png. Png is the default. def ...
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. def redraw(self, reset_camera=False): """ Redraw the render window. Args: reset_camera: Set to True...
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 s...
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. to_unit_cell: Whether or not to fall back sites into the unit cell. def set_structure(sel...
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. Args: site: Site to add. def ...
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. def add_text(self, coords, text, color=(0, 0, 0)): """ Add text at a coordinate. Args: coords: Coor...
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. def add_line(self, start, end, color=(0.5, 0.5, 0.5), width=1): """ Ad...
Adds a polyhedron. Args: neighbors: Neighbors of the polyhedron (the vertices). center: The atom in the center of the polyhedron. color: Color for text as RGB. opacity: Opacity of the polyhedron draw_edges: If set to True, the a line will be drawn at ...
Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be drawn. color: Color for triangle as RGB. center: The "central atom" of the triangle opacity: opacity of the triangle draw_edges: If set to True, the a l...
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 opacity: Opacity of the tubes representing the bonds radius: Radius of tube s representing th...
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 = ...
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...
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(s...
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 ax (axes): matplotlib axes with which to visualize scale (float): radius scaling for sites repeat (int): number of repea...
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. Args: structure (Structure): structure from which...
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 surface sites height (float): threshold in angstroms of distance from topmost ...
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) su...
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 def get_extended_surface_mesh(self, repeat=(5, 5, 1)): """ Gets an extended surface mesh for to u...
Finds surface sites according to the above algorithm. Returns a list of corresponding cartesian coordinates. Args: distance (float): distance from the coordinating ensemble of atoms along the miller index for the site (i. e. the distance from the slab itself...
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 as input to in_coord_list_pbc for dupl. checking def symm_red...
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 def near_reduce(self, coords_set, threshold=1e-4): """ Prunes coordinate set for coord...
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 of ints): list of ints from which to select sites from site list ...