Instruction:
Create a Python 3 function for
finding the stable entry at a given pH and V.

Response:
def find_stable_entry(self, pH, V):
        """
        Finds stable entry at a pH,V condition
        Args:
            pH (float): pH to find stable entry
            V (float): V to find stable entry

        Returns:

        """
        energies_at_conditions = [e.normalized_energy_at_conditions(pH, V)
                                  for e in self.stable_entries]
        return self.stable_entries[np.argmin(energies_at_conditions)]


Instruction:
Write a Python 3 script for
finding the decomposition to most stable entry

Response:
def get_decomposition_energy(self, entry, pH, V):
        """
        Finds decomposition to most stable entry

        Args:
            entry (PourbaixEntry): PourbaixEntry corresponding to
                compound to find the decomposition for
            pH (float): pH at which to find the decomposition
            V (float): voltage at which to find the decomposition

        Returns:
            reaction corresponding to the decomposition
        """
        # Find representative multientry
        if self._multielement and not isinstance(entry, MultiEntry):
            possible_entries = self._generate_multielement_entries(
                self._filtered_entries, forced_include=[entry])

            # Filter to only include materials where the entry is only solid
            if entry.phase_type == "solid":
                possible_entries = [e for e in possible_entries
                                    if e.phase_type.count("Solid") == 1]
            possible_energies = [e.normalized_energy_at_conditions(pH, V)
                                 for e in possible_entries]
        else:
            possible_energies = [entry.normalized_energy_at_conditions(pH, V)]

        min_energy = np.min(possible_energies, axis=0)

        # Find entry and take the difference
        hull = self.get_hull_energy(pH, V)
        return min_energy - hull


Instruction:
How would you implement a function in Python 3 that
shows the pourbaix plot of the pourbaix plot of the national product of the pourbaix data

Response:
def show(self, *args, **kwargs):
        """
        Shows the pourbaix plot

        Args:
            *args: args to get_pourbaix_plot
            **kwargs: kwargs to get_pourbaix_plot

        Returns:
            None
        """
        plt = self.get_pourbaix_plot(*args, **kwargs)
        plt.show()


Instruction:
Can you generate the documentation for the following Python 3 function
def get_pourbaix_plot(self, limits=None, title="",
                          label_domains=True, plt=None):
        """
        Plot Pourbaix diagram.

        Args:
            limits: 2D list containing limits of the Pourbaix diagram
                of the form [[xlo, xhi], [ylo, yhi]]
            title (str): Title to display on plot
            label_domains (bool): whether to label pourbaix domains
            plt (pyplot): Pyplot instance for plotting

        Returns:
            plt (pyplot) - matplotlib plot object with pourbaix diagram
        """
        if limits is None:
            limits = [[-2, 16], [-3, 3]]

        plt = plt or pretty_plot(16)

        xlim = limits[0]
        ylim = limits[1]

        h_line = np.transpose([[xlim[0], -xlim[0] * PREFAC],
                               [xlim[1], -xlim[1] * PREFAC]])
        o_line = np.transpose([[xlim[0], -xlim[0] * PREFAC + 1.23],
                               [xlim[1], -xlim[1] * PREFAC + 1.23]])
        neutral_line = np.transpose([[7, ylim[0]], [7, ylim[1]]])
        V0_line = np.transpose([[xlim[0], 0], [xlim[1], 0]])

        ax = plt.gca()
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        lw = 3
        plt.plot(h_line[0], h_line[1], "r--", linewidth=lw)
        plt.plot(o_line[0], o_line[1], "r--", linewidth=lw)
        plt.plot(neutral_line[0], neutral_line[1], "k-.", linewidth=lw)
        plt.plot(V0_line[0], V0_line[1], "k-.", linewidth=lw)

        for entry, vertices in self._pd._stable_domain_vertices.items():
            center = np.average(vertices, axis=0)
            x, y = np.transpose(np.vstack([vertices, vertices[0]]))
            plt.plot(x, y, 'k-', linewidth=lw)
            if label_domains:
                plt.annotate(generate_entry_label(entry), center, ha='center',
                             va='center', fontsize=20, color="b")

        plt.xlabel("pH")
        plt.ylabel("E (V)")
        plt.title(title, fontsize=20, fontweight='bold')
        return plt

Response: Returns a matplotlib plot object with the pourbaix diagram.


Instruction:
Here you have a function in Python 3, explain what it does
def apply_transformation(self, structure, return_ranked_list=False):
        num_remove_dict = {}
        total_combis = 0
        for indices, frac in zip(self.indices, self.fractions):
            num_to_remove = len(indices) * frac
            if abs(num_to_remove - int(round(num_to_remove))) > 1e-3:
                raise ValueError("Fraction to remove must be consistent with "
                                 "integer amounts in structure.")
            else:
                num_to_remove = int(round(num_to_remove))
            num_remove_dict[tuple(indices)] = num_to_remove
            n = len(indices)
            total_combis += int(round(math.factorial(n) /
                                      math.factorial(num_to_remove) /
                                      math.factorial(n - num_to_remove)))

        self.logger.debug("Total combinations = {}".format(total_combis))

        try:
            num_to_return = int(return_ranked_list)
        except ValueError:
            num_to_return = 1

        num_to_return = max(1, num_to_return)
        self.logger.debug("Will return {} best structures."
                          .format(num_to_return))

        if self.algo == PartialRemoveSitesTransformation.ALGO_FAST:
            all_structures = self.fast_ordering(structure, num_remove_dict,
                                                num_to_return)
        elif self.algo == PartialRemoveSitesTransformation.ALGO_COMPLETE:
            all_structures = self.complete_ordering(structure, num_remove_dict)
        elif self.algo == PartialRemoveSitesTransformation.ALGO_BEST_FIRST:
            all_structures = self.best_first_ordering(structure,
                                                      num_remove_dict)
        elif self.algo == PartialRemoveSitesTransformation.ALGO_ENUMERATE:
            all_structures = self.enumerate_ordering(structure)
        else:
            raise ValueError("Invalid algo.")

        opt_s = all_structures[0]["structure"]
        return opt_s if not return_ranked_list \
            else all_structures[0:num_to_return]

Response: Applies the transformation to the structure.


Instruction:
Given the following Python 3 function, write the documentation
def apply_transformation(self, structure):
        new_structure = structure.copy()
        for prop in self.site_properties.keys():
            new_structure.add_site_property(prop, self.site_properties[prop])
        return new_structure

Response: Applies the transformation to the structure.


Instruction:
Create a Python 3 function for
writing the input files for a LAMMPS run.

Response:
def write_lammps_inputs(output_dir, script_template, settings=None,
                        data=None, script_filename="in.lammps",
                        make_dir_if_not_present=True, **kwargs):
    """
    Writes input files for a LAMMPS run. Input script is constructed
    from a str template with placeholders to be filled by custom
    settings. Data file is either written from a LammpsData
    instance or copied from an existing file if read_data cmd is
    inspected in the input script. Other supporting files are not
    handled at the moment.

    Args:
        output_dir (str): Directory to output the input files.
        script_template (str): String template for input script with
            placeholders. The format for placeholders has to be
            '$variable_name', e.g., '$temperature'
        settings (dict): Contains values to be written to the
            placeholders, e.g., {'temperature': 1}. Default to None.
        data (LammpsData or str): Data file as a LammpsData instance or
            path to an existing data file. Default to None, i.e., no
            data file supplied. Useful only when read_data cmd is in
            the script.
        script_filename (str): Filename for the input script.
        make_dir_if_not_present (bool): Set to True if you want the
            directory (and the whole path) to be created if it is not
            present.
        **kwargs: kwargs supported by LammpsData.write_file.

    Examples:
        >>> eam_template = '''units           metal
        ... atom_style      atomic
        ...
        ... lattice         fcc 3.615
        ... region          box block 0 20 0 20 0 20
        ... create_box      1 box
        ... create_atoms    1 box
        ...
        ... pair_style      eam
        ... pair_coeff      1 1 Cu_u3.eam
        ...
        ... velocity        all create $temperature 376847 loop geom
        ...
        ... neighbor        1.0 bin
        ... neigh_modify    delay 5 every 1
        ...
        ... fix             1 all nvt temp $temperature $temperature 0.1
        ...
        ... timestep        0.005
        ...
        ... run             $nsteps'''
        >>> write_lammps_inputs('.', eam_template, settings={'temperature': 1600.0, 'nsteps': 100})
        >>> with open('in.lammps') as f:
        ...     script = f.read()
        ...
        >>> print(script)
        units           metal
        atom_style      atomic

        lattice         fcc 3.615
        region          box block 0 20 0 20 0 20
        create_box      1 box
        create_atoms    1 box

        pair_style      eam
        pair_coeff      1 1 Cu_u3.eam

        velocity        all create 1600.0 376847 loop geom

        neighbor        1.0 bin
        neigh_modify    delay 5 every 1

        fix             1 all nvt temp 1600.0 1600.0 0.1

        timestep        0.005

        run             100

    """
    variables = {} if settings is None else settings
    template = Template(script_template)
    input_script = template.safe_substitute(**variables)
    if make_dir_if_not_present and not os.path.exists(output_dir):
        os.makedirs(output_dir)
    with open(os.path.join(output_dir, script_filename), "w") as f:
        f.write(input_script)
    read_data = re.search(r"read_data\s+(.*)\n", input_script)
    if read_data:
        data_filename = read_data.group(1).split()[0]
        if isinstance(data, LammpsData):
            data.write_file(os.path.join(output_dir, data_filename), **kwargs)
        elif isinstance(data, str) and os.path.exists(data):
            shutil.copyfile(data, os.path.join(output_dir, data_filename))
        else:
            warnings.warn("No data file supplied. Skip writing %s."
                          % data_filename)


Instruction:
Create a Python 3 function for
writing all input files for the current instance of a LammpsData object.

Response:
def write_inputs(self, output_dir, **kwargs):
        """
        Writes all input files (input script, and data if needed).
        Other supporting files are not handled at this moment.

        Args:
            output_dir (str): Directory to output the input files.
            **kwargs: kwargs supported by LammpsData.write_file.

        """
        write_lammps_inputs(output_dir=output_dir,
                            script_template=self.script_template,
                            settings=self.settings, data=self.data,
                            script_filename=self.script_filename, **kwargs)


Instruction:
Given the following Python 3 function, write the documentation
def generate_reciprocal_vectors_squared(a1, a2, a3, encut):
    for vec in genrecip(a1, a2, a3, encut):
        yield np.dot(vec, vec)

Response: Generates the reciprocal vectors squared of the specied base - set of lattice vectors.


Instruction:
Can you create a Python 3 function that
returns the closest site to the input position for both bulk and defect structures

Response:
def closestsites(struct_blk, struct_def, pos):
    """
    Returns closest site to the input position
    for both bulk and defect structures
    Args:
        struct_blk: Bulk structure
        struct_def: Defect structure
        pos: Position
    Return: (site object, dist, index)
    """
    blk_close_sites = struct_blk.get_sites_in_sphere(pos, 5, include_index=True)
    blk_close_sites.sort(key=lambda x: x[1])
    def_close_sites = struct_def.get_sites_in_sphere(pos, 5, include_index=True)
    def_close_sites.sort(key=lambda x: x[1])

    return blk_close_sites[0], def_close_sites[0]


