INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Adds a dos for plotting.
def add_dos(self, label, dos): """ Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: PhononDos object """ densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.d...
Add a dictionary of doses with an optional sorting function for the keys.
def add_dos_dict(self, dos_dict, key_sort_func=None): """ Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """ if key_sort_func:...
Get a matplotlib plot showing the DOS.
def get_plot(self, xlim=None, ylim=None, units="thz"): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequen...
Show the plot using matplotlib.
def show(self, xlim=None, ylim=None, units="thz"): """ Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequencies. Accep...
utility private method to add ticks to a band structure
def _maketicks(self, plt): """ utility private method to add ticks to a band structure """ ticks = self.get_ticks() # Sanitize only plot the uniq values uniq_d = [] uniq_l = [] temp_ticks = list(zip(ticks['distance'], ticks['label'])) for i in rang...
Get the data nicely formatted for a plot
def bs_plot_data(self): """ Get the data nicely formatted for a plot Returns: A dict of the following format: ticks: A dict with the 'distances' at which there is a qpoint (the x axis) and the labels (None if no label) frequencies: A list (one el...
Get a matplotlib object for the bandstructure plot.
def get_plot(self, ylim=None, units="thz"): """ Get a matplotlib object for the bandstructure plot. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. units: units for the frequencies. Accepted values thz, ev, mev, ha,...
Save matplotlib plot to a file.
def save_plot(self, filename, img_format="eps", ylim=None, units="thz"): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. units: units fo...
Get all ticks and labels for a band structure plot.
def get_ticks(self): """ Get all ticks and labels for a band structure plot. Returns: A dict with 'distance': a list of distance at which ticks should be set and 'label': a list of label for each of those ticks. """ tick_distance = [] tick_labels ...
plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the PhononBSPlotter
def plot_compare(self, other_plotter): """ plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the Ph...
plot the Brillouin zone
def plot_brillouin(self): """ plot the Brillouin zone """ # get labels and lines labels = {} for q in self._bs.qpoints: if q.label: labels[q.label] = q.frac_coords lines = [] for b in self._bs.branches: lines.appen...
Plots a thermodynamic property for a generic function from a PhononDos instance.
def _plot_thermo(self, func, temperatures, factor=1, ax=None, ylabel=None, label=None, ylim=None, **kwargs): """ Plots a thermodynamic property for a generic function from a PhononDos instance. Args: func: the thermodynamic function to be used to calculate the property t...
Plots the constant volume specific heat C_v in a temperature range.
def plot_cv(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the constant volume specific heat C_v in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis l...
Plots the vibrational entrpy in a temperature range.
def plot_entropy(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the vibrational entrpy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. ...
Plots the vibrational internal energy in a temperature range.
def plot_internal_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the vibrational internal energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y...
Plots the vibrational contribution to the Helmoltz free energy in a temperature range.
def plot_helmholtz_free_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the vibrational contribution to the Helmoltz free energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ...
Plots all the thermodynamic properties in a temperature range.
def plot_thermodynamic_properties(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots all the thermodynamic properties in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specif...
Create a dictionary representation of a PWInput object Returns: dict
def as_dict(self): """ Create a dictionary representation of a PWInput object Returns: dict """ pwinput_dict = {'structure': self.structure.as_dict(), 'pseudo': self.pseudo, 'sections': self.sections, ...
Load a PWInput object from a dictionary. Args: pwinput_dict ( dict ): dictionary with PWInput data Returns: PWInput object
def from_dict(cls, pwinput_dict): """ Load a PWInput object from a dictionary. Args: pwinput_dict (dict): dictionary with PWInput data Returns: PWInput object """ pwinput = cls(structure=Structure.from_dict(pwinput_dict['struc...
Write the PWSCF input file.
def write_file(self, filename): """ Write the PWSCF input file. Args: filename (str): The string filename to output to. """ with open(filename, "w") as f: f.write(self.__str__())
Reads an PWInput object from a string.
def from_string(string): """ Reads an PWInput object from a string. Args: string (str): PWInput string Returns: PWInput object """ lines = list(clean_lines(string.splitlines())) def input_mode(line): if line[0] == "&": ...
Static helper method to convert PWINPUT parameters to proper type e. g. integers floats etc.
def proc_val(key, val): """ Static helper method to convert PWINPUT parameters to proper type, e.g., integers, floats, etc. Args: key: PWINPUT parameter key val: Actual value of PWINPUT parameter. """ float_keys = ('etot_conv_thr','forc_conv_thr',...
General pattern reading. Uses monty s regrep method. Takes the same arguments.
def read_pattern(self, patterns, reverse=False, terminate_on_match=False, postprocess=str): """ General pattern reading. Uses monty's regrep method. Takes the same arguments. Args: patterns (dict): A dict of patterns, e.g., {"energy": r"e...
Print to the given stream the template of the: class: QueueAdapter of type qtype.
def show_qparams(qtype, stream=sys.stdout): """Print to the given stream the template of the :class:`QueueAdapter` of type `qtype`.""" for cls in all_subclasses(QueueAdapter): if cls.QTYPE == qtype: return stream.write(cls.QTEMPLATE) raise ValueError("Cannot find class associated to qtype %s" % qty...
Return the concrete: class: QueueAdapter class from a string. Note that one can register a customized version with:
def make_qadapter(**kwargs): """ Return the concrete :class:`QueueAdapter` class from a string. Note that one can register a customized version with: .. example:: from qadapters import SlurmAdapter class MyAdapter(SlurmAdapter): QTYPE = "myslurm" # Add your cus...
Build and return a string with the command required to launch executable with the qadapter qad.
def string_to_run(self, qad, executable, stdin=None, stdout=None, stderr=None, exec_args=None): """ Build and return a string with the command required to launch `executable` with the qadapter `qad`. Args qad: Qadapter instance. executable (str): Executable name or path ...
Convert an object into a OmpEnv
def as_ompenv(cls, obj): """Convert an object into a OmpEnv""" if isinstance(obj, cls): return obj if obj is None: return cls() return cls(**obj)
Provides a simple though not complete dict serialization of the object ( OMP missing not all limits are kept in the dictionary... other things to be checked )
def as_dict(self): """ Provides a simple though not complete dict serialization of the object (OMP missing, not all limits are kept in the dictionary, ... other things to be checked) Raise: `ValueError` if errors. """ if self.has_omp: raise NotImp...
Check if the keys specified by the user in qparams are supported.
def validate_qparams(self): """ Check if the keys specified by the user in qparams are supported. Raise: `ValueError` if errors. """ # No validation for ShellAdapter. if isinstance(self, ShellAdapter): return # Parse the template so that we know the ...
Save submission
def record_launch(self, queue_id): # retcode): """Save submission""" self.launches.append( AttrDict(queue_id=queue_id, mpi_procs=self.mpi_procs, omp_threads=self.omp_threads, mem_per_proc=self.mem_per_proc, timelimit=self.timelimit)) return len(self.launches)
Validate the parameters of the run. Raises self. Error if invalid parameters.
def validate(self): """Validate the parameters of the run. Raises self.Error if invalid parameters.""" errors = [] app = errors.append if not self.hint_cores >= self.mpi_procs * self.omp_threads >= self.min_cores: app("self.hint_cores >= mpi_procs * omp_threads >= self.min_c...
True if the qadapter in principle is able to run the: class: ParalConf pconf
def can_run_pconf(self, pconf): """True if the qadapter in principle is able to run the :class:`ParalConf` pconf""" if not self.hint_cores >= pconf.num_cores >= self.min_cores: return False if not self.hw.can_use_omp_threads(self.omp_threads): return False if pconf.mem_per_proc > self.hw...
Returns ( num_nodes mpi_per_node )
def distribute(self, mpi_procs, omp_threads, mem_per_proc): """ Returns (num_nodes, mpi_per_node) Aggressive: When Open MPI thinks that it is in an exactly- or under-subscribed mode (i.e., the number of running processes is equal to or less than the number of available processors), ...
Return substitution dict for replacements into the template Subclasses may want to customize this method.
def get_subs_dict(self, qnodes=None): """ Return substitution dict for replacements into the template Subclasses may want to customize this method. """ #d = self.qparams.copy() d = self.qparams d.update(self.optimize_params(qnodes=qnodes)) # clean null val...
Return a string with the options that are passed to the resource manager.
def _make_qheader(self, job_name, qout_path, qerr_path): """Return a string with the options that are passed to the resource manager.""" # get substitution dict for replacements into the template subs_dict = self.get_subs_dict() # Set job_name and the names for the stderr and stdout of ...
Returns a ( multi - line ) String representing the queue script e. g. PBS script. Uses the template_file along with internal parameters to create the script.
def get_script_str(self, job_name, launch_dir, executable, qout_path, qerr_path, stdin=None, stdout=None, stderr=None, exec_args=None): """ Returns a (multi-line) String representing the queue script, e.g. PBS script. Uses the template_file along with internal parameters t...
Public API: wraps the concrete implementation _submit_to_queue
def submit_to_queue(self, script_file): """ Public API: wraps the concrete implementation _submit_to_queue Raises: `self.MaxNumLaunchesError` if we have already tried to submit the job max_num_launches `self.Error` if generic error """ if not os.path.exis...
returns the number of jobs in the queue probably using subprocess or shutil to call a command like qstat. returns None when the number of jobs cannot be determined.
def get_njobs_in_queue(self, username=None): """ returns the number of jobs in the queue, probably using subprocess or shutil to call a command like 'qstat'. returns None when the number of jobs cannot be determined. Args: username: (str) the username of the jobs to count (d...
Method to increase the amount of memory asked for by factor. Return: new memory if success 0 if memory cannot be increased.
def more_mem_per_proc(self, factor=1): """ Method to increase the amount of memory asked for, by factor. Return: new memory if success, 0 if memory cannot be increased. """ base_increase = 2000 old_mem = self.mem_per_proc new_mem = old_mem + factor*base_increase ...
Method to increase the amount of memory overheaded asked for the master node. Return: new master memory overhead if success 0 if it cannot be increased.
def more_master_mem_overhead(self, mem_increase_mb=1000): """ Method to increase the amount of memory overheaded asked for the master node. Return: new master memory overhead if success, 0 if it cannot be increased. """ old_master_mem_overhead = self.master_mem_overhead n...
Method to increase the number of MPI procs. Return: new number of processors if success 0 if processors cannot be increased.
def more_cores(self, factor=1): """ Method to increase the number of MPI procs. Return: new number of processors if success, 0 if processors cannot be increased. """ # TODO : find a formula that works for all max_cores if self.max_cores > 40: base_increase = 4 *...
Method to increase the wall time
def more_time(self, factor=1): """ Method to increase the wall time """ base_increase = int(self.timelimit_hard / 10) new_time = self.timelimit + base_increase*factor print('qadapter: trying to increase time') if new_time < self.timelimit_hard: self.s...
Set the memory per process in megabytes
def set_mem_per_proc(self, mem_mb): """Set the memory per process in megabytes""" super().set_mem_per_proc(mem_mb) self.qparams["mem_per_cpu"] = self.mem_per_proc
Select is not the most intuitive command. For more info see:
def get_select(self, ret_dict=False, qnodes=None, memory_policy=None): """ Select is not the most intuitive command. For more info see: * http://www.cardiff.ac.uk/arcca/services/equipment/User-Guide/pbs.html * https://portal.ivec.org/docs/Supercomputers/PBS_Pro """ ...
Submit a job script to the queue.
def _submit_to_queue(self, script_file): """Submit a job script to the queue.""" if sys.version_info[0] < 3: process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE) else: # need string not bytes so must use universal_newlines process = Popen(['qsub', ...
Set the number of CPUs used for MPI.
def set_mpi_procs(self, mpi_procs): """Set the number of CPUs used for MPI.""" QueueAdapter.set_mpi_procs(self, mpi_procs) num_nodes, rest_cores = self.hw.divmod_node(mpi_procs, omp_threads=1) if num_nodes == 0: self.qparams["nodes"] = 1 self.qparams["ppn"] = mpi...
Set the memory per process in megabytes
def set_mem_per_proc(self, mem_mb): """Set the memory per process in megabytes""" super().set_mem_per_proc(mem_mb) self.qparams["mem_per_slot"] = str(int(self.mem_per_proc)) + "M"
Limits are specified with the format hh: mm: ss ( hours: minutes: seconds )
def set_timelimit(self, timelimit): """Limits are specified with the format hh:mm:ss (hours:minutes:seconds)""" super().set_timelimit(timelimit) self.qparams["wall_clock_limit"] = qu.time2loadlever(timelimit)
Return ( bg_size ranks_per_node ) from mpi_procs and omp_threads.
def bgsize_rankspernode(self): """Return (bg_size, ranks_per_node) from mpi_procs and omp_threads.""" bg_size = int(math.ceil((self.mpi_procs * self.omp_threads)/ self.hw.cores_per_node)) bg_size = max(bg_size, 32) # TODO hardcoded ranks_per_node = int(math.ceil(self.mpi_procs / bg_size)) retu...
[ a [ 0 ] b [ 0 ]... a [ 1 ] b [ 1 ]... a [ n ] b [ n ]... ] >>> alternate ( [ 1 4 ] [ 2 5 ] [ 3 6 ] ) [ 1 2 3 4 5 6 ]
def alternate(*iterables): """ [a[0], b[0], ... , a[1], b[1], ..., a[n], b[n] ...] >>> alternate([1,4], [2,5], [3,6]) [1, 2, 3, 4, 5, 6] """ items = [] for tup in zip(*iterables): items.extend([item for item in tup]) return items
Scan directory tree starting from top look for files with extension ext and parse timing data.
def walk(cls, top=".", ext=".abo"): """ Scan directory tree starting from top, look for files with extension `ext` and parse timing data. Return: (parser, paths, okfiles) where `parser` is the new object, `paths` is the list of files found and `okfiles` is the li...
Read and parse a filename or a list of filenames. Files that cannot be opened are ignored. A single filename may also be given.
def parse(self, filenames): """ Read and parse a filename or a list of filenames. Files that cannot be opened are ignored. A single filename may also be given. Return: list of successfully read files. """ filenames = list_strings(filenames) read_ok = [] ...
Parse the TIMER section
def _read(self, fh, fname): """Parse the TIMER section""" if fname in self._timers: raise self.Error("Cannot overwrite timer associated to: %s " % fname) def parse_line(line): """Parse single line.""" name, vals = line[:25], line[25:].split() try:...
Return the list of timers associated to the given filename and MPI rank mpi_rank.
def timers(self, filename=None, mpi_rank="0"): """ Return the list of timers associated to the given `filename` and MPI rank mpi_rank. """ if filename is not None: return [self._timers[filename][mpi_rank]] else: return [self._timers[filename][mpi_rank] for...
Return the names of sections ordered by ordkey. For the time being the values are taken from the first timer.
def section_names(self, ordkey="wall_time"): """ Return the names of sections ordered by ordkey. For the time being, the values are taken from the first timer. """ section_names = [] # FIXME this is not trivial for idx, timer in enumerate(self.timers()): ...
Return the list of sections stored in self. timers () given section_name A fake section is returned if the timer does not have section_name.
def get_sections(self, section_name): """ Return the list of sections stored in self.timers() given `section_name` A fake section is returned if the timer does not have section_name. """ sections = [] for timer in self.timers(): for sect in timer.sections: ...
Analyze the parallel efficiency.
def pefficiency(self): """ Analyze the parallel efficiency. Return: :class:`ParallelEfficiency` object. """ timers = self.timers() # Number of CPUs employed in each calculation. ncpus = [timer.ncpus for timer in timers] # Find the minimum nu...
Return pandas DataFrame with the most important results stored in the timers.
def summarize(self, **kwargs): """ Return pandas DataFrame with the most important results stored in the timers. """ import pandas as pd colnames = ["fname", "wall_time", "cpu_time", "mpi_nprocs", "omp_nthreads", "mpi_rank"] frame = pd.DataFrame(columns=colnames) ...
Plot the parallel efficiency
def plot_efficiency(self, key="wall_time", what="good+bad", nmax=5, ax=None, **kwargs): """ Plot the parallel efficiency Args: key: Parallel efficiency is computed using the wall_time. what: Specifies what to plot: `good` for sections with good parallel efficiency. ...
Plot pie charts of the different timers.
def plot_pie(self, key="wall_time", minfract=0.05, **kwargs): """ Plot pie charts of the different timers. Args: key: Keyword used to extract data from timers. minfract: Don't show sections whose relative weight is less that minfract. Returns: `matpl...
Plot stacked histogram of the different timers.
def plot_stacked_hist(self, key="wall_time", nmax=5, ax=None, **kwargs): """ Plot stacked histogram of the different timers. Args: key: Keyword used to extract data from the timers. Only the first `nmax` sections with largest value are show. mmax: Maximum...
Call all plot methods provided by the parser.
def plot_all(self, show=True, **kwargs): """ Call all plot methods provided by the parser. """ figs = []; app = figs.append app(self.plot_stacked_hist(show=show)) app(self.plot_efficiency(show=show)) app(self.plot_pie(show=show)) return figs
Return a string with data in CSV format
def to_csvline(self, with_header=False): """Return a string with data in CSV format""" string = "" if with_header: string += "# " + " ".join(at for at in AbinitTimerSection.FIELDS) + "\n" string += ", ".join(str(v) for v in self.to_tuple()) + "\n" return string
Write data on file fileobj using CSV format.
def to_csv(self, fileobj=sys.stdout): """Write data on file fileobj using CSV format.""" openclose = is_string(fileobj) if openclose: fileobj = open(fileobj, "w") for idx, section in enumerate(self.sections): fileobj.write(section.to_csvline(with_header=(idx == ...
Return a table ( list of lists ) with timer data
def to_table(self, sort_key="wall_time", stop=None): """Return a table (list of lists) with timer data""" table = [list(AbinitTimerSection.FIELDS), ] ord_sections = self.order_sections(sort_key) if stop is not None: ord_sections = ord_sections[:stop] for osect in or...
Return a pandas DataFrame with entries sorted according to sort_key.
def get_dataframe(self, sort_key="wall_time", **kwargs): """ Return a pandas DataFrame with entries sorted according to `sort_key`. """ import pandas as pd frame = pd.DataFrame(columns=AbinitTimerSection.FIELDS) for osect in self.order_sections(sort_key): fra...
Return a list of values associated to a particular list of keys.
def get_values(self, keys): """ Return a list of values associated to a particular list of keys. """ if is_string(keys): return [s.__dict__[keys] for s in self.sections] else: values = [] for k in keys: values.append([s.__dict__...
Select the entries whose value [ key ] is > = minval or whose fraction [ key ] is > = minfract Return the names of the sections and the corresponding values.
def names_and_values(self, key, minval=None, minfract=None, sorted=True): """ Select the entries whose value[key] is >= minval or whose fraction[key] is >= minfract Return the names of the sections and the corresponding values. """ values = self.get_values(key) names = se...
Sort sections according to the value of key.
def order_sections(self, key, reverse=True): """Sort sections according to the value of key.""" fsort = lambda s: s.__dict__[key] return sorted(self.sections, key=fsort, reverse=reverse)
Plot pie chart for this timer.
def pie(self, key="wall_time", minfract=0.05, ax=None, **kwargs): """ Plot pie chart for this timer. Args: key: Keyword used to extract data from the timer. minfract: Don't show sections whose relative weight is less that minfract. ax: matplotlib :class:`Axes...
Returns ASE Atoms object from pymatgen structure.
def get_atoms(structure, **kwargs): """ Returns ASE Atoms object from pymatgen structure. Args: structure: pymatgen.core.structure.Structure **kwargs: other keyword args to pass into the ASE Atoms constructor Returns: ASE Atoms object """ ...
Returns pymatgen structure from ASE Atoms.
def get_structure(atoms, cls=None): """ Returns pymatgen structure from ASE Atoms. Args: atoms: ASE Atoms object cls: The Structure class to instantiate (defaults to pymatgen structure) Returns: Equivalent pymatgen.core.structure.Structure ""...
Returns the densities but with a Gaussian smearing of std dev sigma applied.
def get_smeared_densities(self, sigma): """ Returns the densities, but with a Gaussian smearing of std dev sigma applied. Args: sigma: Std dev of Gaussian smearing function. Returns: Gaussian-smeared densities. """ from scipy.ndimage.fil...
Json - serializable dict representation of PhononDos.
def as_dict(self): """ Json-serializable dict representation of PhononDos. """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "frequencies": list(self.frequencies), "densities": list(self.densities)}
Index of the first point for which the freqencies are equal or greater than zero.
def ind_zero_freq(self): """ Index of the first point for which the freqencies are equal or greater than zero. """ ind = np.searchsorted(self.frequencies, 0) if ind >= len(self.frequencies): raise ValueError("No positive frequencies found") return ind
Constant volume specific heat C_v at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/ ( K * mol - c ). A mol - c is the abbreviation of a mole - cell that is the number of Avogadro times the atoms in a unit cell. To compare with experimental data the result sh...
def cv(self, t, structure=None): """ Constant volume specific heat C_v at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the a...
Vibrational entropy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/ ( K * mol - c ). A mol - c is the abbreviation of a mole - cell that is the number of Avogadro times the atoms in a unit cell. To compare with experimental data the result should be divide...
def entropy(self, t, structure=None): """ Vibrational entropy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a...
Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/ mol - c. A mol - c is the abbreviation of a mole - cell that is the number of Avogadro times the atoms in a unit cell. To compare with experimental data the result s...
def internal_energy(self, t, structure=None): """ Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Av...
Phonon contribution to the Helmholtz free energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/ mol - c. A mol - c is the abbreviation of a mole - cell that is the number of Avogadro times the atoms in a unit cell. To compare with experimental data the re...
def helmholtz_free_energy(self, t, structure=None): """ Phonon contribution to the Helmholtz free energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number ...
Zero point energy energy of the system. Only positive frequencies will be used. Result in J/ mol - c. A mol - c is the abbreviation of a mole - cell that is the number of Avogadro times the atoms in a unit cell. To compare with experimental data the result should be divided by the number of unit formulas in the cell. I...
def zero_point_energy(self, structure=None): """ Zero point energy energy of the system. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with experimental dat...
Get element projected Dos.
def get_element_dos(self): """ Get element projected Dos. Returns: dict of {Element: Dos} """ el_dos = {} for site, atom_dos in self.pdos.items(): el = site.specie if el not in el_dos: el_dos[el] = np.array(atom_dos) ...
Returns CompleteDos object from dict representation.
def from_dict(cls, d): """ Returns CompleteDos object from dict representation. """ tdos = PhononDos.from_dict(d) struct = Structure.from_dict(d["structure"]) pdoss = {} for at, pdos in zip(struct, d["pdos"]): pdoss[at] = pdos return cls(struc...
Json - serializable dict representation of CompletePhononDos.
def as_dict(self): """ Json-serializable dict representation of CompletePhononDos. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "structure": self.structure.as_dict(), "frequencies": list(self.frequencies), ...
Sorts a dict by value.
def sort_dict(d, key=None, reverse=False): """ Sorts a dict by value. Args: d: Input dictionary key: Function which takes an tuple (key, object) and returns a value to compare and sort by. By default, the function compares the values of the dict i.e. key = lambda t :...
Uses enumerate max and min to return the indices of the values in a list with the maximum and minimum value:
def min_max_indexes(seq): """ Uses enumerate, max, and min to return the indices of the values in a list with the maximum and minimum value: """ l = sorted(enumerate(seq), key=lambda s: s[1]) return l[0][0], l[-1][0]
True if values are stricly increasing.
def strictly_increasing(values): """True if values are stricly increasing.""" return all(x < y for x, y in zip(values, values[1:]))
True if values are stricly decreasing.
def strictly_decreasing(values): """True if values are stricly decreasing.""" return all(x > y for x, y in zip(values, values[1:]))
True if values are not increasing.
def non_increasing(values): """True if values are not increasing.""" return all(x >= y for x, y in zip(values, values[1:]))
True if values are not decreasing.
def non_decreasing(values): """True if values are not decreasing.""" return all(x <= y for x, y in zip(values, values[1:]))
Returns False if values are not monotonic ( decreasing|increasing ). mode is < for a decreasing sequence > for an increasing sequence. Two numbers are considered equal if they differ less that atol.
def monotonic(values, mode="<", atol=1.e-8): """ Returns False if values are not monotonic (decreasing|increasing). mode is "<" for a decreasing sequence, ">" for an increasing sequence. Two numbers are considered equal if they differ less that atol. .. warning: Not very efficient for large...
Rounds a number rounded to a specific number of significant figures instead of to a specific precision.
def round_to_sigfigs(num, sigfigs): """ Rounds a number rounded to a specific number of significant figures instead of to a specific precision. """ if type(sigfigs) != int: raise TypeError("Number of significant figures must be integer.") elif sigfigs < 1: raise ValueError("Numbe...
Given a symmetric matrix in upper triangular matrix form as flat array indexes as: [ A_xx A_yy A_zz A_xy A_xz A_yz ] This will generate the full matrix: [[ A_xx A_xy A_xz ] [ A_xy A_yy A_yz ] [ A_xz A_yz A_zz ]
def make_symmetric_matrix_from_upper_tri(val): """ Given a symmetric matrix in upper triangular matrix form as flat array indexes as: [A_xx,A_yy,A_zz,A_xy,A_xz,A_yz] This will generate the full matrix: [[A_xx,A_xy,A_xz],[A_xy,A_yy,A_yz],[A_xz,A_yz,A_zz] """ idx = [0,3,4,1,5,2] val = np.a...
Returns a: class: Work object that performs G0W0 calculations for the given the material.
def g0w0_extended_work(structure, pseudos, kppa, nscf_nband, ecuteps, ecutsigx, scf_nband, accuracy="normal", spin_mode="polarized", smearing="fermi_dirac:0.1 eV", response_models=["godby"], charge=0.0, inclvkb=2, scr_nband=None, sigma_nband=None, workdir=None, manager=None...
Gets information on the components in a bonded structure.
def get_structure_components(bonded_structure, inc_orientation=False, inc_site_ids=False, inc_molecule_graph=False): """ Gets information on the components in a bonded structure. Correctly determines the dimensionality of all structures, regardless of structure type or impr...
Calculates the dimensionality of the component containing the given site.
def calculate_dimensionality_of_site(bonded_structure, site_index, inc_vertices=False): """ Calculates the dimensionality of the component containing the given site. Implements directly the modified breadth-first-search algorithm described in Algorithm 1 of: P....
Converts a zero - dimensional networkx Graph object into a MoleculeGraph.
def zero_d_graph_to_molecule_graph(bonded_structure, graph): """ Converts a zero-dimensional networkx Graph object into a MoleculeGraph. Implements a similar breadth-first search to that in calculate_dimensionality_of_site(). Args: bonded_structure (StructureGraph): A structure with bonds,...
Finds bonded atoms and returns a adjacency matrix of bonded atoms.
def find_connected_atoms(struct, tolerance=0.45, ldict=JmolNN().el_radius): """ Finds bonded atoms and returns a adjacency matrix of bonded atoms. Author: "Gowoon Cheon" Email: "gcheon@stanford.edu" Args: struct (Structure): Input structure tolerance: length in angstroms used in fi...
Finds bonded clusters of atoms in the structure with periodic boundary conditions.
def find_clusters(struct, connected_matrix): """ Finds bonded clusters of atoms in the structure with periodic boundary conditions. If there are atoms that are not bonded to anything, returns [0,1,0]. (For faster computation time) Author: "Gowoon Cheon" Email: "gcheon@stanford.edu" Ar...
returns the deviatoric component of the stress
def deviator_stress(self): """ returns the deviatoric component of the stress """ if not self.is_symmetric: raise warnings.warn("The stress tensor is not symmetric, " "so deviator stress will not be either") return self - self.mean_stre...
calculates the first Piola - Kirchoff stress
def piola_kirchoff_1(self, def_grad): """ calculates the first Piola-Kirchoff stress Args: def_grad (3x3 array-like): deformation gradient tensor """ if not self.is_symmetric: raise ValueError("The stress tensor is not symmetric, \ ...