Instruction:
How would you implement a function in Python 3 that
returns the density at the reciprocal vector.

Response:
def rho_rec(self, g2):
        """
        Reciprocal space model charge value
        for input squared reciprocal vector.
        Args:
            g2: Square of reciprocal vector

        Returns:
            Charge density at the reciprocal vector magnitude
        """
        return (self.expnorm / np.sqrt(1 + self.gamma2 * g2) + (
            1 - self.expnorm) * np.exp(-0.25 * self.beta2 * g2))


Instruction:
Write a Python 3 function for
returning the limit of the reciprocal vector 0.

Response:
def rho_rec_limit0(self):
        """
        Reciprocal space model charge value
        close to reciprocal vector 0 .
        rho_rec(g->0) -> 1 + rho_rec_limit0 * g^2
        """
        return -2 * self.gamma2 * self.expnorm - 0.25 * self.beta2 * (
            1 - self.expnorm)


Instruction:
How would you explain what the following Python 3 function does
def make_supercells_with_defects(self, scaling_matrix):
        scs = []
        sc = self._structure.copy()
        sc.make_supercell(scaling_matrix)
        scs.append(sc)
        for ids, defect_site in enumerate(self._defect_sites):
            sc_with_inter = sc.copy()
            sc_with_inter.append(
                defect_site.species_string,
                defect_site.frac_coords,
                coords_are_cartesian=False,
                validate_proximity=False,
                properties=None)
            if not sc_with_inter:
                raise RuntimeError(
                    "could not generate supercell with" " interstitial {}".format(
                        ids + 1))
            scs.append(sc_with_inter.copy())
        return scs

Response: Generates a sequence of supercells in which each supercell contains a single interstitial and a single interstitial.


Instruction:
Write a Python 3 function that can
cluster nodes that are too close together using a tolerance.

Response:
def cluster_nodes(self, tol=0.2):
        """
        Cluster nodes that are too close together using a tol.

        Args:
            tol (float): A distance tolerance. PBC is taken into account.
        """
        lattice = self.structure.lattice

        vfcoords = [v.frac_coords for v in self.vnodes]

        # Manually generate the distance matrix (which needs to take into
        # account PBC.
        dist_matrix = np.array(lattice.get_all_distances(vfcoords, vfcoords))
        dist_matrix = (dist_matrix + dist_matrix.T) / 2
        for i in range(len(dist_matrix)):
            dist_matrix[i, i] = 0
        condensed_m = squareform(dist_matrix)
        z = linkage(condensed_m)
        cn = fcluster(z, tol, criterion="distance")
        merged_vnodes = []
        for n in set(cn):
            poly_indices = set()
            frac_coords = []
            for i, j in enumerate(np.where(cn == n)[0]):
                poly_indices.update(self.vnodes[j].polyhedron_indices)
                if i == 0:
                    frac_coords.append(self.vnodes[j].frac_coords)
                else:
                    fcoords = self.vnodes[j].frac_coords
                    # We need the image to combine the frac_coords properly.
                    d, image = lattice.get_distance_and_image(frac_coords[0],
                                                              fcoords)
                    frac_coords.append(fcoords + image)
            merged_vnodes.append(
                VoronoiPolyhedron(lattice, np.average(frac_coords, axis=0),
                                  poly_indices, self.coords))
        self.vnodes = merged_vnodes
        logger.debug("%d vertices after combination." % len(self.vnodes))


Instruction:
Write a Python 3 script to
remove vnodes that are too close to existing atoms in the structure.

Response:
def remove_collisions(self, min_dist=0.5):
        """
        Remove vnodes that are too close to existing atoms in the structure

        Args:
            min_dist(float): The minimum distance that a vertex needs to be
                from existing atoms.
        """
        vfcoords = [v.frac_coords for v in self.vnodes]
        sfcoords = self.structure.frac_coords
        dist_matrix = self.structure.lattice.get_all_distances(vfcoords,
                                                               sfcoords)
        all_dist = np.min(dist_matrix, axis=1)
        new_vnodes = []
        for i, v in enumerate(self.vnodes):
            if all_dist[i] > min_dist:
                new_vnodes.append(v)
        self.vnodes = new_vnodes


Instruction:
Write a Python 3 script for
getting the modified structure with the voronoi nodes inserted.

Response:
def get_structure_with_nodes(self):
        """
        Get the modified structure with the voronoi nodes inserted. The
        species is set as a DummySpecie X.
        """
        new_s = Structure.from_sites(self.structure)
        for v in self.vnodes:
            new_s.append("X", v.frac_coords)
        return new_s


Instruction:
How would you explain what the following Python 3 function does
def _get_charge_distribution_df(self):
        # Fraction coordinates and corresponding indices
        axis_grid = np.array([np.array(self.chgcar.get_axis_grid(i)) /
                              self.structure.lattice.abc[i] for i in range(3)])
        axis_index = np.array([range(len(axis_grid[i])) for i in range(3)])

        data = {}

        for index in itertools.product(*axis_index):
            a, b, c = index
            f_coords = (axis_grid[0][a], axis_grid[1][b], axis_grid[2][c])
            data[f_coords] = self.chgcar.data["total"][a][b][c]

        # Fraction coordinates - charge density table
        df = pd.Series(data).reset_index()
        df.columns = ['a', 'b', 'c', 'Charge Density']
        self._charge_distribution_df = df

        return df

Response: Return a complete table of fractional coordinates - charge density.


Instruction:
Create a Python 3 function for
updating _extrema_df extrema_type and extrema_coords

Response:
def _update_extrema(self, f_coords, extrema_type, threshold_frac=None,
                        threshold_abs=None):
        """Update _extrema_df, extrema_type and extrema_coords"""

        if threshold_frac is not None:
            if threshold_abs is not None:
                logger.warning(  # Exit if both filter are set
                    "Filter can be either threshold_frac or threshold_abs!")
                return
            if threshold_frac > 1 or threshold_frac < 0:
                raise Exception("threshold_frac range is [0, 1]!")

        # Return empty result if coords list is empty
        if len(f_coords) == 0:
            df = pd.DataFrame({}, columns=['A', 'B', 'C', "Chgcar"])
            self._extrema_df = df
            self.extrema_coords = []
            logger.info("Find {} {}.".format(len(df), extrema_type))
            return

        data = {}
        unit = 1 / np.array(self.chgcar.dim)  # pixel along a, b, c

        for fc in f_coords:
            a, b, c = tuple(map(int, fc / unit))
            data[tuple(fc)] = self.chgcar.data["total"][a][b][c]

        df = pd.Series(data).reset_index()
        df.columns = ['a', 'b', 'c', 'Charge Density']
        ascending = (extrema_type == "local minima")

        if threshold_abs is None:
            threshold_frac = threshold_frac \
                if threshold_frac is not None else 1.0
            num_extrema = int(threshold_frac * len(f_coords))
            df = df.sort_values(by="Charge Density", ascending=ascending)[
                 0:num_extrema]
            df.reset_index(drop=True, inplace=True)  # reset major index
        else:  # threshold_abs is set
            df = df.sort_values(by="Charge Density", ascending=ascending)
            df = df[df["Charge Density"] <= threshold_abs] if ascending \
                else df[df["Charge Density"] >= threshold_abs]

        extrema_coords = []
        for row in df.iterrows():
            fc = np.array(row[1]["a":"c"])
            extrema_coords.append(fc)

        self._extrema_df = df
        self.extrema_type = extrema_type
        self.extrema_coords = extrema_coords
        logger.info("Find {} {}.".format(len(df), extrema_type))


Instruction:
Can you tell what is the following Python 3 function doing
def get_local_extrema(self, find_min=True, threshold_frac=None,
                          threshold_abs=None):
        """
        Get all local extrema fractional coordinates in charge density,
        searching for local minimum by default. Note that sites are NOT grouped
        symmetrically.

        Args:
            find_min (bool): True to find local minimum else maximum, otherwise
                find local maximum.

            threshold_frac (float): optional fraction of extrema shown, which
                returns `threshold_frac * tot_num_extrema` extrema fractional
                coordinates based on highest/lowest intensity.

                E.g. set 0.2 to show the extrema with 20% highest or lowest
                intensity. Value range: 0 <= threshold_frac <= 1

                Note that threshold_abs and threshold_frac should not set in the
                same time.

            threshold_abs (float): optional filter. When searching for local
                minima, intensity <= threshold_abs returns; when searching for
                local maxima, intensity >= threshold_abs returns.

                Note that threshold_abs and threshold_frac should not set in the
                same time.

        Returns:
            extrema_coords (list): list of fractional coordinates corresponding
                to local extrema.
        """
        sign, extrema_type = 1, "local maxima"

        if find_min:
            sign, extrema_type = -1, "local minima"

        # Make 3x3x3 supercell
        # This is a trick to resolve the periodical boundary issue.
        total_chg = sign * self.chgcar.data["total"]
        total_chg = np.tile(total_chg, reps=(3, 3, 3))
        coordinates = peak_local_max(total_chg, min_distance=1)

        # Remove duplicated sites introduced by supercell.
        f_coords = [coord / total_chg.shape * 3 for coord in coordinates]
        f_coords = [f - 1 for f in f_coords if
                    all(np.array(f) < 2) and all(np.array(f) >= 1)]

        # Update information
        self._update_extrema(f_coords, extrema_type,
                             threshold_frac=threshold_frac,
                             threshold_abs=threshold_abs)

        return self.extrema_coords

Response: Get all local extrema fractional coordinates in charge density.


Instruction:
How would you explain what the following Python 3 function does
def cluster_nodes(self, tol=0.2):
        lattice = self.structure.lattice
        vf_coords = self.extrema_coords

        if len(vf_coords) == 0:
            if self.extrema_type is None:
                logger.warning(
                    "Please run ChargeDensityAnalyzer.get_local_extrema first!")
                return
            new_f_coords = []
            self._update_extrema(new_f_coords, self.extrema_type)
            return new_f_coords

        # Manually generate the distance matrix (which needs to take into
        # account PBC.
        dist_matrix = np.array(lattice.get_all_distances(vf_coords, vf_coords))
        dist_matrix = (dist_matrix + dist_matrix.T) / 2

        for i in range(len(dist_matrix)):
            dist_matrix[i, i] = 0
        condensed_m = squareform(dist_matrix)
        z = linkage(condensed_m)
        cn = fcluster(z, tol, criterion="distance")
        merged_fcoords = []

        for n in set(cn):
            frac_coords = []
            for i, j in enumerate(np.where(cn == n)[0]):
                if i == 0:
                    frac_coords.append(self.extrema_coords[j])
                else:
                    f_coords = self.extrema_coords[j]
                    # We need the image to combine the frac_coords properly.
                    d, image = lattice.get_distance_and_image(frac_coords[0],
                                                              f_coords)
                    frac_coords.append(f_coords + image)
            merged_fcoords.append(np.average(frac_coords, axis=0))

        merged_fcoords = [f - np.floor(f) for f in merged_fcoords]
        merged_fcoords = [f * (np.abs(f - 1) > 1E-15) for f in merged_fcoords]
        # the second line for fringe cases like
        # np.array([ 5.0000000e-01 -4.4408921e-17  5.0000000e-01])
        # where the shift to [0,1) does not work due to float precision
        self._update_extrema(merged_fcoords, extrema_type=self.extrema_type)
        logger.debug(
            "{} vertices after combination.".format(len(self.extrema_coords)))

Response: Cluster nodes that are too close together using a tolerance.


Instruction:
Can you implement a function in Python 3 that
removes predicted sites that are too close to existing atoms in the species.

Response:
def remove_collisions(self, min_dist=0.5):
        """
        Remove predicted sites that are too close to existing atoms in the
        structure.

        Args:
            min_dist (float): The minimum distance (in Angstrom) that
                a predicted site needs to be from existing atoms. A min_dist
                with value <= 0 returns all sites without distance checking.
        """
        s_f_coords = self.structure.frac_coords
        f_coords = self.extrema_coords
        if len(f_coords) == 0:
            if self.extrema_type is None:
                logger.warning(
                    "Please run ChargeDensityAnalyzer.get_local_extrema first!")
                return
            new_f_coords = []
            self._update_extrema(new_f_coords, self.extrema_type)
            return new_f_coords

        dist_matrix = self.structure.lattice.get_all_distances(f_coords,
                                                               s_f_coords)
        all_dist = np.min(dist_matrix, axis=1)
        new_f_coords = []

        for i, f in enumerate(f_coords):
            if all_dist[i] > min_dist:
                new_f_coords.append(f)
        self._update_extrema(new_f_coords, self.extrema_type)

        return new_f_coords


Instruction:
Can you tell what is the following Python 3 function doing
def get_structure_with_nodes(self, find_min=True, min_dist=0.5, tol=0.2,
                                 threshold_frac=None, threshold_abs=None):
        """
        Get the modified structure with the possible interstitial sites added.
        The species is set as a DummySpecie X.

        Args:
            find_min (bool): True to find local minimum else maximum, otherwise
                find local maximum.

            min_dist (float): The minimum distance (in Angstrom) that
                a predicted site needs to be from existing atoms. A min_dist
                with value <= 0 returns all sites without distance checking.

            tol (float): A distance tolerance of nodes clustering that sites too
                closed to other predicted sites will be merged. PBC is taken
                into account.

            threshold_frac (float): optional fraction of extrema, which returns
                `threshold_frac * tot_num_extrema` extrema fractional
                coordinates based on highest/lowest intensity.

                E.g. set 0.2 to insert DummySpecie atom at the extrema with 20%
                highest or lowest intensity.
                Value range: 0 <= threshold_frac <= 1

                Note that threshold_abs and threshold_frac should not set in the
                same time.

            threshold_abs (float): optional filter. When searching for local
                minima, intensity <= threshold_abs returns; when searching for
                local maxima, intensity >= threshold_abs returns.

                Note that threshold_abs and threshold_frac should not set in the
                same time.

        Returns:
            structure (Structure)
        """

        structure = self.structure.copy()
        self.get_local_extrema(find_min=find_min, threshold_frac=threshold_frac,
                               threshold_abs=threshold_abs)

        self.remove_collisions(min_dist)
        self.cluster_nodes(tol=tol)
        for fc in self.extrema_coords:
            structure.append("X", fc)

        return structure

Response: Get the modified structure with the possible interstitial sites added.


Instruction:
Make a summary of the following Python 3 code
def sort_sites_by_integrated_chg(self, r=0.4):

        if self.extrema_type is None:
            self.get_local_extrema()
        int_den = []
        for isite in self.extrema_coords:
            mask = self._dist_mat(isite) < r
            vol_sphere = self.chgcar.structure.volume * (mask.sum()/self.chgcar.ngridpts)
            chg_in_sphere = np.sum(self.chgcar.data['total'] * mask) / mask.size / vol_sphere
            int_den.append(chg_in_sphere)
        self._extrema_df['avg_charge_den'] = int_den
        self._extrema_df.sort_values(by=['avg_charge_den'], inplace=True)
        self._extrema_df.reset_index(drop=True, inplace=True)

Response:
Sort the sites by the average charge density around each local minima in the charge density
            and store the result in _extrema_df.


Instruction:
Create a Python 3 function to
parse a QChem output file with multiple calculations and returns a list of QCCalcs.

Response:
def multiple_outputs_from_file(cls, filename, keep_sub_files=True):
        """
            Parses a QChem output file with multiple calculations
            1.) Seperates the output into sub-files
                e.g. qcout -> qcout.0, qcout.1, qcout.2 ... qcout.N
                a.) Find delimeter for multiple calcualtions
                b.) Make seperate output sub-files
            2.) Creates seperate QCCalcs for each one from the sub-files
        """
        to_return = []
        with zopen(filename, 'rt') as f:
            text = re.split(r'\s*(?:Running\s+)*Job\s+\d+\s+of\s+\d+\s+',
                            f.read())
        if text[0] == '':
            text = text[1:]
        for i, sub_text in enumerate(text):
            temp = open(filename + '.' + str(i), 'w')
            temp.write(sub_text)
            temp.close()
            tempOutput = cls(filename + '.' + str(i))
            to_return.append(tempOutput)
            if not keep_sub_files:
                os.remove(filename + '.' + str(i))
        return to_return


Instruction:
Create a Python 3 function to
parse charge and multiplicity.

Response:
def _read_charge_and_multiplicity(self):
        """
        Parses charge and multiplicity.
        """
        temp_charge = read_pattern(
            self.text, {
                "key": r"\$molecule\s+([\-\d]+)\s+\d"
            },
            terminate_on_match=True).get('key')
        if temp_charge != None:
            self.data["charge"] = int(temp_charge[0][0])
        else:
            temp_charge = read_pattern(
                self.text, {
                    "key": r"Sum of atomic charges \=\s+([\d\-\.\+]+)"
                },
                terminate_on_match=True).get('key')
            if temp_charge == None:
                self.data["charge"] = None
            else:
                self.data["charge"] = int(float(temp_charge[0][0]))

        temp_multiplicity = read_pattern(
            self.text, {
                "key": r"\$molecule\s+[\-\d]+\s+(\d)"
            },
            terminate_on_match=True).get('key')
        if temp_multiplicity != None:
            self.data["multiplicity"] = int(temp_multiplicity[0][0])
        else:
            temp_multiplicity = read_pattern(
                self.text, {
                    "key": r"Sum of spin\s+charges \=\s+([\d\-\.\+]+)"
                },
                terminate_on_match=True).get('key')
            if temp_multiplicity == None:
                self.data["multiplicity"] = 1
            else:
                self.data["multiplicity"] = int(
                    float(temp_multiplicity[0][0])) + 1


Instruction:
How would you explain what the following Python 3 function does
def _read_species_and_inital_geometry(self):
        header_pattern = r"Standard Nuclear Orientation \(Angstroms\)\s+I\s+Atom\s+X\s+Y\s+Z\s+-+"
        table_pattern = r"\s*\d+\s+([a-zA-Z]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*"
        footer_pattern = r"\s*-+"
        temp_geom = read_table_pattern(self.text, header_pattern,
                                       table_pattern, footer_pattern)
        if temp_geom == None or len(temp_geom) == 0:
            self.data["species"] = None
            self.data["initial_geometry"] = None
            self.data["initial_molecule"] = None
            self.data["point_group"] = None
        else:
            temp_point_group = read_pattern(
            self.text, {
                "key":
                r"Molecular Point Group\s+([A-Za-z\d\*]+)"
            },
            terminate_on_match=True).get('key')
            if temp_point_group != None:
                self.data["point_group"] = temp_point_group[0][0]
            else:
                self.data["point_group"] = None
            temp_geom = temp_geom[0]
            species = []
            geometry = np.zeros(shape=(len(temp_geom), 3), dtype=float)
            for ii, entry in enumerate(temp_geom):
                species += [entry[0]]
                for jj in range(3):
                    geometry[ii, jj] = float(entry[jj + 1])
            self.data["species"] = species
            self.data["initial_geometry"] = geometry
            self.data["initial_molecule"] = Molecule(
                species=species,
                coords=geometry,
                charge=self.data.get('charge'),
                spin_multiplicity=self.data.get('multiplicity'))

Response: Parses species and initial geometry.


Instruction:
Can you generate the documentation for the following Python 3 function
def _read_SCF(self):
        if self.data.get('using_GEN_SCFMAN', []):
            if "SCF_failed_to_converge" in self.data.get("errors"):
                footer_pattern = r"^\s*gen_scfman_exception: SCF failed to converge"
            else:
                footer_pattern = r"^\s*\-+\n\s+SCF time"
            header_pattern = r"^\s*\-+\s+Cycle\s+Energy\s+(?:(?:DIIS)*\s+[Ee]rror)*(?:RMS Gradient)*\s+\-+(?:\s*\-+\s+OpenMP\s+Integral\s+computing\s+Module\s+(?:Release:\s+version\s+[\d\-\.]+\,\s+\w+\s+[\d\-\.]+\, Q-Chem Inc\. Pittsburgh\s+)*\-+)*\n"
            table_pattern = r"(?:\s*Nonlocal correlation = [\d\-\.]+e[\d\-]+)*(?:\s*Inaccurate integrated density:\n\s+Number of electrons\s+=\s+[\d\-\.]+\n\s+Numerical integral\s+=\s+[\d\-\.]+\n\s+Relative error\s+=\s+[\d\-\.]+\s+\%\n)*\s*\d+\s+([\d\-\.]+)\s+([\d\-\.]+)e([\d\-\.\+]+)(?:\s+Convergence criterion met)*(?:\s+Preconditoned Steepest Descent)*(?:\s+Roothaan Step)*(?:\s+(?:Normal\s+)*BFGS [Ss]tep)*(?:\s+LineSearch Step)*(?:\s+Line search: overstep)*(?:\s+Dog-leg BFGS step)*(?:\s+Line search: understep)*(?:\s+Descent step)*"
        else:
            if "SCF_failed_to_converge" in self.data.get("errors"):
                footer_pattern = r"^\s*\d+\s*[\d\-\.]+\s+[\d\-\.]+E[\d\-\.]+\s+Convergence\s+failure\n"
            else:
                footer_pattern = r"^\s*\-+\n"
            header_pattern = r"^\s*\-+\s+Cycle\s+Energy\s+DIIS Error\s+\-+\n"
            table_pattern = r"(?:\s*Inaccurate integrated density:\n\s+Number of electrons\s+=\s+[\d\-\.]+\n\s+Numerical integral\s+=\s+[\d\-\.]+\n\s+Relative error\s+=\s+[\d\-\.]+\s+\%\n)*\s*\d+\s*([\d\-\.]+)\s+([\d\-\.]+)E([\d\-\.\+]+)(?:\s*\n\s*cpu\s+[\d\-\.]+\swall\s+[\d\-\.]+)*(?:\nin dftxc\.C, eleTot sum is:[\d\-\.]+, tauTot is\:[\d\-\.]+)*(?:\s+Convergence criterion met)*(?:\s+Done RCA\. Switching to DIIS)*(?:\n\s*Warning: not using a symmetric Q)*(?:\nRecomputing EXC\s*[\d\-\.]+\s*[\d\-\.]+\s*[\d\-\.]+(?:\s*\nRecomputing EXC\s*[\d\-\.]+\s*[\d\-\.]+\s*[\d\-\.]+)*)*"

        temp_scf = read_table_pattern(self.text, header_pattern, table_pattern,
                                      footer_pattern)
        real_scf = []
        for one_scf in temp_scf:
            temp = np.zeros(shape=(len(one_scf), 2))
            for ii, entry in enumerate(one_scf):
                temp[ii, 0] = float(entry[0])
                temp[ii, 1] = float(entry[1]) * 10**float(entry[2])
            real_scf += [temp]

        self.data["SCF"] = real_scf

Response: Reads the SCF from the SCF file and returns a list of strings.


Instruction:
How would you explain what the following Python 3 function does
def _read_mulliken(self):
        if self.data.get('unrestricted', []):
            header_pattern = r"\-+\s+Ground-State Mulliken Net Atomic Charges\s+Atom\s+Charge \(a\.u\.\)\s+Spin\s\(a\.u\.\)\s+\-+"
            table_pattern = r"\s+\d+\s\w+\s+([\d\-\.]+)\s+([\d\-\.]+)"
            footer_pattern = r"\s\s\-+\s+Sum of atomic charges"
        else:
            header_pattern = r"\-+\s+Ground-State Mulliken Net Atomic Charges\s+Atom\s+Charge \(a\.u\.\)\s+\-+"
            table_pattern = r"\s+\d+\s\w+\s+([\d\-\.]+)"
            footer_pattern = r"\s\s\-+\s+Sum of atomic charges"

        temp_mulliken = read_table_pattern(self.text, header_pattern,
                                           table_pattern, footer_pattern)
        real_mulliken = []
        for one_mulliken in temp_mulliken:
            if self.data.get('unrestricted', []):
                temp = np.zeros(shape=(len(one_mulliken), 2))
                for ii, entry in enumerate(one_mulliken):
                    temp[ii, 0] = float(entry[0])
                    temp[ii, 1] = float(entry[1])
            else:
                temp = np.zeros(len(one_mulliken))
                for ii, entry in enumerate(one_mulliken):
                    temp[ii] = float(entry[0])
            real_mulliken += [temp]

        self.data["Mulliken"] = real_mulliken

Response: Parses Mulliken charges. Parses spins given an unrestricted SCF.


Instruction:
Given the following Python 3 function, write the documentation
def _read_optimized_geometry(self):
        header_pattern = r"\*+\s+OPTIMIZATION\s+CONVERGED\s+\*+\s+\*+\s+Coordinates \(Angstroms\)\s+ATOM\s+X\s+Y\s+Z"
        table_pattern = r"\s+\d+\s+\w+\s+([\d\-\.]+)\s+([\d\-\.]+)\s+([\d\-\.]+)"
        footer_pattern = r"\s+Z-matrix Print:"

        parsed_optimized_geometry = read_table_pattern(
            self.text, header_pattern, table_pattern, footer_pattern)
        if parsed_optimized_geometry == [] or None:
            self.data["optimized_geometry"] = None
            header_pattern = r"^\s+\*+\s+OPTIMIZATION CONVERGED\s+\*+\s+\*+\s+Z-matrix\s+Print:\s+\$molecule\s+[\d\-]+\s+[\d\-]+\n"
            table_pattern = r"\s*(\w+)(?:\s+(\d+)\s+([\d\-\.]+)(?:\s+(\d+)\s+([\d\-\.]+)(?:\s+(\d+)\s+([\d\-\.]+))*)*)*(?:\s+0)*"
            footer_pattern = r"^\$end\n"

            self.data["optimized_zmat"] = read_table_pattern(
                self.text, header_pattern, table_pattern, footer_pattern)
        else:
            self.data["optimized_geometry"] = process_parsed_coords(
                parsed_optimized_geometry[0])
            if self.data.get('charge') != None:
                self.data["molecule_from_optimized_geometry"] = Molecule(
                    species=self.data.get('species'),
                    coords=self.data.get('optimized_geometry'),
                    charge=self.data.get('charge'),
                    spin_multiplicity=self.data.get('multiplicity'))

Response: Parses optimized XYZ coordinates.


Instruction:
Given the following Python 3 function, write the documentation
def _read_last_geometry(self):
        header_pattern = r"\s+Optimization\sCycle:\s+" + \
            str(len(self.data.get("energy_trajectory"))) + \
            r"\s+Coordinates \(Angstroms\)\s+ATOM\s+X\s+Y\s+Z"
        table_pattern = r"\s+\d+\s+\w+\s+([\d\-\.]+)\s+([\d\-\.]+)\s+([\d\-\.]+)"
        footer_pattern = r"\s+Point Group\:\s+[\d\w\*]+\s+Number of degrees of freedom\:\s+\d+"

        parsed_last_geometry = read_table_pattern(
            self.text, header_pattern, table_pattern, footer_pattern)
        if parsed_last_geometry == [] or None:
            self.data["last_geometry"] = None
        else:
            self.data["last_geometry"] = process_parsed_coords(
                parsed_last_geometry[0])
            if self.data.get('charge') != None:
                self.data["molecule_from_last_geometry"] = Molecule(
                    species=self.data.get('species'),
                    coords=self.data.get('last_geometry'),
                    charge=self.data.get('charge'),
                    spin_multiplicity=self.data.get('multiplicity'))

Response: Parses the last geometry from an optimization trajectory and stores it in the self. data.


Instruction:
Given the following Python 3 function, write the documentation
def _read_frequency_data(self):
        temp_dict = read_pattern(
            self.text, {
                "frequencies":
                r"\s*Frequency:\s+([\d\-\.]+)(?:\s+([\d\-\.]+)(?:\s+([\d\-\.]+))*)*",
                "IR_intens":
                r"\s*IR Intens:\s+([\d\-\.]+)(?:\s+([\d\-\.]+)(?:\s+([\d\-\.]+))*)*",
                "IR_active":
                r"\s*IR Active:\s+([YESNO]+)(?:\s+([YESNO]+)(?:\s+([YESNO]+))*)*",
                "ZPE":
                r"\s*Zero point vibrational energy:\s+([\d\-\.]+)\s+kcal/mol",
                "trans_enthalpy":
                r"\s*Translational Enthalpy:\s+([\d\-\.]+)\s+kcal/mol",
                "rot_enthalpy":
                r"\s*Rotational Enthalpy:\s+([\d\-\.]+)\s+kcal/mol",
                "vib_enthalpy":
                r"\s*Vibrational Enthalpy:\s+([\d\-\.]+)\s+kcal/mol",
                "gas_constant":
                r"\s*gas constant \(RT\):\s+([\d\-\.]+)\s+kcal/mol",
                "trans_entropy":
                r"\s*Translational Entropy:\s+([\d\-\.]+)\s+cal/mol\.K",
                "rot_entropy":
                r"\s*Rotational Entropy:\s+([\d\-\.]+)\s+cal/mol\.K",
                "vib_entropy":
                r"\s*Vibrational Entropy:\s+([\d\-\.]+)\s+cal/mol\.K",
                "total_enthalpy":
                r"\s*Total Enthalpy:\s+([\d\-\.]+)\s+kcal/mol",
                "total_entropy":
                r"\s*Total Entropy:\s+([\d\-\.]+)\s+cal/mol\.K"
            })

        keys = ["ZPE", "trans_enthalpy", "rot_enthalpy", "vib_enthalpy", "gas_constant", "trans_entropy", "rot_entropy", "vib_entropy", "total_enthalpy", "total_entropy"]

        for key in keys:
            if temp_dict.get(key) == None:
                self.data[key] = None
            else:
                self.data[key] = float(temp_dict.get(key)[0][0])

        if temp_dict.get('frequencies') == None:
            self.data['frequencies'] = None
            self.data['IR_intens'] = None
            self.data['IR_active'] = None
        else:
            temp_freqs = [
                value for entry in temp_dict.get('frequencies')
                for value in entry
            ]
            temp_intens = [
                value for entry in temp_dict.get('IR_intens')
                for value in entry
            ]
            active = [
                value for entry in temp_dict.get('IR_active')
                for value in entry
            ]
            self.data['IR_active'] = active

            freqs = np.zeros(len(temp_freqs) - temp_freqs.count('None'))
            for ii, entry in enumerate(temp_freqs):
                if entry != 'None':
                    freqs[ii] = float(entry)
            self.data['frequencies'] = freqs

            intens = np.zeros(len(temp_intens) - temp_intens.count('None'))
            for ii, entry in enumerate(temp_intens):
                if entry != 'None':
                    intens[ii] = float(entry)
            self.data['IR_intens'] = intens

            header_pattern = r"\s*Raman Active:\s+[YESNO]+\s+(?:[YESNO]+\s+)*X\s+Y\s+Z\s+(?:X\s+Y\s+Z\s+)*"
            table_pattern = r"\s*[a-zA-Z][a-zA-Z\s]\s*([\d\-\.]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*(?:([\d\-\.]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*(?:([\d\-\.]+)\s*([\d\-\.]+)\s*([\d\-\.]+))*)*"
            footer_pattern = r"TransDip\s+[\d\-\.]+\s*[\d\-\.]+\s*[\d\-\.]+\s*(?:[\d\-\.]+\s*[\d\-\.]+\s*[\d\-\.]+\s*)*"
            temp_freq_mode_vecs = read_table_pattern(
                self.text, header_pattern, table_pattern, footer_pattern)
            freq_mode_vecs = np.zeros(
                shape=(len(freqs), len(temp_freq_mode_vecs[0]), 3))

            for ii, triple_FMV in enumerate(temp_freq_mode_vecs):
                for jj, line in enumerate(triple_FMV):
                    for kk, entry in enumerate(line):
                        if entry != 'None':
                            freq_mode_vecs[int(ii * 3 + math.floor(kk / 3)),
                                           jj, kk % 3] = float(entry)

            self.data["frequency_mode_vectors"] = freq_mode_vecs

Response: Parses frequency data from the log file and returns a dictionary of frequency data.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _read_single_point_data(self):
        temp_dict = read_pattern(
            self.text, {
                "final_energy":
                    r"\s*SCF\s+energy in the final basis set\s+=\s*([\d\-\.]+)"
            })

        if temp_dict.get('final_energy') == None:
            self.data['final_energy'] = None
        else:
            # -1 in case of pcm
            # Two lines will match the above; we want final calculation
            self.data['final_energy'] = float(temp_dict.get('final_energy')[-1][0])

Response: Parses final free energy information from single - point calculations.


Instruction:
Can you generate the documentation for the following Python 3 function
def _read_pcm_information(self):

        temp_dict = read_pattern(
            self.text, {
                "g_electrostatic": r"\s*G_electrostatic\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*",
                "g_cavitation": r"\s*G_cavitation\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*",
                "g_dispersion": r"\s*G_dispersion\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*",
                "g_repulsion": r"\s*G_repulsion\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*",
                "total_contribution_pcm": r"\s*Total\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*",
            }
        )

        if temp_dict.get("g_electrostatic") is None:
            self.data["g_electrostatic"] = None
        else:
            self.data["g_electrostatic"] = float(temp_dict.get("g_electrostatic")[0][0])

        if temp_dict.get("g_cavitation") is None:
            self.data["g_cavitation"] = None
        else:
            self.data["g_cavitation"] = float(temp_dict.get("g_cavitation")[0][0])

        if temp_dict.get("g_dispersion") is None:
            self.data["g_dispersion"] = None
        else:
            self.data["g_dispersion"] = float(temp_dict.get("g_dispersion")[0][0])

        if temp_dict.get("g_repulsion") is None:
            self.data["g_repulsion"] = None
        else:
            self.data["g_repulsion"] = float(temp_dict.get("g_repulsion")[0][0])

        if temp_dict.get("total_contribution_pcm") is None:
            self.data["total_contribution_pcm"] = []
        else:
            self.data["total_contribution_pcm"] = float(temp_dict.get("total_contribution_pcm")[0][0])

Response: Parses PCM information from the PCM file and stores the values in the self. data attribute.


Instruction:
How would you implement a function in Python 3 that
parses three potential optimization errors and adds them to the internal data structure.

Response:
def _check_optimization_errors(self):
        """
        Parses three potential optimization errors: failing to converge within the allowed number
        of optimization cycles, failure to determine the lamda needed to continue, and inconsistent
        size of MO files due to a linear dependence in the AO basis.
        """
        if read_pattern(
                self.text, {
                    "key": r"MAXIMUM OPTIMIZATION CYCLES REACHED"
                },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["out_of_opt_cycles"]
        elif read_pattern(
                self.text, {
                    "key": r"UNABLE TO DETERMINE Lamda IN FormD"
                },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["unable_to_determine_lamda"]
        elif read_pattern(
                self.text, {
                    "key": r"Inconsistent size for SCF MO coefficient file"
                },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["linear_dependent_basis"]


Instruction:
Create a Python 3 function for
checking for potential errors that can cause jobs to crash.

Response:
def _check_completion_errors(self):
        """
        Parses four potential errors that can cause jobs to crash: inability to transform
        coordinates due to a bad symmetric specification, an input file that fails to pass
        inspection, and errors reading and writing files.
        """
        if read_pattern(
                self.text, {
                    "key":
                    r"Coordinates do not transform within specified threshold"
                },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["failed_to_transform_coords"]
        elif read_pattern(
                self.text,
            {
                "key": r"The Q\-Chem input file has failed to pass inspection"
            },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["input_file_error"]
        elif read_pattern(
                self.text, {
                    "key": r"Error opening input stream"
                },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["failed_to_read_input"]
        elif read_pattern(
                self.text, {
                    "key": r"FileMan error: End of file reached prematurely"
                },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["IO_error"]
        elif read_pattern(
                self.text, {
                    "key": r"Could not find \$molecule section in ParseQInput"
                },
                terminate_on_match=True).get('key') == [[]]:
            self.data["errors"] += ["read_molecule_error"]
        elif read_pattern(
                self.text, {
                    "key": r"Welcome to Q-Chem"
                },
                terminate_on_match=True).get('key') != [[]]:
            self.data["errors"] += ["never_called_qchem"]
        else:
            self.data["errors"] += ["unknown_error"]


Instruction:
Write a Python 3 script to
query the COD for a structure by id.

Response:
def get_structure_by_id(self, cod_id, **kwargs):
        """
        Queries the COD for a structure by id.

        Args:
            cod_id (int): COD id.
            kwargs: All kwargs supported by
                :func:`pymatgen.core.structure.Structure.from_str`.

        Returns:
            A Structure.
        """
        r = requests.get("http://www.crystallography.net/cod/%s.cif" % cod_id)
        return Structure.from_str(r.text, fmt="cif", **kwargs)


Instruction:
Write a Python 3 script to
query the COD for structures by formula. Requires mysql executable to be in the path. Requires mysql executable to be in the path. Requires pymatgen. core. structure. Structure. from_str to be called.

Response:
def get_structure_by_formula(self, formula, **kwargs):
        """
        Queries the COD for structures by formula. Requires mysql executable to
        be in the path.

        Args:
            cod_id (int): COD id.
            kwargs: All kwargs supported by
                :func:`pymatgen.core.structure.Structure.from_str`.

        Returns:
            A list of dict of the format
            [{"structure": Structure, "cod_id": cod_id, "sg": "P n m a"}]
        """
        structures = []
        sql = 'select file, sg from data where formula="- %s -"' % \
              Composition(formula).hill_formula
        text = self.query(sql).split("\n")
        text.pop(0)
        for l in text:
            if l.strip():
                cod_id, sg = l.split("\t")
                r = requests.get("http://www.crystallography.net/cod/%s.cif"
                                 % cod_id.strip())
                try:
                    s = Structure.from_str(r.text, fmt="cif", **kwargs)
                    structures.append({"structure": s, "cod_id": int(cod_id),
                                       "sg": sg})
                except Exception:
                    import warnings
                    warnings.warn("\nStructure.from_str failed while parsing CIF file:\n%s" % r.text)
                    raise

        return structures


Instruction:
Can you generate the documentation for the following Python 3 function
def get_csms(self, isite, mp_symbol):
        cn = symbol_cn_mapping[mp_symbol]
        if cn not in self.ce_list[isite]:
            return []
        else:
            return [envs[mp_symbol] for envs in self.ce_list[isite][cn]]

Response:
Returns the continuous symmetry measure of site with index isite with respect to the
         perfect coordination environment with mp_symbol.


Instruction:
Can you tell what is the following Python 3 function doing
def plot_csm_and_maps(self, isite, max_csm=8.0):
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            print('Plotting Chemical Environments requires matplotlib ... exiting "plot" function')
            return
        fig = self.get_csm_and_maps(isite=isite, max_csm=max_csm)
        if fig is None:
            return
        plt.show()

Response: This function plots the coordination numbers of a given site for all the distfactor and angfactor parameters.


Instruction:
Write a Python 3 script for
returning a matplotlib figure object that can be used to plot the chemical environments of a given site.

Response:
def get_environments_figure(self, isite, plot_type=None, title='Coordination numbers', max_dist=2.0,
                                additional_condition=AC.ONLY_ACB, colormap=None, figsize=None,
                                strategy=None):
        """
        Plotting of the coordination environments of a given site for all the distfactor/angfactor regions. The
        chemical environments with the lowest continuous symmetry measure is shown for each distfactor/angfactor
        region as the value for the color of that distfactor/angfactor region (using a colormap).
        :param isite: Index of the site for which the plot has to be done
        :param plot_type: How to plot the coordinations
        :param title: Title for the figure
        :param max_dist: Maximum distance to be plotted when the plotting of the distance is set to 'initial_normalized'
                         or 'initial_real' (Warning: this is not the same meaning in both cases! In the first case,
                         the closest atom lies at a "normalized" distance of 1.0 so that 2.0 means refers to this
                         normalized distance while in the second case, the real distance is used)
        :param figsize: Size of the figure to be plotted
        :return: The figure object to be plotted or saved to file
        """
        try:
            import matplotlib.pyplot as mpl
            from matplotlib import cm
            from matplotlib.colors import Normalize, LinearSegmentedColormap, ListedColormap
            from matplotlib.patches import Rectangle, Polygon
        except ImportError:
            print('Plotting Chemical Environments requires matplotlib ... exiting "plot" function')
            return

        #Initializes the figure
        if figsize is None:
            fig = mpl.figure()
        else:
            fig = mpl.figure(figsize=figsize)
        subplot = fig.add_subplot(111)

        #Initializes the distance and angle parameters
        if plot_type is None:
            plot_type = {'distance_parameter': ('initial_normalized', None),
                         'angle_parameter': ('initial_normalized_inverted', None)}
        if colormap is None:
            mycm = cm.jet
        else:
            mycm = colormap
        mymin = 0.0
        mymax = 10.0
        norm = Normalize(vmin=mymin, vmax=mymax)
        scalarmap = cm.ScalarMappable(norm=norm, cmap=mycm)
        dist_limits = [1.0, max_dist]
        ang_limits = [0.0, 1.0]
        if plot_type['distance_parameter'][0] == 'one_minus_inverse_alpha_power_n':
            if plot_type['distance_parameter'][1] is None:
                exponent = 3
            else:
                exponent = plot_type['distance_parameter'][1]['exponent']
            xlabel = 'Distance parameter : $1.0-\\frac{{1.0}}{{\\alpha^{{{:d}}}}}$'.format(exponent)
            def dp_func(dp):
                return 1.0-1.0/np.power(dp, exponent)
        elif plot_type['distance_parameter'][0] == 'initial_normalized':
            xlabel = 'Distance parameter : $\\alpha$'
            def dp_func(dp):
                return dp
        else:
            raise ValueError('Wrong value for distance parameter plot type "{}"'.
                             format(plot_type['distance_parameter'][0]))

        if plot_type['angle_parameter'][0] == 'one_minus_gamma':
            ylabel = 'Angle parameter : $1.0-\\gamma$'
            def ap_func(ap):
                return 1.0-ap
        elif plot_type['angle_parameter'][0] in ['initial_normalized_inverted', 'initial_normalized']:
            ylabel = 'Angle parameter : $\\gamma$'
            def ap_func(ap):
                return ap
        else:
            raise ValueError('Wrong value for angle parameter plot type "{}"'.
                             format(plot_type['angle_parameter'][0]))
        dist_limits = [dp_func(dp) for dp in dist_limits]
        ang_limits = [ap_func(ap) for ap in ang_limits]

        for cn, cn_nb_sets in self.neighbors_sets[isite].items():
            for inb_set, nb_set in enumerate(cn_nb_sets):
                nb_set_surface_pts = nb_set.voronoi_grid_surface_points()
                if nb_set_surface_pts is None:
                    continue
                ce = self.ce_list[isite][cn][inb_set]
                if ce is None:
                    mycolor = 'w'
                    myinvcolor = 'k'
                    mytext = '{:d}'.format(cn)
                else:
                    mingeom = ce.minimum_geometry()
                    if mingeom is not None:
                        mp_symbol = mingeom[0]
                        csm = mingeom[1]['symmetry_measure']
                        mycolor = scalarmap.to_rgba(csm)
                        myinvcolor = [1.0 - mycolor[0], 1.0 - mycolor[1], 1.0 - mycolor[2], 1.0]
                        mytext = '{}'.format(mp_symbol)
                    else:
                        mycolor = 'w'
                        myinvcolor = 'k'
                        mytext = '{:d}'.format(cn)
                nb_set_surface_pts = [(dp_func(pt[0]), ap_func(pt[1])) for pt in nb_set_surface_pts]
                polygon = Polygon(nb_set_surface_pts, closed=True, edgecolor='k', facecolor=mycolor, linewidth=1.2)
                subplot.add_patch(polygon)
                myipt = len(nb_set_surface_pts) / 2
                ipt = int(myipt)
                if myipt != ipt:
                    raise RuntimeError('Number of surface points not even')
                patch_center = ((nb_set_surface_pts[0][0] + min(nb_set_surface_pts[ipt][0], dist_limits[1])) / 2,
                                (nb_set_surface_pts[0][1] + nb_set_surface_pts[ipt][1]) / 2)

                if (np.abs(nb_set_surface_pts[-1][1] - nb_set_surface_pts[-2][1]) > 0.06 and
                      np.abs(min(nb_set_surface_pts[-1][0], dist_limits[1]) - nb_set_surface_pts[0][0]) > 0.125):
                    xytext = ((min(nb_set_surface_pts[-1][0], dist_limits[1]) + nb_set_surface_pts[0][0]) / 2,
                              (nb_set_surface_pts[-1][1] + nb_set_surface_pts[-2][1]) / 2)
                    subplot.annotate(mytext, xy=xytext,
                                     ha='center', va='center', color=myinvcolor, fontsize='x-small')
                elif (np.abs(nb_set_surface_pts[ipt][1] - nb_set_surface_pts[0][1]) > 0.1 and
                    np.abs(min(nb_set_surface_pts[ipt][0], dist_limits[1]) - nb_set_surface_pts[0][0]) > 0.125):
                    xytext = patch_center
                    subplot.annotate(mytext, xy=xytext,
                                     ha='center', va='center', color=myinvcolor, fontsize='x-small')

        subplot.set_title(title)
        subplot.set_xlabel(xlabel)
        subplot.set_ylabel(ylabel)

        dist_limits.sort()
        ang_limits.sort()
        subplot.set_xlim(dist_limits)
        subplot.set_ylim(ang_limits)
        if strategy is not None:
            try:
                strategy.add_strategy_visualization_to_subplot(subplot=subplot)
            except:
                pass
        if plot_type['angle_parameter'][0] == 'initial_normalized_inverted':
            subplot.axes.invert_yaxis()

        scalarmap.set_array([mymin, mymax])
        cb = fig.colorbar(scalarmap, ax=subplot, extend='max')
        cb.set_label('Continuous symmetry measure')
        return fig, subplot


Instruction:
Can you tell what is the following Python 3 function doing
def plot_environments(self,  isite, plot_type=None, title='Coordination numbers', max_dist=2.0,
                          additional_condition=AC.ONLY_ACB, figsize=None, strategy=None):
        """
        Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the
        chemical environments are given, a color map is added to the plot, with the lowest continuous symmetry measure
        as the value for the color of that distfactor/angfactor set.
        :param isite: Index of the site for which the plot has to be done
        :param plot_type: How to plot the coordinations
        :param title: Title for the figure
        :param max_dist: Maximum distance to be plotted when the plotting of the distance is set to 'initial_normalized'
                         or 'initial_real' (Warning: this is not the same meaning in both cases! In the first case,
                         the closest atom lies at a "normalized" distance of 1.0 so that 2.0 means refers to this
                         normalized distance while in the second case, the real distance is used)
        :param figsize: Size of the figure to be plotted
        :return: Nothing returned, just plot the figure
        """
        fig, subplot = self.get_environments_figure(isite=isite, plot_type=plot_type, title=title, max_dist=max_dist,
                                                    additional_condition=additional_condition, figsize=figsize,
                                                    strategy=strategy)
        if fig is None:
            return
        fig.show()

Response: This function plots the chemical environments of a given site.


Instruction:
How would you explain what the following Python 3 function does
def as_dict(self):
        ce_list_dict = [{str(cn): [ce.as_dict() if ce is not None else None for ce in ce_dict[cn]]
                         for cn in ce_dict} if ce_dict is not None else None for ce_dict in self.ce_list]
        nbs_sets_dict = [{str(cn): [nb_set.as_dict() for nb_set in nb_sets]
                          for cn, nb_sets in site_nbs_sets.items()}
                         if site_nbs_sets is not None else None
                         for site_nbs_sets in self.neighbors_sets]
        info_dict = {key: val for key, val in self.info.items() if key not in ['sites_info']}
        info_dict['sites_info'] = [{'nb_sets_info': {str(cn): {str(inb_set): nb_set_info
                                                               for inb_set, nb_set_info in cn_sets.items()}
                                                     for cn, cn_sets in site_info['nb_sets_info'].items()},
                                    'time': site_info['time']} if 'nb_sets_info' in site_info else {}
                                   for site_info in self.info['sites_info']]

        return {"@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "voronoi": self.voronoi.as_dict(),
                "valences": self.valences,
                "sites_map": self.sites_map,
                "equivalent_sites": [[ps.as_dict() for ps in psl] for psl in self.equivalent_sites],
                "ce_list": ce_list_dict,
                "structure": self.structure.as_dict(),
                "neighbors_sets": nbs_sets_dict,
                "info": info_dict}

Response: Return a dict representation of the StructureEnvironments object.


Instruction:
Create a Python 3 function to
reconstruct the StructureEnvironments object from a dict representation of the StructureEnvironments created using the as_dict method.

Response:
def from_dict(cls, d):
        """
        Reconstructs the StructureEnvironments object from a dict representation of the StructureEnvironments created
        using the as_dict method.
        :param d: dict representation of the StructureEnvironments object
        :return: StructureEnvironments object
        """
        ce_list = [None if (ce_dict == 'None' or ce_dict is None) else {
            int(cn): [None if (ced is None or ced == 'None') else
                      ChemicalEnvironments.from_dict(ced) for ced in ce_dict[cn]]
            for cn in ce_dict} for ce_dict in d['ce_list']]
        voronoi = DetailedVoronoiContainer.from_dict(d['voronoi'])
        structure = Structure.from_dict(d['structure'])
        neighbors_sets = [{int(cn): [cls.NeighborsSet.from_dict(dd=nb_set_dict,
                                                                structure=structure,
                                                                detailed_voronoi=voronoi)
                                     for nb_set_dict in nb_sets]
                           for cn, nb_sets in site_nbs_sets_dict.items()}
                          if site_nbs_sets_dict is not None else None
                          for site_nbs_sets_dict in d['neighbors_sets']]
        info = {key: val for key, val in d['info'].items() if key not in ['sites_info']}
        if 'sites_info' in d['info']:
            info['sites_info'] = [{'nb_sets_info': {int(cn): {int(inb_set): nb_set_info
                                                              for inb_set, nb_set_info in cn_sets.items()}
                                                    for cn, cn_sets in site_info['nb_sets_info'].items()},
                                   'time': site_info['time']} if 'nb_sets_info' in site_info else {}
                                  for site_info in d['info']['sites_info']]
        return cls(voronoi=voronoi, valences=d['valences'],
                   sites_map=d['sites_map'],
                   equivalent_sites=[[PeriodicSite.from_dict(psd) for psd in psl] for psl in d['equivalent_sites']],
                   ce_list=ce_list, structure=structure,
                   neighbors_sets=neighbors_sets,
                   info=info)


Instruction:
Can you tell what is the following Python 3 function doing
def structure_contains_atom_environment(self, atom_symbol, ce_symbol):
        for isite, site in enumerate(self.structure):
            if (Element(atom_symbol) in site.species.
                    element_composition and self.site_contains_environment(isite, ce_symbol)):
                return True
        return False

Response: Checks whether the structure contains a given atom in a given coordination environment.


Instruction:
Write a Python 3 script for
returning a dict representation of the LightStructureEnvironments object.

Response:
def as_dict(self):
        """
        Bson-serializable dict representation of the LightStructureEnvironments object.
        :return: Bson-serializable dict representation of the LightStructureEnvironments object.
        """
        return {"@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "strategy": self.strategy.as_dict(),
                "structure": self.structure.as_dict(),
                "coordination_environments": self.coordination_environments,
                "all_nbs_sites": [{'site': nb_site['site'].as_dict(),
                                   'index': nb_site['index'],
                                   'image_cell': [int(ii) for ii in nb_site['image_cell']]}
                                  for nb_site in self._all_nbs_sites],
                "neighbors_sets": [[nb_set.as_dict() for nb_set in site_nb_sets] if site_nb_sets is not None else None
                                   for site_nb_sets in self.neighbors_sets],
                "valences": self.valences}


Instruction:
How would you implement a function in Python 3 that
reconstructs the LightStructureEnvironments object from a dict representation of the LightStructureEnvironments object.

Response:
def from_dict(cls, d):
        """
        Reconstructs the LightStructureEnvironments object from a dict representation of the
        LightStructureEnvironments created using the as_dict method.
        :param d: dict representation of the LightStructureEnvironments object
        :return: LightStructureEnvironments object
        """
        dec = MontyDecoder()
        structure = dec.process_decoded(d['structure'])
        all_nbs_sites = []
        for nb_site in d['all_nbs_sites']:
            site = dec.process_decoded(nb_site['site'])
            if 'image_cell' in nb_site:
                image_cell = np.array(nb_site['image_cell'], np.int)
            else:
                diff = site.frac_coords - structure[nb_site['index']].frac_coords
                rounddiff = np.round(diff)
                if not np.allclose(diff, rounddiff):
                    raise ValueError('Weird, differences between one site in a periodic image cell is not '
                                     'integer ...')
                image_cell = np.array(rounddiff, np.int)
            all_nbs_sites.append({'site': site,
                                  'index': nb_site['index'],
                                  'image_cell': image_cell})
        neighbors_sets = [[cls.NeighborsSet.from_dict(dd=nb_set, structure=structure,
                                                      all_nbs_sites=all_nbs_sites)
                           for nb_set in site_nb_sets] if site_nb_sets is not None else None
                          for site_nb_sets in d['neighbors_sets']]
        return cls(strategy=dec.process_decoded(d['strategy']),
                   coordination_environments=d['coordination_environments'],
                   all_nbs_sites=all_nbs_sites,
                   neighbors_sets=neighbors_sets,
                   structure=structure,
                   valences=d['valences'])


Instruction:
How would you explain what the following Python 3 function does
def minimum_geometry(self, symmetry_measure_type=None, max_csm=None):
        if len(self.coord_geoms) == 0:
            return None
        cglist = [cg for cg in self.coord_geoms]
        if symmetry_measure_type is None:
            csms = np.array([self.coord_geoms[cg]['other_symmetry_measures']['csm_wcs_ctwcc'] for cg in cglist])
        else:
            csms = np.array([self.coord_geoms[cg]['other_symmetry_measures'][symmetry_measure_type] for cg in cglist])
        csmlist = [self.coord_geoms[cg] for cg in cglist]
        imin = np.argmin(csms)
        if max_csm is not None:
            if csmlist[imin] > max_csm:
                return None
        return cglist[imin], csmlist[imin]

Response: Returns the geometry with the minimum continuous symmetry measure of this ChemicalEnvironments object and csm associated to it.


Instruction:
Create a Python 3 function for
returning a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object.

Response:
def minimum_geometries(self, n=None, symmetry_measure_type=None, max_csm=None):
        """
        Returns a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object
        :param n: Number of geometries to be included in the list
        :return: list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object
        :raise: ValueError if no coordination geometry is found in this ChemicalEnvironments object
        """
        cglist = [cg for cg in self.coord_geoms]
        if symmetry_measure_type is None:
            csms = np.array([self.coord_geoms[cg]['other_symmetry_measures']['csm_wcs_ctwcc'] for cg in cglist])
        else:
            csms = np.array([self.coord_geoms[cg]['other_symmetry_measures'][symmetry_measure_type] for cg in cglist])
        csmlist = [self.coord_geoms[cg] for cg in cglist]
        isorted = np.argsort(csms)
        if max_csm is not None:
            if n is None:
                return [(cglist[ii], csmlist[ii]) for ii in isorted if csms[ii] <= max_csm]
            else:
                return [(cglist[ii], csmlist[ii]) for ii in isorted[:n] if csms[ii] <= max_csm]
        else:
            if n is None:
                return [(cglist[ii], csmlist[ii]) for ii in isorted]
            else:
                return [(cglist[ii], csmlist[ii]) for ii in isorted[:n]]


Instruction:
Here you have a function in Python 3, explain what it does
def add_coord_geom(self, mp_symbol, symmetry_measure, algo='UNKNOWN', permutation=None, override=False,
                       local2perfect_map=None, perfect2local_map=None, detailed_voronoi_index=None,
                       other_symmetry_measures=None, rotation_matrix=None, scaling_factor=None):
        """
        Adds a coordination geometry to the ChemicalEnvironments object
        :param mp_symbol: Symbol (internal) of the coordination geometry added
        :param symmetry_measure: Symmetry measure of the coordination geometry added
        :param algo: Algorithm used for the search of the coordination geometry added
        :param permutation: Permutation of the neighbors that leads to the csm stored
        :param override: If set to True, the coordination geometry will override the existent one if present
        :return: :raise: ChemenvError if the coordination geometry is already added and override is set to False
        """
        if not allcg.is_a_valid_coordination_geometry(mp_symbol=mp_symbol):
            raise ChemenvError(self.__class__,
                               'add_coord_geom',
                               'Coordination geometry with mp_symbol "{mp}" is not valid'
                               .format(mp=mp_symbol))
        if mp_symbol in list(self.coord_geoms.keys()) and not override:
            raise ChemenvError(self.__class__,
                               "add_coord_geom",
                               "This coordination geometry is already present and override is set to False")
        else:
            self.coord_geoms[mp_symbol] = {'symmetry_measure': float(symmetry_measure), 'algo': algo,
                                           'permutation': [int(i) for i in permutation],
                                           'local2perfect_map': local2perfect_map,
                                           'perfect2local_map': perfect2local_map,
                                           'detailed_voronoi_index': detailed_voronoi_index,
                                           'other_symmetry_measures': other_symmetry_measures,
                                           'rotation_matrix': rotation_matrix,
                                           'scaling_factor': scaling_factor}

Response: Adds a coordination geometry to the ChemicalEnvironments object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def as_dict(self):
        return {"@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "coord_geoms": jsanitize(self.coord_geoms)}

Response: Returns a dictionary representation of the ChemicalEnvironments object.


Instruction:
Can you implement a function in Python 3 that
reconstructs the ChemicalEnvironments object from a dict representation of the ChemicalEnvironments created by as_dict method.

Response:
def from_dict(cls, d):
        """
        Reconstructs the ChemicalEnvironments object from a dict representation of the ChemicalEnvironments created
        using the as_dict method.
        :param d: dict representation of the ChemicalEnvironments object
        :return: ChemicalEnvironments object
        """
        ce = cls()
        for cg in d['coord_geoms'].keys():
            if d['coord_geoms'][cg]['local2perfect_map'] is None:
                l2p_map = None
            else:
                l2p_map = {int(key): int(val) for key, val in d['coord_geoms'][cg]['local2perfect_map'].items()}
            if d['coord_geoms'][cg]['perfect2local_map'] is None:
                p2l_map = None
            else:
                p2l_map = {int(key): int(val) for key, val in d['coord_geoms'][cg]['perfect2local_map'].items()}
            if ('other_symmetry_measures' in d['coord_geoms'][cg] and
                        d['coord_geoms'][cg]['other_symmetry_measures'] is not None):
                other_csms = d['coord_geoms'][cg]['other_symmetry_measures']
            else:
                other_csms = None
            ce.add_coord_geom(cg,
                              d['coord_geoms'][cg]['symmetry_measure'],
                              d['coord_geoms'][cg]['algo'],
                              permutation=d['coord_geoms'][cg]['permutation'],
                              local2perfect_map=l2p_map,
                              perfect2local_map=p2l_map,
                              detailed_voronoi_index=d['coord_geoms'][cg]['detailed_voronoi_index'],
                              other_symmetry_measures=other_csms,
                              rotation_matrix=d['coord_geoms'][cg]['rotation_matrix'],
                              scaling_factor=d['coord_geoms'][cg]['scaling_factor'])
        return ce


Instruction:
How would you explain what the following Python 3 function does
def icohplist(self):
        icohplist_new = {}
        for key, value in self._icohpcollection._icohplist.items():
            icohplist_new[key] = {"length": value._length, "number_of_bonds": value._num,
                                  "icohp": value._icohp, "translation": value._translation}
        return icohplist_new

Response: Returns a new icohplist compatible with older version of this class


Instruction:
Explain what the following Python 3 code does
def get_structure_with_charges(self, structure_filename):

        struct = Structure.from_file(structure_filename)
        Mulliken = self.Mulliken
        Loewdin = self.Loewdin
        site_properties = {"Mulliken Charges": Mulliken, "Loewdin Charges": Loewdin}
        new_struct = struct.copy(site_properties=site_properties)
        return new_struct

Response: get a Structure object with Mulliken and Loewdin charges as site properties


Instruction:
Can you create a Python 3 function that
returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter

Response:
def get_bandstructure(self):
        """
        returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter
        """

        return LobsterBandStructureSymmLine(kpoints=self.kpoints_array, eigenvals=self.eigenvals, lattice=self.lattice,
                                            efermi=self.efermi, labels_dict=self.label_dict,
                                            structure=self.structure,
                                            projections=self.p_eigenvals)


Instruction:
Can you implement a function in Python 3 that
gets the decomposition leading to lowest cost

Response:
def get_lowest_decomposition(self, composition):
        """
        Get the decomposition leading to lowest cost

        Args:
            composition:
                Composition as a pymatgen.core.structure.Composition
        Returns:
            Decomposition as a dict of {Entry: amount}
        """

        entries_list = []
        elements = [e.symbol for e in composition.elements]
        for i in range(len(elements)):
            for combi in itertools.combinations(elements, i + 1):
                chemsys = [Element(e) for e in combi]
                x = self.costdb.get_entries(chemsys)
                entries_list.extend(x)
        try:
            pd = PhaseDiagram(entries_list)
            return pd.get_decomposition(composition)
        except IndexError:
            raise ValueError("Error during PD building; most likely, "
                             "cost data does not exist!")


Instruction:
Make a summary of the following Python 3 code
def get_cost_per_mol(self, comp):

        comp = comp if isinstance(comp, Composition) else Composition(comp)
        decomp = self.get_lowest_decomposition(comp)
        return sum(k.energy_per_atom * v * comp.num_atoms for k, v in
                   decomp.items())

Response: Get best estimate of minimum cost per mol based on known data.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_cost_per_kg(self, comp):
        comp = comp if isinstance(comp, Composition) else Composition(comp)
        return self.get_cost_per_mol(comp) / (
            comp.weight.to("kg") * const.N_A)

Response: Get best estimate of minimum cost per kg based on known data.


Instruction:
How would you code a function in Python 3 to
convert a string into a boolean.

Response:
def as_bool(s):
    """
    Convert a string into a boolean.

    >>> assert as_bool(True) is True and as_bool("Yes") is True and as_bool("false") is False
    """
    if s in (False, True): return s
    # Assume string
    s = s.lower()
    if s in ("yes", "true"):
        return True
    elif s in ("no", "false"):
        return False
    else:
        raise ValueError("Don't know how to convert type %s: %s into a boolean" % (type(s), s))


Instruction:
Can you create a Python 3 function that
splits the ABINIT extension from a filename.

Response:
def abi_splitext(filename):
    """
    Split the ABINIT extension from a filename.
    "Extension" are found by searching in an internal database.

    Returns "(root, ext)" where ext is the registered ABINIT extension
    The final ".nc" is included (if any)

    >>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK')
    >>> assert abi_splitext("/home/guido/foo_bar_WFK.nc") == ('foo_bar_', 'WFK.nc')
    """
    filename = os.path.basename(filename)
    is_ncfile = False
    if filename.endswith(".nc"):
        is_ncfile = True
        filename = filename[:-3]

    known_extensions = abi_extensions()

    # This algorith fails if we have two files
    # e.g. HAYDR_SAVE, ANOTHER_HAYDR_SAVE
    for i in range(len(filename)-1, -1, -1):
        ext = filename[i:]
        if ext in known_extensions:
            break

    else:
        raise ValueError("Cannot find a registered extension in %s" % filename)

    root = filename[:i]
    if is_ncfile:
        ext += ".nc"

    return root, ext


Instruction:
Can you write a function in Python 3 where it
converts a Mongodb - like dictionary to a list of operands and operators.

Response:
def map2rpn(map, obj):
    """
    Convert a Mongodb-like dictionary to a RPN list of operands and operators.

    Reverse Polish notation (RPN) is a mathematical notation in which every
    operator follows all of its operands, e.g.

    3 - 4 + 5 -->   3 4 - 5 +

    >>> d = {2.0: {'$eq': 1.0}}
    >>> assert map2rpn(d, None) == [2.0, 1.0, '$eq']
    """
    rpn = []

    for k, v in map.items():

        if k in _ALL_OPS:
            if isinstance(v, collections.abc.Mapping):
                # e.g "$not": {"$gt": "one"}
                # print("in op_vmap",k, v)
                values = map2rpn(v, obj)
                rpn.extend(values)
                rpn.append(k)

            elif isinstance(v, (list, tuple)):
                # e.g "$and": [{"$not": {"one": 1.0}}, {"two": {"$lt": 3}}]}
                # print("in_op_list",k, v)
                for d in v:
                    rpn.extend(map2rpn(d, obj))

                rpn.append(k)

            else:
                # Examples
                # 1) "$eq"": "attribute_name"
                # 2) "$eq"": 1.0
                try:
                    #print("in_otherv",k, v)
                    rpn.append(getattr(obj, v))
                    rpn.append(k)

                except TypeError:
                    #print("in_otherv, raised",k, v)
                    rpn.extend([v, k])
        else:
            try:
                k = getattr(obj, k)
            except TypeError:
                k = k

            if isinstance(v, collections.abc.Mapping):
                # "one": {"$eq": 1.0}}
                values = map2rpn(v, obj)
                rpn.append(k)
                rpn.extend(values)
            else:
                #"one": 1.0
                rpn.extend([k, v, "$eq"])

    return rpn


Instruction:
How would you code a function in Python 3 to
evaluate the RPN form produced my map2rpn.

Response:
def evaluate_rpn(rpn):
    """
    Evaluates the RPN form produced my map2rpn.

    Returns:
        bool
    """
    vals_stack = []

    for item in rpn:

        if item in _ALL_OPS:
            # Apply the operator and push to the task.
            v2 = vals_stack.pop()

            if item in _UNARY_OPS:
                res = _UNARY_OPS[item](v2)

            elif item in _BIN_OPS:
                v1 = vals_stack.pop()
                res = _BIN_OPS[item](v1, v2)
            else:
                raise ValueError("%s not in unary_ops or bin_ops" % str(item))

            vals_stack.append(res)

        else:
            # Push the operand
            vals_stack.append(item)

        #print(vals_stack)

    assert len(vals_stack) == 1
    assert isinstance(vals_stack[0], bool)

    return vals_stack[0]


Instruction:
Can you tell what is the following Python 3 function doing
def write(self, string):
        self.make_dir()
        with open(self.path, "w") as f:
            if not string.endswith("\n"):
                return f.write(string + "\n")
            else:
                return f.write(string)

Response: Write string to file.


Instruction:
Explain what the following Python 3 code does
def writelines(self, lines):
        self.make_dir()
        with open(self.path, "w") as f:
            return f.writelines(lines)

Response: Write a list of strings to file.


Instruction:
Can you generate the documentation for the following Python 3 function
def make_dir(self):
        if not os.path.exists(self.dirname):
            os.makedirs(self.dirname)

Response: Make the directory where the file is located.


Instruction:
Can you tell what is the following Python 3 function doing
def list_filepaths(self, wildcard=None):
        # Select the files in the directory.
        fnames = [f for f in os.listdir(self.path)]
        filepaths = filter(os.path.isfile, [os.path.join(self.path, f) for f in fnames])

        # Filter using the shell patterns.
        if wildcard is not None:
            filepaths = WildCard(wildcard).filter(filepaths)

        return filepaths

Response: Returns the list of absolute filepaths in the directory.


Instruction:
Implement a function in Python 3 to
return the absolute path of the ABINIT file with extension ext.

Response:
def has_abiext(self, ext, single_file=True):
        """
        Returns the absolute path of the ABINIT file with extension ext.
        Support both Fortran files and netcdf files. In the later case,
        we check whether a file with extension ext + ".nc" is present
        in the directory. Returns empty string is file is not present.

        Raises:
            `ValueError` if multiple files with the given ext are found.
            This implies that this method is not compatible with multiple datasets.
        """
        if ext != "abo":
            ext = ext if ext.startswith('_') else '_' + ext

        files = []
        for f in self.list_filepaths():
            # For the time being, we ignore DDB files in nc format.
            if ext == "_DDB" and f.endswith(".nc"): continue
            # Ignore BSE text files e.g. GW_NLF_MDF
            if ext == "_MDF" and not f.endswith(".nc"): continue
            # Ignore DDK.nc files (temporary workaround for v8.8.2 in which
            # the DFPT code produces a new file with DDK.nc extension that enters
            # into conflict with AbiPy convention.
            if ext == "_DDK" and f.endswith(".nc"): continue

            if f.endswith(ext) or f.endswith(ext + ".nc"):
                files.append(f)

        # This should fix the problem with the 1WF files in which the file extension convention is broken
        if not files:
            files = [f for f in self.list_filepaths() if fnmatch(f, "*%s*" % ext)]

        if not files:
            return ""

        if len(files) > 1 and single_file:
            # ABINIT users must learn that multiple datasets are bad!
            raise ValueError("Found multiple files with the same extensions:\n %s\n" % files +
                             "Please avoid using multiple datasets!")

        return files[0] if single_file else files


Instruction:
Implement a Python 3 function for
creating a simbolic link to the given file extension.

Response:
def symlink_abiext(self, inext, outext):
        """
        Create a simbolic link (outext --> inext). The file names are implicitly
        given by the ABINIT file extension.

        Example:

            outdir.symlink_abiext('1WF', 'DDK')

        creates the link out_DDK that points to out_1WF

        Return: 0 if success.

        Raise: RuntimeError
        """
        infile = self.has_abiext(inext)
        if not infile:
            raise RuntimeError('no file with extension %s in %s' % (inext, self))

        for i in range(len(infile) - 1, -1, -1):
            if infile[i] == '_':
                break
        else:
            raise RuntimeError('Extension %s could not be detected in file %s' % (inext, infile))

        outfile = infile[:i] + '_' + outext

        if os.path.exists(outfile):
            if os.path.islink(outfile):
                if os.path.realpath(outfile) == infile:
                    logger.debug("link %s already exists but it's ok because it points to the correct file" % outfile)
                    return 0
                else:
                    raise RuntimeError("Expecting link at %s already exists but it does not point to %s" % (outfile, infile))
            else:
                raise RuntimeError('Expecting link at %s but found file.' % outfile)

        os.symlink(infile, outfile)
        return 0


Instruction:
Can you generate the documentation for the following Python 3 function
def rename_abiext(self, inext, outext):
        infile = self.has_abiext(inext)
        if not infile:
            raise RuntimeError('no file with extension %s in %s' % (inext, self))

        for i in range(len(infile) - 1, -1, -1):
            if infile[i] == '_':
                break
        else:
            raise RuntimeError('Extension %s could not be detected in file %s' % (inext, infile))

        outfile = infile[:i] + '_' + outext
        shutil.move(infile, outfile)
        return 0

Response: Rename the Abinit file with extension inext with the new extension outext


Instruction:
Can you generate the documentation for the following Python 3 function
def copy_abiext(self, inext, outext):
        infile = self.has_abiext(inext)
        if not infile:
            raise RuntimeError('no file with extension %s in %s' % (inext, self))

        for i in range(len(infile) - 1, -1, -1):
            if infile[i] == '_':
                break
        else:
            raise RuntimeError('Extension %s could not be detected in file %s' % (inext, infile))

        outfile = infile[:i] + '_' + outext
        shutil.copy(infile, outfile)
        return 0

Response: Copy the Abinit file with extension inext to a new file withw extension outext


Instruction:
Can you tell what is the following Python 3 function doing
def remove_exts(self, exts):
        paths = []

        for ext in list_strings(exts):
            path = self.has_abiext(ext)
            if not path: continue
            try:
                os.remove(path)
                paths.append(path)
            except IOError:
                logger.warning("Exception while trying to remove file %s" % path)

        return paths

Response: Remove the files with the given extensions.


Instruction:
Given the following Python 3 function, write the documentation
def find_last_timden_file(self):
        regex = re.compile(r"out_TIM(\d+)_DEN(.nc)?$")

        timden_paths = [f for f in self.list_filepaths() if regex.match(os.path.basename(f))]
        if not timden_paths: return None

        # Build list of (step, path) tuples.
        stepfile_list = []
        for path in timden_paths:
            name = os.path.basename(path)
            match = regex.match(name)
            step, ncext = match.groups()
            stepfile_list.append((int(step), path))

        # DSU sort.
        last = sorted(stepfile_list, key=lambda t: t[0])[-1]
        return dict2namedtuple(step=last[0], path=last[1])

Response: This function finds the last TIM?_DEN file in the directory and returns a namedtuple of the path and step number.


Instruction:
Can you tell what is the following Python 3 function doing
def find_1wf_files(self):
        regex = re.compile(r"out_1WF(\d+)(\.nc)?$")

        wf_paths = [f for f in self.list_filepaths() if regex.match(os.path.basename(f))]
        if not wf_paths: return None

        # Build list of (pertcase, path) tuples.
        pertfile_list = []
        for path in wf_paths:
            name = os.path.basename(path)
            match = regex.match(name)
            pertcase, ncext = match.groups()
            pertfile_list.append((int(pertcase), path))

        # DSU sort.
        pertfile_list = sorted(pertfile_list, key=lambda t: t[0])
        return [dict2namedtuple(pertcase=item[0], path=item[1]) for item in pertfile_list]

Response: This method scans the directory structure and returns a list of namedtuple


Instruction:
Here you have a function in Python 3, explain what it does
def find_1den_files(self):
        regex = re.compile(r"out_DEN(\d+)(\.nc)?$")
        den_paths = [f for f in self.list_filepaths() if regex.match(os.path.basename(f))]
        if not den_paths: return None

        # Build list of (pertcase, path) tuples.
        pertfile_list = []
        for path in den_paths:
            name = os.path.basename(path)
            match = regex.match(name)
            pertcase, ncext = match.groups()
            pertfile_list.append((int(pertcase), path))

        # DSU sort.
        pertfile_list = sorted(pertfile_list, key=lambda t: t[0])
        return [dict2namedtuple(pertcase=item[0], path=item[1]) for item in pertfile_list]

Response: This method scans the directory tree for 1DEN files and returns a list of namedtuples each containing the path of the 1DEN file and the idir - ipert index.


Instruction:
Can you generate the documentation for the following Python 3 function
def fix_paths(self, paths):
        old2new, fixed_exts = {}, []

        for path in list_strings(paths):
            newpath, ext = self._fix_path(path)

            if newpath is not None:
                #if ext not in fixed_exts:
                #    if ext == "1WF": continue
                #    raise ValueError("Unknown extension %s" % ext)
                #print(ext, path, fixed_exts)
                #if ext != '1WF':
                #    assert ext not in fixed_exts
                if ext not in fixed_exts:
                    if ext == "1WF": continue
                    raise ValueError("Unknown extension %s" % ext)
                fixed_exts.append(ext)
                old2new[path] = newpath

        return old2new

Response:
Fix the filenames in the iterable paths
            - > new_path - > new_path - > new_path - > new_path - > new_path - > new_path - > old_path - > new_path - > new_path - > new_path - > new_path - > new_path - > new_path - > new_path - > new_path - > new_path - > new_path - > new_path


Instruction:
Create a Python 3 function for
converting obj into a condition object.

Response:
def as_condition(cls, obj):
        """Convert obj into :class:`Condition`"""
        if isinstance(obj, cls):
            return obj
        else:
            return cls(cmap=obj)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def plot(self, ax=None, **kwargs):
        ax, fig, plt = get_ax_fig_plt(ax)

        yy = [len(v) for v in self.values]
        ax.plot(self.binvals, yy, **kwargs)

        return fig

Response: Plot the histogram with matplotlib returns matplotlib figure.