Instruction:
Here you have a function in Python 3, explain what it does
def from_csv(cls, filename: str):
        with open(filename, "r", encoding="utf-8") as f:
            reader = csv.reader(f, delimiter=unicode2str(","),
                                quotechar=unicode2str("\""),
                                quoting=csv.QUOTE_MINIMAL)
            entries = list()
            header_read = False
            elements = None
            for row in reader:
                if not header_read:
                    elements = row[1:(len(row) - 1)]
                    header_read = True
                else:
                    name = row[0]
                    energy = float(row[-1])
                    comp = dict()
                    for ind in range(1, len(row) - 1):
                        if float(row[ind]) > 0:
                            comp[Element(elements[ind - 1])] = float(row[ind])
                    entries.append(PDEntry(Composition(comp), energy, name))
        return cls(entries)

Response: Imports PDEntries from a csv file.


Instruction:
Explain what the following Python 3 code does
def _parse_parameters(val_type, val):
    if val_type == "logical":
        return val == "T"
    elif val_type == "int":
        return int(val)
    elif val_type == "string":
        return val.strip()
    else:
        return float(val)

Response: Helper function to convert a Vasprun parameter into the proper type.


Instruction:
Here you have a function in Python 3, explain what it does
def _parse_v_parameters(val_type, val, filename, param_name):
    if val_type == "logical":
        val = [i == "T" for i in val.split()]
    elif val_type == "int":
        try:
            val = [int(i) for i in val.split()]
        except ValueError:
            # Fix for stupid error in vasprun sometimes which displays
            # LDAUL/J as 2****
            val = _parse_from_incar(filename, param_name)
            if val is None:
                raise IOError("Error in parsing vasprun.xml")
    elif val_type == "string":
        val = val.split()
    else:
        try:
            val = [float(i) for i in val.split()]
        except ValueError:
            # Fix for stupid error in vasprun sometimes which displays
            # MAGMOM as 2****
            val = _parse_from_incar(filename, param_name)
            if val is None:
                raise IOError("Error in parsing vasprun.xml")
    return val

Response: Helper function to convert a Vasprun array - type parameter into the proper base class.


Instruction:
How would you explain what the following Python 3 function does
def _vasprun_float(f):
    try:
        return float(f)
    except ValueError as e:
        f = f.strip()
        if f == '*' * len(f):
            warnings.warn('Float overflow (*******) encountered in vasprun')
            return np.nan
        raise e

Response: Convert a string to a float.


Instruction:
Can you tell what is the following Python 3 function doing
def get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None,
                                                   projections=False):
    """
    This method is used to get band structure info from a VASP directory. It
    takes into account that the run can be divided in several branches named
    "branch_x". If the run has not been divided in branches the method will
    turn to parsing vasprun.xml directly.

    The method returns None is there"s a parsing error

    Args:
        dir_name: Directory containing all bandstructure runs.
        efermi: Efermi for bandstructure.
        projections: True if you want to get the data on site projections if
            any. Note that this is sometimes very large

    Returns:
        A BandStructure Object
    """
    # TODO: Add better error handling!!!
    if os.path.exists(os.path.join(dir_name, "branch_0")):
        # get all branch dir names
        branch_dir_names = [os.path.abspath(d)
                            for d in glob.glob("{i}/branch_*"
                                               .format(i=dir_name))
                            if os.path.isdir(d)]

        # sort by the directory name (e.g, branch_10)
        sort_by = lambda x: int(x.split("_")[-1])
        sorted_branch_dir_names = sorted(branch_dir_names, key=sort_by)

        # populate branches with Bandstructure instances
        branches = []
        for dir_name in sorted_branch_dir_names:
            xml_file = os.path.join(dir_name, "vasprun.xml")
            if os.path.exists(xml_file):
                run = Vasprun(xml_file, parse_projected_eigen=projections)
                branches.append(run.get_band_structure(efermi=efermi))
            else:
                # It might be better to throw an exception
                warnings.warn("Skipping {}. Unable to find {}"
                              .format(d=dir_name, f=xml_file))

        return get_reconstructed_band_structure(branches, efermi)
    else:
        xml_file = os.path.join(dir_name, "vasprun.xml")
        # Better handling of Errors
        if os.path.exists(xml_file):
            return Vasprun(xml_file, parse_projected_eigen=projections) \
                .get_band_structure(kpoints_filename=None, efermi=efermi)
        else:
            return None

Response: This method gets the bandstructure information from a VASP directory. It takes into account that the run can be divided in several branches named branch_0 and branch_10.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_adjusted_fermi_level(efermi, cbm, band_structure):
    # make a working copy of band_structure
    bs_working = BandStructureSymmLine.from_dict(band_structure.as_dict())
    if bs_working.is_metal():
        e = efermi
        while e < cbm:
            e += 0.01
            bs_working._efermi = e
            if not bs_working.is_metal():
                return e
    return efermi

Response: This function returns the adjusted fermi level for a given fermi energy and band minimum.


Instruction:
Make a summary of the following Python 3 code
def optical_absorption_coeff(self):
        if self.dielectric_data["density"]:
            real_avg = [sum(self.dielectric_data["density"][1][i][0:3]) / 3
                        for i in range(len(self.dielectric_data["density"][0]))]
            imag_avg = [sum(self.dielectric_data["density"][2][i][0:3]) / 3
                        for i in range(len(self.dielectric_data["density"][0]))]

            def f(freq, real, imag):
                """
                The optical absorption coefficient calculated in terms of
                equation
                """
                hbar = 6.582119514e-16  # eV/K
                coeff = np.sqrt(
                    np.sqrt(real ** 2 + imag ** 2) - real) * \
                        np.sqrt(2) / hbar * freq
                return coeff

            absorption_coeff = [f(freq, real, imag) for freq, real, imag in
                                zip(self.dielectric_data["density"][0],
                                    real_avg, imag_avg)]
        return absorption_coeff

Response: Calculates the optical absorption coefficient for the current locale.


Instruction:
Can you generate the documentation for the following Python 3 function
def converged_electronic(self):
        final_esteps = self.ionic_steps[-1]["electronic_steps"]
        if 'LEPSILON' in self.incar and self.incar['LEPSILON']:
            i = 1
            to_check = set(['e_wo_entrp', 'e_fr_energy', 'e_0_energy'])
            while set(final_esteps[i].keys()) == to_check:
                i += 1
            return i + 1 != self.parameters["NELM"]
        return len(final_esteps) < self.parameters["NELM"]

Response: Checks that the electronic step convergence has been reached in the final ionic step.


Instruction:
Create a Python 3 function to
check that ionic step convergence has been reached i. e. that the vasp exited before reaching the max ionic steps for a relaxation run.

Response:
def converged_ionic(self):
        """
        Checks that ionic step convergence has been reached, i.e. that vasp
        exited before reaching the max ionic steps for a relaxation run
        """
        nsw = self.parameters.get("NSW", 0)
        return nsw <= 1 or len(self.ionic_steps) < nsw


Instruction:
Write a Python 3 function for
returning the final energy from the vasp run.

Response:
def final_energy(self):
        """
        Final energy from the vasp run.
        """
        try:
            final_istep = self.ionic_steps[-1]
            if final_istep["e_wo_entrp"] != final_istep[
                'electronic_steps'][-1]["e_0_energy"]:
                warnings.warn("Final e_wo_entrp differs from the final "
                              "electronic step. VASP may have included some "
                              "corrections, e.g., vdw. Vasprun will return "
                              "the final e_wo_entrp, i.e., including "
                              "corrections in such instances.")
                return final_istep["e_wo_entrp"]
            return final_istep['electronic_steps'][-1]["e_0_energy"]
        except (IndexError, KeyError):
            warnings.warn("Calculation does not have a total energy. "
                          "Possibly a GW or similar kind of run. A value of "
                          "infinity is returned.")
            return float('inf')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def hubbards(self):
        symbols = [s.split()[1] for s in self.potcar_symbols]
        symbols = [re.split(r"_", s)[0] for s in symbols]
        if not self.incar.get("LDAU", False):
            return {}
        us = self.incar.get("LDAUU", self.parameters.get("LDAUU"))
        js = self.incar.get("LDAUJ", self.parameters.get("LDAUJ"))
        if len(js) != len(us):
            js = [0] * len(us)
        if len(us) == len(symbols):
            return {symbols[i]: us[i] - js[i] for i in range(len(symbols))}
        elif sum(us) == 0 and sum(js) == 0:
            return {}
        else:
            raise VaspParserError("Length of U value parameters and atomic "
                                  "symbols are mismatched")

Response: Returns a dict of hubbard U values used if a vasprun is a GGA + U run.


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

        METAGGA_TYPES = {"TPSS", "RTPSS", "M06L", "MBJL", "SCAN", "MS0", "MS1", "MS2"}

        if self.parameters.get("LHFCALC", False):
            rt = "HF"
        elif self.parameters.get("METAGGA", "").strip().upper() in METAGGA_TYPES:
            rt = self.parameters["METAGGA"].strip().upper()
        elif self.parameters.get("LUSE_VDW", False):
            vdw_gga = {"RE": "DF", "OR": "optPBE", "BO": "optB88",
                       "MK": "optB86b", "ML": "DF2"}
            gga = self.parameters.get("GGA").upper()
            rt = "vdW-" + vdw_gga[gga]
        elif self.potcar_symbols[0].split()[0] == 'PAW':
            rt = "LDA"
        else:
            rt = "GGA"
        if self.is_hubbard:
            rt += "+U"
        return rt

Response: Returns the run type of the current log entry. Currently supports LDA GGA vdW - DF and HF calcs. Currently supports LDA GGA vdW - DF and HF calcs.


Instruction:
Can you create a Python 3 function that
returns True if the run is a DFT + U run.

Response:
def is_hubbard(self):
        """
        True if run is a DFT+U run.
        """
        if len(self.hubbards) == 0:
            return False
        return sum(self.hubbards.values()) > 1e-8


Instruction:
Given the following Python 3 function, write the documentation
def get_computed_entry(self, inc_structure=True, parameters=None,
                           data=None):
        """
        Returns a ComputedStructureEntry from the vasprun.

        Args:
            inc_structure (bool): Set to True if you want
                ComputedStructureEntries to be returned instead of
                ComputedEntries.
            parameters (list): Input parameters to include. It has to be one of
                the properties supported by the Vasprun object. If
                parameters is None, a default set of parameters that are
                necessary for typical post-processing will be set.
            data (list): Output data to include. Has to be one of the properties
                supported by the Vasprun object.

        Returns:
            ComputedStructureEntry/ComputedEntry
        """
        param_names = {"is_hubbard", "hubbards", "potcar_symbols",
                       "potcar_spec", "run_type"}
        if parameters:
            param_names.update(parameters)
        params = {p: getattr(self, p) for p in param_names}
        data = {p: getattr(self, p) for p in data} if data is not None else {}

        if inc_structure:
            return ComputedStructureEntry(self.final_structure,
                                          self.final_energy, parameters=params,
                                          data=data)
        else:
            return ComputedEntry(self.final_structure.composition,
                                 self.final_energy, parameters=params,
                                 data=data)

Response: Returns a ComputedStructureEntry from the vasprun.


Instruction:
How would you explain what the following Python 3 function does
def get_band_structure(self, kpoints_filename=None, efermi=None,
                           line_mode=False, force_hybrid_mode=False):
        """
        Returns the band structure as a BandStructure object

        Args:
            kpoints_filename (str): Full path of the KPOINTS file from which
                the band structure is generated.
                If none is provided, the code will try to intelligently
                determine the appropriate KPOINTS file by substituting the
                filename of the vasprun.xml with KPOINTS.
                The latter is the default behavior.
            efermi (float): If you want to specify manually the fermi energy
                this is where you should do it. By default, the None value
                means the code will get it from the vasprun.
            line_mode (bool): Force the band structure to be considered as
                a run along symmetry lines.
            force_hybrid_mode (bool): Makes it possible to read in self-consistent band structure calculations for every type of functional

        Returns:
            a BandStructure object (or more specifically a
            BandStructureSymmLine object if the run is detected to be a run
            along symmetry lines)

            Two types of runs along symmetry lines are accepted: non-sc with
            Line-Mode in the KPOINT file or hybrid, self-consistent with a
            uniform grid+a few kpoints along symmetry lines (explicit KPOINTS
            file) (it's not possible to run a non-sc band structure with hybrid
            functionals). The explicit KPOINTS file needs to have data on the
            kpoint label as commentary.
        """

        if not kpoints_filename:
            kpoints_filename = zpath(
                os.path.join(os.path.dirname(self.filename), 'KPOINTS'))
        if not os.path.exists(kpoints_filename) and line_mode is True:
            raise VaspParserError('KPOINTS needed to obtain band structure '
                                  'along symmetry lines.')

        if efermi is None:
            efermi = self.efermi

        kpoint_file = None
        if os.path.exists(kpoints_filename):
            kpoint_file = Kpoints.from_file(kpoints_filename)
        lattice_new = Lattice(self.lattice_rec.matrix)

        kpoints = [np.array(self.actual_kpoints[i])
                   for i in range(len(self.actual_kpoints))]

        p_eigenvals = defaultdict(list)
        eigenvals = defaultdict(list)

        nkpts = len(kpoints)

        neigenvalues = [len(v) for v in self.eigenvalues[Spin.up]]
        min_eigenvalues = min(neigenvalues)

        for spin, v in self.eigenvalues.items():
            v = np.swapaxes(v, 0, 1)
            eigenvals[spin] = v[:, :, 0]

            if self.projected_eigenvalues:
                peigen = self.projected_eigenvalues[spin]
                # Original axes for self.projected_eigenvalues are kpoints,
                # band, ion, orb.
                # For BS input, we need band, kpoints, orb, ion.
                peigen = np.swapaxes(peigen, 0, 1)  # Swap kpoint and band axes
                peigen = np.swapaxes(peigen, 2, 3)  # Swap ion and orb axes

                p_eigenvals[spin] = peigen
                # for b in range(min_eigenvalues):
                #     p_eigenvals[spin].append(
                #         [{Orbital(orb): v for orb, v in enumerate(peigen[b, k])}
                #          for k in range(nkpts)])

        # check if we have an hybrid band structure computation
        # for this we look at the presence of the LHFCALC tag
        hybrid_band = False
        if self.parameters.get('LHFCALC', False) or \
                0. in self.actual_kpoints_weights:
            hybrid_band = True

        if kpoint_file is not None:
            if kpoint_file.style == Kpoints.supported_modes.Line_mode:
                line_mode = True

        if line_mode:
            labels_dict = {}
            if hybrid_band or force_hybrid_mode:
                start_bs_index = 0
                for i in range(len(self.actual_kpoints)):
                    if self.actual_kpoints_weights[i] == 0.0:
                        start_bs_index = i
                        break
                for i in range(start_bs_index, len(kpoint_file.kpts)):
                    if kpoint_file.labels[i] is not None:
                        labels_dict[kpoint_file.labels[i]] = \
                            kpoint_file.kpts[i]
                # remake the data only considering line band structure k-points
                # (weight = 0.0 kpoints)
                nbands = len(eigenvals[Spin.up])
                kpoints = kpoints[start_bs_index:nkpts]
                up_eigen = [eigenvals[Spin.up][i][start_bs_index:nkpts]
                            for i in range(nbands)]
                if self.projected_eigenvalues:
                    p_eigenvals[Spin.up] = [p_eigenvals[Spin.up][i][
                                            start_bs_index:nkpts]
                                            for i in range(nbands)]
                if self.is_spin:
                    down_eigen = [eigenvals[Spin.down][i][start_bs_index:nkpts]
                                  for i in range(nbands)]
                    eigenvals = {Spin.up: up_eigen, Spin.down: down_eigen}
                    if self.projected_eigenvalues:
                        p_eigenvals[Spin.down] = [p_eigenvals[Spin.down][i][
                                                  start_bs_index:nkpts]
                                                  for i in range(nbands)]
                else:
                    eigenvals = {Spin.up: up_eigen}
            else:
                if '' in kpoint_file.labels:
                    raise Exception("A band structure along symmetry lines "
                                    "requires a label for each kpoint. "
                                    "Check your KPOINTS file")
                labels_dict = dict(zip(kpoint_file.labels, kpoint_file.kpts))
                labels_dict.pop(None, None)
            return BandStructureSymmLine(kpoints, eigenvals, lattice_new,
                                         efermi, labels_dict,
                                         structure=self.final_structure,
                                         projections=p_eigenvals)
        else:
            return BandStructure(kpoints, eigenvals, lattice_new, efermi,
                                 structure=self.final_structure,
                                 projections=p_eigenvals)

Response: Returns the band structure object for the specified kpoints file and efermi.


Instruction:
Here you have a function in Python 3, explain what it does
def eigenvalue_band_properties(self):
        vbm = -float("inf")
        vbm_kpoint = None
        cbm = float("inf")
        cbm_kpoint = None
        for spin, d in self.eigenvalues.items():
            for k, val in enumerate(d):
                for (eigenval, occu) in val:
                    if occu > self.occu_tol and eigenval > vbm:
                        vbm = eigenval
                        vbm_kpoint = k
                    elif occu <= self.occu_tol and eigenval < cbm:
                        cbm = eigenval
                        cbm_kpoint = k
        return max(cbm - vbm, 0), cbm, vbm, vbm_kpoint == cbm_kpoint

Response: Return the band properties of the eigenvalues as a tuple.


Instruction:
Make a summary of the following Python 3 code
def read_pattern(self, patterns, reverse=False, terminate_on_match=False,
                     postprocess=str):
        """
        General pattern reading. Uses monty's regrep method. Takes the same
        arguments.

        Args:
            patterns (dict): A dict of patterns, e.g.,
                {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"}.
            reverse (bool): Read files in reverse. Defaults to false. Useful for
                large files, esp OUTCARs, especially when used with
                terminate_on_match.
            terminate_on_match (bool): Whether to terminate when there is at
                least one match in each key in pattern.
            postprocess (callable): A post processing function to convert all
                matches. Defaults to str, i.e., no change.

        Renders accessible:
            Any attribute in patterns. For example,
            {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"} will set the
            value of self.data["energy"] = [[-1234], [-3453], ...], to the
            results from regex and postprocess. Note that the returned values
            are lists of lists, because you can grep multiple items on one line.
        """
        matches = regrep(self.filename, patterns, reverse=reverse,
                         terminate_on_match=terminate_on_match,
                         postprocess=postprocess)
        for k in patterns.keys():
            self.data[k] = [i[0] for i in matches.get(k, [])]

Response: General pattern reading. Uses monty s regrep method.


Instruction:
Write a Python 3 function for
parsing the entire table - like data file and returns a list of tables.

Response:
def read_table_pattern(self, header_pattern, row_pattern, footer_pattern,
                           postprocess=str, attribute_name=None,
                           last_one_only=True):
        """
        Parse table-like data. A table composes of three parts: header,
        main body, footer. All the data matches "row pattern" in the main body
        will be returned.

        Args:
            header_pattern (str): The regular expression pattern matches the
                table header. This pattern should match all the text
                immediately before the main body of the table. For multiple
                sections table match the text until the section of
                interest. MULTILINE and DOTALL options are enforced, as a
                result, the "." meta-character will also match "\n" in this
                section.
            row_pattern (str): The regular expression matches a single line in
                the table. Capture interested field using regular expression
                groups.
            footer_pattern (str): The regular expression matches the end of the
                table. E.g. a long dash line.
            postprocess (callable): A post processing function to convert all
                matches. Defaults to str, i.e., no change.
            attribute_name (str): Name of this table. If present the parsed data
                will be attached to "data. e.g. self.data["efg"] = [...]
            last_one_only (bool): All the tables will be parsed, if this option
                is set to True, only the last table will be returned. The
                enclosing list will be removed. i.e. Only a single table will
                be returned. Default to be True.

        Returns:
            List of tables. 1) A table is a list of rows. 2) A row if either a list of
            attribute values in case the the capturing group is defined without name in
            row_pattern, or a dict in case that named capturing groups are defined by
            row_pattern.
        """
        with zopen(self.filename, 'rt') as f:
            text = f.read()
        table_pattern_text = header_pattern + r"\s*^(?P<table_body>(?:\s+" + \
                             row_pattern + r")+)\s+" + footer_pattern
        table_pattern = re.compile(table_pattern_text, re.MULTILINE | re.DOTALL)
        rp = re.compile(row_pattern)
        tables = []
        for mt in table_pattern.finditer(text):
            table_body_text = mt.group("table_body")
            table_contents = []
            for line in table_body_text.split("\n"):
                ml = rp.search(line)
                d = ml.groupdict()
                if len(d) > 0:
                    processed_line = {k: postprocess(v) for k, v in d.items()}
                else:
                    processed_line = [postprocess(v) for v in ml.groups()]
                table_contents.append(processed_line)
            tables.append(table_contents)
        if last_one_only:
            retained_data = tables[-1]
        else:
            retained_data = tables
        if attribute_name is not None:
            self.data[attribute_name] = retained_data
        return retained_data


Instruction:
Create a Python 3 function for
parsing the eletrostatic potential for the last ionic step

Response:
def read_electrostatic_potential(self):
        """
        Parses the eletrostatic potential for the last ionic step
        """
        pattern = {"ngf": r"\s+dimension x,y,z NGXF=\s+([\.\-\d]+)\sNGYF=\s+([\.\-\d]+)\sNGZF=\s+([\.\-\d]+)"}
        self.read_pattern(pattern, postprocess=int)
        self.ngf = self.data.get("ngf", [[]])[0]

        pattern = {"radii": r"the test charge radii are((?:\s+[\.\-\d]+)+)"}
        self.read_pattern(pattern, reverse=True, terminate_on_match=True, postprocess=str)
        self.sampling_radii = [float(f) for f in self.data["radii"][0][0].split()]

        header_pattern = r"\(the norm of the test charge is\s+[\.\-\d]+\)"
        table_pattern = r"((?:\s+\d+\s*[\.\-\d]+)+)"
        footer_pattern = r"\s+E-fermi :"

        pots = self.read_table_pattern(header_pattern, table_pattern, footer_pattern)
        pots = "".join(itertools.chain.from_iterable(pots))

        pots = re.findall(r"\s+\d+\s?([\.\-\d]+)+", pots)
        pots = [float(f) for f in pots]

        self.electrostatic_potential = pots


Instruction:
Write a Python 3 function for
reading the frequency dependent dielectric function and returns a dictionary of the frequency dependent dielectric functions.

Response:
def read_freq_dielectric(self):
        """
        Parses the frequency dependent dielectric function (obtained with
        LOPTICS). Frequencies (in eV) are in self.frequencies, and dielectric
        tensor function is given as self.dielectric_tensor_function.
        """

        plasma_pattern = r"plasma frequency squared.*"
        dielectric_pattern = r"frequency dependent\s+IMAGINARY " \
                             r"DIELECTRIC FUNCTION \(independent particle, " \
                             r"no local field effects\)(\sdensity-density)*$"
        row_pattern = r"\s+".join([r"([\.\-\d]+)"] * 3)
        plasma_frequencies = collections.defaultdict(list)
        read_plasma = False
        read_dielectric = False
        energies = []
        data = {"REAL": [], "IMAGINARY": []}
        count = 0
        component = "IMAGINARY"
        with zopen(self.filename, "rt") as f:
            for l in f:
                l = l.strip()
                if re.match(plasma_pattern, l):
                    read_plasma = "intraband" if "intraband" in l else "interband"
                elif re.match(dielectric_pattern, l):
                    read_plasma = False
                    read_dielectric = True
                    row_pattern = r"\s+".join([r"([\.\-\d]+)"] * 7)

                if read_plasma and re.match(row_pattern, l):
                    plasma_frequencies[read_plasma].append(
                        [float(t) for t in l.strip().split()])
                elif read_dielectric:
                    if re.match(row_pattern, l.strip()):
                        toks = l.strip().split()
                        if component == "IMAGINARY":
                            energies.append(float(toks[0]))
                        xx, yy, zz, xy, yz, xz = [float(t) for t in toks[1:]]
                        matrix = [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]
                        data[component].append(matrix)
                    elif re.match(r"\s*-+\s*", l):
                        count += 1
                    if count == 2:
                        component = "REAL"
                    elif count == 3:
                        break

        self.plasma_frequencies = {k: np.array(v[:3])
                                   for k, v in plasma_frequencies.items()}
        self.dielectric_energies = np.array(energies)
        self.dielectric_tensor_function = np.array(data["REAL"]) + \
                                          1j * np.array(data["IMAGINARY"])


Instruction:
Explain what the following Python 3 code does
def read_chemical_shielding(self):
        header_pattern = r"\s+CSA tensor \(J\. Mason, Solid State Nucl\. Magn\. Reson\. 2, " \
                         r"285 \(1993\)\)\s+" \
                         r"\s+-{50,}\s+" \
                         r"\s+EXCLUDING G=0 CONTRIBUTION\s+INCLUDING G=0 CONTRIBUTION\s+" \
                         r"\s+-{20,}\s+-{20,}\s+" \
                         r"\s+ATOM\s+ISO_SHIFT\s+SPAN\s+SKEW\s+ISO_SHIFT\s+SPAN\s+SKEW\s+" \
                         r"-{50,}\s*$"
        first_part_pattern = r"\s+\(absolute, valence only\)\s+$"
        swallon_valence_body_pattern = r".+?\(absolute, valence and core\)\s+$"
        row_pattern = r"\d+(?:\s+[-]?\d+\.\d+){3}\s+" + r'\s+'.join(
            [r"([-]?\d+\.\d+)"] * 3)
        footer_pattern = r"-{50,}\s*$"
        h1 = header_pattern + first_part_pattern
        cs_valence_only = self.read_table_pattern(
            h1, row_pattern, footer_pattern, postprocess=float,
            last_one_only=True)
        h2 = header_pattern + swallon_valence_body_pattern
        cs_valence_and_core = self.read_table_pattern(
            h2, row_pattern, footer_pattern, postprocess=float,
            last_one_only=True)
        all_cs = {}
        for name, cs_table in [["valence_only", cs_valence_only],
                               ["valence_and_core", cs_valence_and_core]]:
            all_cs[name] = cs_table
        self.data["chemical_shielding"] = all_cs

Response: Parses the NMR chemical shieldings data.


Instruction:
Can you create a Python 3 function that
parses the « G0 contribution of NMR chemical shielding.

Response:
def read_cs_g0_contribution(self):
        """
            Parse the  G0 contribution of NMR chemical shielding.

            Returns:
            G0 contribution matrix as list of list.
        """
        header_pattern = r'^\s+G\=0 CONTRIBUTION TO CHEMICAL SHIFT \(field along BDIR\)\s+$\n' \
                         r'^\s+-{50,}$\n' \
                         r'^\s+BDIR\s+X\s+Y\s+Z\s*$\n' \
                         r'^\s+-{50,}\s*$\n'
        row_pattern = r'(?:\d+)\s+' + r'\s+'.join([r'([-]?\d+\.\d+)'] * 3)
        footer_pattern = r'\s+-{50,}\s*$'
        self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float,
                                last_one_only=True, attribute_name="cs_g0_contribution")


Instruction:
Can you tell what is the following Python 3 function doing
def read_cs_core_contribution(self):
        header_pattern = r'^\s+Core NMR properties\s*$\n' \
                         r'\n' \
                         r'^\s+typ\s+El\s+Core shift \(ppm\)\s*$\n' \
                         r'^\s+-{20,}$\n'
        row_pattern = r'\d+\s+(?P<element>[A-Z][a-z]?\w?)\s+(?P<shift>[-]?\d+\.\d+)'
        footer_pattern = r'\s+-{20,}\s*$'
        self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=str,
                                last_one_only=True, attribute_name="cs_core_contribution")
        core_contrib = {d['element']: float(d['shift'])
                        for d in self.data["cs_core_contribution"]}
        self.data["cs_core_contribution"] = core_contrib

Response: Parse the core contribution of NMR chemical shielding.


Instruction:
How would you explain what the following Python 3 function does
def read_cs_raw_symmetrized_tensors(self):
        header_pattern = r"\s+-{50,}\s+" \
                         r"\s+Absolute Chemical Shift tensors\s+" \
                         r"\s+-{50,}$"
        first_part_pattern = r"\s+UNSYMMETRIZED TENSORS\s+$"
        row_pattern = r"\s+".join([r"([-]?\d+\.\d+)"] * 3)
        unsym_footer_pattern = r"^\s+SYMMETRIZED TENSORS\s+$"

        with zopen(self.filename, 'rt') as f:
            text = f.read()
        unsym_table_pattern_text = header_pattern + first_part_pattern + \
                                   r"(?P<table_body>.+)" + unsym_footer_pattern
        table_pattern = re.compile(unsym_table_pattern_text,
                                   re.MULTILINE | re.DOTALL)
        rp = re.compile(row_pattern)
        m = table_pattern.search(text)
        if m:
            table_text = m.group("table_body")
            micro_header_pattern = r"ion\s+\d+"
            micro_table_pattern_text = micro_header_pattern + \
                                       r"\s*^(?P<table_body>(?:\s*" + \
                                       row_pattern + r")+)\s+"
            micro_table_pattern = re.compile(micro_table_pattern_text,
                                             re.MULTILINE | re.DOTALL)
            unsym_tensors = []
            for mt in micro_table_pattern.finditer(table_text):
                table_body_text = mt.group("table_body")
                tensor_matrix = []
                for line in table_body_text.rstrip().split("\n"):
                    ml = rp.search(line)
                    processed_line = [float(v) for v in ml.groups()]
                    tensor_matrix.append(processed_line)
                unsym_tensors.append(tensor_matrix)
            self.data["unsym_cs_tensor"] = unsym_tensors
        else:
            raise ValueError("NMR UNSYMMETRIZED TENSORS is not found")

Response: Parses the matrix form of NMR tensor before corrected to table.


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

        header_pattern = r'Electric field gradients \(V/A\^2\)\n' \
                         r'-*\n' \
                         r' ion\s+V_xx\s+V_yy\s+V_zz\s+V_xy\s+V_xz\s+V_yz\n' \
                         r'-*\n'

        row_pattern = r'\d+\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)'
        footer_pattern = r'-*\n'

        data = self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float)
        tensors = [make_symmetric_matrix_from_upper_tri(d) for d in data]
        self.data["unsym_efg_tensor"] = tensors
        return tensors

Response:
Parses the NMR Electric Field Gradient Raw Tensors
        returns a list of symmetrized matrices


Instruction:
Create a Python 3 function to
parse the NMR Electric Field Gradient interpretted values.

Response:
def read_nmr_efg(self):
        """
        Parse the NMR Electric Field Gradient interpretted values.

        Returns:
            Electric Field Gradient tensors as a list of dict in the order of atoms from OUTCAR.
            Each dict key/value pair corresponds to a component of the tensors.
        """
        header_pattern = r'^\s+NMR quadrupolar parameters\s+$\n' \
                         r'^\s+Cq : quadrupolar parameter\s+Cq=e[*]Q[*]V_zz/h$\n' \
                         r'^\s+eta: asymmetry parameters\s+\(V_yy - V_xx\)/ V_zz$\n' \
                         r'^\s+Q  : nuclear electric quadrupole moment in mb \(millibarn\)$\n' \
                         r'^-{50,}$\n' \
                         r'^\s+ion\s+Cq\(MHz\)\s+eta\s+Q \(mb\)\s+$\n' \
                         r'^-{50,}\s*$\n'
        row_pattern = r'\d+\s+(?P<cq>[-]?\d+\.\d+)\s+(?P<eta>[-]?\d+\.\d+)\s+' \
                      r'(?P<nuclear_quadrupole_moment>[-]?\d+\.\d+)'
        footer_pattern = r'-{50,}\s*$'
        self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float,
                                last_one_only=True, attribute_name="efg")


Instruction:
Can you generate the documentation for the following Python 3 function
def read_elastic_tensor(self):
        header_pattern = r"TOTAL ELASTIC MODULI \(kBar\)\s+" \
                         r"Direction\s+([X-Z][X-Z]\s+)+" \
                         r"\-+"
        row_pattern = r"[X-Z][X-Z]\s+" + r"\s+".join([r"(\-*[\.\d]+)"] * 6)
        footer_pattern = r"\-+"
        et_table = self.read_table_pattern(header_pattern, row_pattern,
                                           footer_pattern, postprocess=float)
        self.data["elastic_tensor"] = et_table

Response: Parse the elastic tensor data.


Instruction:
Can you tell what is the following Python 3 function doing
def read_piezo_tensor(self):
        header_pattern = r"PIEZOELECTRIC TENSOR  for field in x, y, " \
                         r"z\s+\(C/m\^2\)\s+([X-Z][X-Z]\s+)+\-+"
        row_pattern = r"[x-z]\s+" + r"\s+".join([r"(\-*[\.\d]+)"] * 6)
        footer_pattern = r"BORN EFFECTIVE"
        pt_table = self.read_table_pattern(header_pattern, row_pattern,
                                           footer_pattern, postprocess=float)
        self.data["piezo_tensor"] = pt_table

Response: Parse the piezo tensor data


Instruction:
Explain what the following Python 3 code does
def read_neb(self, reverse=True, terminate_on_match=True):
        patterns = {
            "energy": r"energy\(sigma->0\)\s+=\s+([\d\-\.]+)",
            "tangent_force": r"(NEB: projections on to tangent \(spring, REAL\)\s+\S+|tangential force \(eV/A\))\s+([\d\-\.]+)"
        }
        self.read_pattern(patterns, reverse=reverse,
                          terminate_on_match=terminate_on_match,
                          postprocess=str)
        self.data["energy"] = float(self.data["energy"][0][0])
        if self.data.get("tangent_force"):
            self.data["tangent_force"] = float(
                self.data["tangent_force"][0][1])

Response: Reads NEB data from the OUTCAR file.


Instruction:
Write a Python 3 script to
read the internal strain tensor and populates self. internal_strain_tensor with an array of voigt notation tensors for each site.

Response:
def read_internal_strain_tensor(self):
        """
        Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation
            tensors for each site.
        """
        search = []

        def internal_strain_start(results, match):
            results.internal_strain_ion = int(match.group(1)) - 1
            results.internal_strain_tensor.append(np.zeros((3, 6)))

        search.append([r"INTERNAL STRAIN TENSOR FOR ION\s+(\d+)\s+for displacements in x,y,z  \(eV/Angst\):",
                       None, internal_strain_start])

        def internal_strain_data(results, match):
            if match.group(1).lower() == "x":
                index = 0
            elif match.group(1).lower() == "y":
                index = 1
            elif match.group(1).lower() == "z":
                index = 2
            else:
                raise Exception(
                    "Couldn't parse row index from symbol for internal strain tensor: {}".format(match.group(1)))
            results.internal_strain_tensor[results.internal_strain_ion][index] = np.array([float(match.group(i))
                                                                                for i in range(2, 8)])
            if index == 2:
                results.internal_strain_ion = None

        search.append([r"^\s+([x,y,z])\s+" + r"([-]?\d+\.\d+)\s+" * 6, lambda results,
                                                                              line: results.internal_strain_ion is not None,
                       internal_strain_data])

        self.internal_strain_ion = None
        self.internal_strain_tensor = []
        micro_pyawk(self.filename, search, self)


Instruction:
Make a summary of the following Python 3 code
def read_pseudo_zval(self):
        try:
            def poscar_line(results, match):
                poscar_line = match.group(1)
                results.poscar_line = re.findall(r'[A-Z][a-z]?', poscar_line)

            def zvals(results, match):
                zvals = match.group(1)
                results.zvals = map(float, re.findall(r'-?\d+\.\d*', zvals))

            search = []
            search.append([r'^.*POSCAR.*=(.*)', None, poscar_line])
            search.append([r'^\s+ZVAL.*=(.*)', None, zvals])

            micro_pyawk(self.filename, search, self)

            zval_dict = {}
            for x, y in zip(self.poscar_line, self.zvals):
                zval_dict.update({x: y})
            self.zval_dict = zval_dict

            # Clean-up
            del (self.poscar_line)
            del (self.zvals)
        except:
            raise Exception("ZVAL dict could not be parsed.")

Response: Read pseudopotential ZVAL dictionary.


Instruction:
Implement a function in Python 3 to
read the core state eigenenergies at each ionic step.

Response:
def read_core_state_eigen(self):
        """
        Read the core state eigenenergies at each ionic step.

        Returns:
            A list of dict over the atom such as [{"AO":[core state eig]}].
            The core state eigenenergie list for each AO is over all ionic
            step.

        Example:
            The core state eigenenergie of the 2s AO of the 6th atom of the
            structure at the last ionic step is [5]["2s"][-1]
        """

        with zopen(self.filename, "rt") as foutcar:
            line = foutcar.readline()
            while line != "":
                line = foutcar.readline()
                if "NIONS =" in line:
                    natom = int(line.split("NIONS =")[1])
                    cl = [defaultdict(list) for i in range(natom)]
                if "the core state eigen" in line:
                    iat = -1
                    while line != "":
                        line = foutcar.readline()
                        # don't know number of lines to parse without knowing
                        # specific species, so stop parsing when we reach
                        # "E-fermi" instead
                        if "E-fermi" in line:
                            break
                        data = line.split()
                        # data will contain odd number of elements if it is
                        # the start of a new entry, or even number of elements
                        # if it continues the previous entry
                        if len(data) % 2 == 1:
                            iat += 1  # started parsing a new ion
                            data = data[1:]  # remove element with ion number
                        for i in range(0, len(data), 2):
                            cl[iat][data[i]].append(float(data[i + 1]))
        return cl


Instruction:
Write a Python 3 function for
reading the average core potentials at each ionic step.

Response:
def read_avg_core_poten(self):
        """
        Read the core potential at each ionic step.

        Returns:
            A list for each ionic step containing a list of the average core
            potentials for each atom: [[avg core pot]].

        Example:
            The average core potential of the 2nd atom of the structure at the
            last ionic step is: [-1][1]
        """

        def pairwise(iterable):
            "s -> (s0,s1), (s1,s2), (s2, s3), ..."
            a = iter(iterable)
            return zip(a, a)

        with zopen(self.filename, "rt") as foutcar:
            line = foutcar.readline()
            aps = []
            while line != "":
                line = foutcar.readline()
                if "the norm of the test charge is" in line:
                    ap = []
                    while line != "":
                        line = foutcar.readline()
                        # don't know number of lines to parse without knowing
                        # specific species, so stop parsing when we reach
                        # "E-fermi" instead
                        if "E-fermi" in line:
                            aps.append(ap)
                            break
                        data = line.split()
                        # the average core potentials of up to 5 elements are
                        # given per line
                        for i, pot in pairwise(data):
                            ap.append(float(pot))
        return aps


Instruction:
Implement a Python 3 function for
reading the Fermi contact shift table from fch data

Response:
def read_fermi_contact_shift(self):
        '''
        output example:
        Fermi contact (isotropic) hyperfine coupling parameter (MHz)
        -------------------------------------------------------------
        ion      A_pw      A_1PS     A_1AE     A_1c      A_tot
        -------------------------------------------------------------
         1      -0.002    -0.002    -0.051     0.000    -0.052
         2      -0.002    -0.002    -0.051     0.000    -0.052
         3       0.056     0.056     0.321    -0.048     0.321
        -------------------------------------------------------------
        , which corresponds to
        [[-0.002, -0.002, -0.051, 0.0, -0.052],
         [-0.002, -0.002, -0.051, 0.0, -0.052],
         [0.056, 0.056, 0.321, -0.048, 0.321]] from 'fch' data
        '''

        # Fermi contact (isotropic) hyperfine coupling parameter (MHz)
        header_pattern1 = r"\s*Fermi contact \(isotropic\) hyperfine coupling parameter \(MHz\)\s+" \
                          r"\s*\-+" \
                          r"\s*ion\s+A_pw\s+A_1PS\s+A_1AE\s+A_1c\s+A_tot\s+" \
                          r"\s*\-+"
        row_pattern1 = r'(?:\d+)\s+' + r'\s+'.join([r'([-]?\d+\.\d+)'] * 5)
        footer_pattern = r"\-+"
        fch_table = self.read_table_pattern(header_pattern1, row_pattern1,
                                            footer_pattern, postprocess=float,
                                            last_one_only=True)

        # Dipolar hyperfine coupling parameters (MHz)
        header_pattern2 = r"\s*Dipolar hyperfine coupling parameters \(MHz\)\s+" \
                          r"\s*\-+" \
                          r"\s*ion\s+A_xx\s+A_yy\s+A_zz\s+A_xy\s+A_xz\s+A_yz\s+" \
                          r"\s*\-+"
        row_pattern2 = r'(?:\d+)\s+' + r'\s+'.join([r'([-]?\d+\.\d+)'] * 6)
        dh_table = self.read_table_pattern(header_pattern2, row_pattern2,
                                           footer_pattern, postprocess=float,
                                           last_one_only=True)

        # Total hyperfine coupling parameters after diagonalization (MHz)
        header_pattern3 = r"\s*Total hyperfine coupling parameters after diagonalization \(MHz\)\s+" \
                          r"\s*\(convention: \|A_zz\| > \|A_xx\| > \|A_yy\|\)\s+" \
                          r"\s*\-+" \
                          r"\s*ion\s+A_xx\s+A_yy\s+A_zz\s+asymmetry \(A_yy - A_xx\)/ A_zz\s+" \
                          r"\s*\-+"
        row_pattern3 = r'(?:\d+)\s+' + r'\s+'.join([r'([-]?\d+\.\d+)'] * 4)
        th_table = self.read_table_pattern(header_pattern3, row_pattern3,
                                           footer_pattern, postprocess=float,
                                           last_one_only=True)

        fc_shift_table = {'fch': fch_table, 'dh': dh_table, 'th': th_table}

        self.data["fermi_contact_shift"] = fc_shift_table


Instruction:
Can you implement a function in Python 3 that
returns the grid for a particular axis.

Response:
def get_axis_grid(self, ind):
        """
        Returns the grid for a particular axis.

        Args:
            ind (int): Axis index.
        """
        ng = self.dim
        num_pts = ng[ind]
        lengths = self.structure.lattice.abc
        return [i / num_pts * lengths[ind] for i in range(num_pts)]


Instruction:
How would you explain what the following Python 3 function does
def parse_file(filename):
        poscar_read = False
        poscar_string = []
        dataset = []
        all_dataset = []
        # for holding any strings in input that are not Poscar
        # or VolumetricData (typically augmentation charges)
        all_dataset_aug = {}
        dim = None
        dimline = None
        read_dataset = False
        ngrid_pts = 0
        data_count = 0
        poscar = None
        with zopen(filename, "rt") as f:
            for line in f:
                original_line = line
                line = line.strip()
                if read_dataset:
                    toks = line.split()
                    for tok in toks:
                        if data_count < ngrid_pts:
                            # This complicated procedure is necessary because
                            # vasp outputs x as the fastest index, followed by y
                            # then z.
                            x = data_count % dim[0]
                            y = int(math.floor(data_count / dim[0])) % dim[1]
                            z = int(math.floor(data_count / dim[0] / dim[1]))
                            dataset[x, y, z] = float(tok)
                            data_count += 1
                    if data_count >= ngrid_pts:
                        read_dataset = False
                        data_count = 0
                        all_dataset.append(dataset)
                elif not poscar_read:
                    if line != "" or len(poscar_string) == 0:
                        poscar_string.append(line)
                    elif line == "":
                        poscar = Poscar.from_string("\n".join(poscar_string))
                        poscar_read = True
                elif not dim:
                    dim = [int(i) for i in line.split()]
                    ngrid_pts = dim[0] * dim[1] * dim[2]
                    dimline = line
                    read_dataset = True
                    dataset = np.zeros(dim)
                elif line == dimline:
                    # when line == dimline, expect volumetric data to follow
                    # so set read_dataset to True
                    read_dataset = True
                    dataset = np.zeros(dim)
                else:
                    # store any extra lines that were not part of the
                    # volumetric data so we know which set of data the extra
                    # lines are associated with
                    key = len(all_dataset) - 1
                    if key not in all_dataset_aug:
                        all_dataset_aug[key] = []
                    all_dataset_aug[key].append(original_line)
            if len(all_dataset) == 4:

                data = {"total": all_dataset[0], "diff_x": all_dataset[1],
                        "diff_y": all_dataset[2], "diff_z": all_dataset[3]}
                data_aug = {"total": all_dataset_aug.get(0, None),
                            "diff_x": all_dataset_aug.get(1, None),
                            "diff_y": all_dataset_aug.get(2, None),
                            "diff_z": all_dataset_aug.get(3, None)}

                # construct a "diff" dict for scalar-like magnetization density,
                # referenced to an arbitrary direction (using same method as
                # pymatgen.electronic_structure.core.Magmom, see
                # Magmom documentation for justification for this)
                # TODO: re-examine this, and also similar behavior in
                # Magmom - @mkhorton
                # TODO: does CHGCAR change with different SAXIS?
                diff_xyz = np.array([data["diff_x"], data["diff_y"],
                                     data["diff_z"]])
                diff_xyz = diff_xyz.reshape((3, dim[0] * dim[1] * dim[2]))
                ref_direction = np.array([1.01, 1.02, 1.03])
                ref_sign = np.sign(np.dot(ref_direction, diff_xyz))
                diff = np.multiply(np.linalg.norm(diff_xyz, axis=0), ref_sign)
                data["diff"] = diff.reshape((dim[0], dim[1], dim[2]))

            elif len(all_dataset) == 2:
                data = {"total": all_dataset[0], "diff": all_dataset[1]}
                data_aug = {"total": all_dataset_aug.get(0, None),
                            "diff": all_dataset_aug.get(1, None)}
            else:
                data = {"total": all_dataset[0]}
                data_aug = {"total": all_dataset_aug.get(0, None)}
            return poscar, data, data_aug

Response: Parses a generic volumetric data file in the vasp - specific format.


Instruction:
Can you generate the documentation for the following Python 3 function
def write_file(self, file_name, vasp4_compatible=False):

        def _print_fortran_float(f):
            """
            Fortran codes print floats with a leading zero in scientific
            notation. When writing CHGCAR files, we adopt this convention
            to ensure written CHGCAR files are byte-to-byte identical to
            their input files as far as possible.
            :param f: float
            :return: str
            """
            s = "{:.10E}".format(f)
            if f >= 0:
                return "0." + s[0] + s[2:12] + 'E' + "{:+03}".format(int(s[13:]) + 1)
            else:
                return "-." + s[1] + s[3:13] + 'E' + "{:+03}".format(int(s[14:]) + 1)

        with zopen(file_name, "wt") as f:
            p = Poscar(self.structure)

            # use original name if it's been set (e.g. from Chgcar)
            comment = getattr(self, 'name', p.comment)

            lines = comment + "\n"
            lines += "   1.00000000000000\n"
            latt = self.structure.lattice.matrix
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[0, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[1, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[2, :])
            if not vasp4_compatible:
                lines += "".join(["%5s" % s for s in p.site_symbols]) + "\n"
            lines += "".join(["%6d" % x for x in p.natoms]) + "\n"
            lines += "Direct\n"
            for site in self.structure:
                lines += "%10.6f%10.6f%10.6f\n" % tuple(site.frac_coords)
            lines += " \n"
            f.write(lines)
            a = self.dim

            def write_spin(data_type):
                lines = []
                count = 0
                f.write("   {}   {}   {}\n".format(a[0], a[1], a[2]))
                for (k, j, i) in itertools.product(list(range(a[2])),
                                                   list(range(a[1])),
                                                   list(range(a[0]))):
                    lines.append(_print_fortran_float(self.data[data_type][i, j, k]))
                    count += 1
                    if count % 5 == 0:
                        f.write(" " + "".join(lines) + "\n")
                        lines = []
                    else:
                        lines.append(" ")
                f.write(" " + "".join(lines) + " \n")
                f.write("".join(self.data_aug.get(data_type, [])))

            write_spin("total")
            if self.is_spin_polarized and self.is_soc:
                write_spin("diff_x")
                write_spin("diff_y")
                write_spin("diff_z")
            elif self.is_spin_polarized:
                write_spin("diff")

Response: Writes the VolumetricData object to a vasp compatible file.


Instruction:
Write a Python 3 script to
return the integrated difference of atom index ind up to radius.

Response:
def get_integrated_diff(self, ind, radius, nbins=1):
        """
        Get integrated difference of atom index ind up to radius. This can be
        an extremely computationally intensive process, depending on how many
        grid points are in the VolumetricData.

        Args:
            ind (int): Index of atom.
            radius (float): Radius of integration.
            nbins (int): Number of bins. Defaults to 1. This allows one to
                obtain the charge integration up to a list of the cumulative
                charge integration values for radii for [radius/nbins,
                2 * radius/nbins, ....].

        Returns:
            Differential integrated charge as a np array of [[radius, value],
            ...]. Format is for ease of plotting. E.g., plt.plot(data[:,0],
            data[:,1])
        """
        # For non-spin-polarized runs, this is zero by definition.
        if not self.is_spin_polarized:
            radii = [radius / nbins * (i + 1) for i in range(nbins)]
            data = np.zeros((nbins, 2))
            data[:, 0] = radii
            return data

        struct = self.structure
        a = self.dim
        if ind not in self._distance_matrix or \
                self._distance_matrix[ind]["max_radius"] < radius:
            coords = []
            for (x, y, z) in itertools.product(*[list(range(i)) for i in a]):
                coords.append([x / a[0], y / a[1], z / a[2]])
            sites_dist = struct.lattice.get_points_in_sphere(
                coords, struct[ind].coords, radius)
            self._distance_matrix[ind] = {"max_radius": radius,
                                          "data": np.array(sites_dist)}

        data = self._distance_matrix[ind]["data"]

        # Use boolean indexing to find all charges within the desired distance.
        inds = data[:, 1] <= radius
        dists = data[inds, 1]
        data_inds = np.rint(np.mod(list(data[inds, 0]), 1) *
                            np.tile(a, (len(dists), 1))).astype(int)
        vals = [self.data["diff"][x, y, z] for x, y, z in data_inds]

        hist, edges = np.histogram(dists, bins=nbins,
                                   range=[0, radius],
                                   weights=vals)
        data = np.zeros((nbins, 2))
        data[:, 0] = edges[1:]
        data[:, 1] = [sum(hist[0:i + 1]) / self.ngridpts
                      for i in range(nbins)]
        return data


Instruction:
Explain what the following Python 3 code does
def get_average_along_axis(self, ind):
        m = self.data["total"]
        ng = self.dim
        if ind == 0:
            total = np.sum(np.sum(m, axis=1), 1)
        elif ind == 1:
            total = np.sum(np.sum(m, axis=0), 1)
        else:
            total = np.sum(np.sum(m, axis=0), 0)
        return total / ng[(ind + 1) % 3] / ng[(ind + 2) % 3]

Response: Get the averaged total of the volumetric data along a certain axis.


Instruction:
How would you explain what the following Python 3 function does
def to_hdf5(self, filename):
        import h5py
        with h5py.File(filename, "w") as f:
            ds = f.create_dataset("lattice", (3, 3), dtype='float')
            ds[...] = self.structure.lattice.matrix
            ds = f.create_dataset("Z", (len(self.structure.species),),
                                  dtype="i")
            ds[...] = np.array([sp.Z for sp in self.structure.species])
            ds = f.create_dataset("fcoords", self.structure.frac_coords.shape,
                                  dtype='float')
            ds[...] = self.structure.frac_coords
            dt = h5py.special_dtype(vlen=str)
            ds = f.create_dataset("species", (len(self.structure.species),),
                                  dtype=dt)
            ds[...] = [str(sp) for sp in self.structure.species]
            grp = f.create_group("vdata")
            for k, v in self.data.items():
                ds = grp.create_dataset(k, self.data[k].shape, dtype='float')
                ds[...] = self.data[k]
            f.attrs["name"] = self.name
            f.attrs["structure_json"] = json.dumps(self.structure.as_dict())

Response: Writes the VolumetricData to a HDF5 file.


Instruction:
How would you implement a function in Python 3 that
returns the occupation for a particular orbital of a particular atom.

Response:
def get_occupation(self, atom_index, orbital):
        """
        Returns the occupation for a particular orbital of a particular atom.

        Args:
            atom_num (int): Index of atom in the PROCAR. It should be noted
                that VASP uses 1-based indexing for atoms, but this is
                converted to 0-based indexing in this parser to be
                consistent with representation of structures in pymatgen.
            orbital (str): An orbital. If it is a single character, e.g., s,
                p, d or f, the sum of all s-type, p-type, d-type or f-type
                orbitals occupations are returned respectively. If it is a
                specific orbital, e.g., px, dxy, etc., only the occupation
                of that orbital is returned.

        Returns:
            Sum occupation of orbital of atom.
        """

        orbital_index = self.orbitals.index(orbital)
        return {spin: np.sum(d[:, :, atom_index, orbital_index] * self.weights[:, None])
                for spin, d in self.data.items()}


Instruction:
Create a Python 3 function for
returning a tuple of all energies from all electronic steps and ionic steps as a list of energies

Response:
def all_energies(self):
        """
        Compilation of all energies from all electronic steps and ionic steps
        as a tuple of list of energies, e.g.,
        ((4507.24605593, 143.824705755, -512.073149912, ...), ...)
        """
        all_energies = []
        for i in range(len(self.electronic_steps)):
            energies = [step["E"] for step in self.electronic_steps[i]]
            energies.append(self.ionic_steps[i]["F"])
            all_energies.append(tuple(energies))
        return tuple(all_energies)


Instruction:
How would you explain what the following Python 3 function does
def site_symbols(self):
        syms = [site.specie.symbol for site in self.structures[0]]
        return [a[0] for a in itertools.groupby(syms)]

Response: Sequence of symbols associated with the Xdatcar.


Instruction:
Write a Python 3 script to
sequence of number of sites of each type associated with the Poscar.

Response:
def natoms(self):
        """
        Sequence of number of sites of each type associated with the Poscar.
        Similar to 7th line in vasp 5+ Xdatcar.
        """
        syms = [site.specie.symbol for site in self.structures[0]]
        return [len(tuple(a[1])) for a in itertools.groupby(syms)]


Instruction:
How would you explain what the following Python 3 function does
def get_string(self, ionicstep_start=1,
                   ionicstep_end=None,
                   significant_figures=8):
        """
        Write  Xdatcar class into a file
        Args:
            filename (str): Filename of output XDATCAR file.
            ionicstep_start (int): Starting number of ionic step.
            ionicstep_end (int): Ending number of ionic step.
        """
        from pymatgen.io.vasp import Poscar
        if (ionicstep_start < 1):
            raise Exception('Start ionic step cannot be less than 1')
        if (ionicstep_end is not None and
                ionicstep_start < 1):
            raise Exception('End ionic step cannot be less than 1')
        latt = self.structures[0].lattice
        if np.linalg.det(latt.matrix) < 0:
            latt = Lattice(-latt.matrix)
        lines = [self.comment, "1.0", str(latt)]
        lines.append(" ".join(self.site_symbols))
        lines.append(" ".join([str(x) for x in self.natoms]))
        format_str = "{{:.{0}f}}".format(significant_figures)
        ionicstep_cnt = 1
        output_cnt = 1
        for cnt, structure in enumerate(self.structures):
            ionicstep_cnt = cnt + 1
            if ionicstep_end is None:
                if (ionicstep_cnt >= ionicstep_start):
                    lines.append("Direct configuration=" +
                                 ' ' * (7 - len(str(output_cnt))) + str(output_cnt))
                    for (i, site) in enumerate(structure):
                        coords = site.frac_coords
                        line = " ".join([format_str.format(c) for c in coords])
                        lines.append(line)
                    output_cnt += 1
            else:
                if ionicstep_start <= ionicstep_cnt < ionicstep_end:
                    lines.append("Direct configuration=" +
                                 ' ' * (7 - len(str(output_cnt))) + str(output_cnt))
                    for (i, site) in enumerate(structure):
                        coords = site.frac_coords
                        line = " ".join([format_str.format(c) for c in coords])
                        lines.append(line)
                    output_cnt += 1
        return "\n".join(lines) + "\n"

Response: Return a string representation of the XDATCAR file.


Instruction:
Given the following Python 3 function, write the documentation
def evaluate_wavefunc(self, kpoint, band, r, spin=0):
        v = self.Gpoints[kpoint] + self.kpoints[kpoint]
        u = np.dot(np.dot(v, self.b), r)
        c = self.coeffs[spin][kpoint][band] if self.spin == 2 else \
            self.coeffs[kpoint][band]
        return np.sum(np.dot(c, np.exp(1j * u, dtype=np.complex64))) / \
               np.sqrt(self.vol)

Response: Evaluates the wavefunction at a given position r.


Instruction:
Here you have a function in Python 3, explain what it does
def fft_mesh(self, kpoint, band, spin=0, shift=True):
        mesh = np.zeros(tuple(self.ng), dtype=np.complex)
        tcoeffs = self.coeffs[spin][kpoint][band] if self.spin == 2 else \
            self.coeffs[kpoint][band]
        for gp, coeff in zip(self.Gpoints[kpoint], tcoeffs):
            t = tuple(gp.astype(np.int) + (self.ng / 2).astype(np.int))
            mesh[t] = coeff
        if shift:
            return np.fft.ifftshift(mesh)
        else:
            return mesh

Response: This function takes a wavefunction and returns a 3D mesh of the coefficients of the wavefunction at the specified kpoint and band.


Instruction:
Write a Python 3 function that can
generate a Chgcar object, which is the charge density of the specified wavefunction. This function generates a Chgcar object with the charge density of the wavefunction specified by band and kpoint (and spin, if the WAVECAR corresponds to a spin-polarized calculation). The phase tag is a feature that is not present in VASP. For a real wavefunction, the phase tag being turned on means that the charge density is multiplied by the sign of the wavefunction at that point in space. A warning is generated if the phase tag is on and the chosen kpoint is not Gamma. Note: Augmentation from the PAWs is NOT included in this function. The maximal charge density will differ from the PARCHG from VASP, but the qualitative shape of the charge density will match. Args: poscar (pymatgen.io.vasp.inputs.Poscar): Poscar object that has the structure associated with the WAVECAR file kpoint (int): the index of the kpoint for the wavefunction band (int): the index of the band for the wavefunction spin (int): optional argument to specify the spin. If the Wavecar has ISPIN = 2, spin == None generates a Chgcar with total spin and magnetization, and spin == {0, 1} specifies just the spin up or down component. phase (bool): flag to determine if the charge density is multiplied by the sign of the wavefunction. Only valid for real wavefunctions. scale (int): scaling for the FFT grid. The default value of 2 is at least as fine as the VASP default. Returns: a pymatgen.io.vasp.outputs.Chgcar object

Response:
def get_parchg(self, poscar, kpoint, band, spin=None, phase=False,
                   scale=2):
        """
        Generates a Chgcar object, which is the charge density of the specified
        wavefunction.

        This function generates a Chgcar object with the charge density of the
        wavefunction specified by band and kpoint (and spin, if the WAVECAR
        corresponds to a spin-polarized calculation). The phase tag is a
        feature that is not present in VASP. For a real wavefunction, the phase
        tag being turned on means that the charge density is multiplied by the
        sign of the wavefunction at that point in space. A warning is generated
        if the phase tag is on and the chosen kpoint is not Gamma.

        Note: Augmentation from the PAWs is NOT included in this function. The
        maximal charge density will differ from the PARCHG from VASP, but the
        qualitative shape of the charge density will match.

        Args:
            poscar (pymatgen.io.vasp.inputs.Poscar): Poscar object that has the
                                structure associated with the WAVECAR file
            kpoint (int):   the index of the kpoint for the wavefunction
            band (int):     the index of the band for the wavefunction
            spin (int):     optional argument to specify the spin. If the
                                Wavecar has ISPIN = 2, spin == None generates a
                                Chgcar with total spin and magnetization, and
                                spin == {0, 1} specifies just the spin up or
                                down component.
            phase (bool):   flag to determine if the charge density is
                                multiplied by the sign of the wavefunction.
                                Only valid for real wavefunctions.
            scale (int):    scaling for the FFT grid. The default value of 2 is
                                at least as fine as the VASP default.
        Returns:
            a pymatgen.io.vasp.outputs.Chgcar object
        """

        if phase and not np.all(self.kpoints[kpoint] == 0.):
            warnings.warn('phase == True should only be used for the Gamma '
                          'kpoint! I hope you know what you\'re doing!')

        # scaling of ng for the fft grid, need to restore value at the end
        temp_ng = self.ng
        self.ng = self.ng * scale
        N = np.prod(self.ng)

        data = {}
        if self.spin == 2:
            if spin is not None:
                wfr = np.fft.ifftn(self.fft_mesh(kpoint, band, spin=spin)) * N
                den = np.abs(np.conj(wfr) * wfr)
                if phase:
                    den = np.sign(np.real(wfr)) * den
                data['total'] = den
            else:
                wfr = np.fft.ifftn(self.fft_mesh(kpoint, band, spin=0)) * N
                denup = np.abs(np.conj(wfr) * wfr)
                wfr = np.fft.ifftn(self.fft_mesh(kpoint, band, spin=1)) * N
                dendn = np.abs(np.conj(wfr) * wfr)
                data['total'] = denup + dendn
                data['diff'] = denup - dendn
        else:
            wfr = np.fft.ifftn(self.fft_mesh(kpoint, band)) * N
            den = np.abs(np.conj(wfr) * wfr)
            if phase:
                den = np.sign(np.real(wfr)) * den
            data['total'] = den

        self.ng = temp_ng
        return Chgcar(poscar, data)


Instruction:
Can you tell what is the following Python 3 function doing
def from_rotation_and_translation(
            rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)),
            translation_vec=(0, 0, 0), tol=0.1):
        """
        Creates a symmetry operation from a rotation matrix and a translation
        vector.

        Args:
            rotation_matrix (3x3 array): Rotation matrix.
            translation_vec (3x1 array): Translation vector.
            tol (float): Tolerance to determine if rotation matrix is valid.

        Returns:
            SymmOp object
        """
        rotation_matrix = np.array(rotation_matrix)
        translation_vec = np.array(translation_vec)
        if rotation_matrix.shape != (3, 3):
            raise ValueError("Rotation Matrix must be a 3x3 numpy array.")
        if translation_vec.shape != (3,):
            raise ValueError("Translation vector must be a rank 1 numpy array "
                             "with 3 elements.")
        affine_matrix = np.eye(4)
        affine_matrix[0:3][:, 0:3] = rotation_matrix
        affine_matrix[0:3][:, 3] = translation_vec
        return SymmOp(affine_matrix, tol)

Response: Creates a SymmOp object from a rotation matrix and a translation vector.


Instruction:
Can you generate the documentation for the following Python 3 function
def operate(self, point):
        affine_point = np.array([point[0], point[1], point[2], 1])
        return np.dot(self.affine_matrix, affine_point)[0:3]

Response: Apply the operation on a point.


Instruction:
Make a summary of the following Python 3 code
def operate_multi(self, points):
        points = np.array(points)
        affine_points = np.concatenate(
            [points, np.ones(points.shape[:-1] + (1,))], axis=-1)
        return np.inner(affine_points, self.affine_matrix)[..., :-1]

Response: Apply the operation on a list of points.


Instruction:
Create a Python 3 function for
applying rotation portion to a tensor.

Response:
def transform_tensor(self, tensor):
        """
        Applies rotation portion to a tensor. Note that tensor has to be in
        full form, not the Voigt form.

        Args:
            tensor (numpy array): a rank n tensor

        Returns:
            Transformed tensor.
        """
        dim = tensor.shape
        rank = len(dim)
        assert all([i == 3 for i in dim])
        # Build einstein sum string
        lc = string.ascii_lowercase
        indices = lc[:rank], lc[rank:2 * rank]
        einsum_string = ','.join([a + i for a, i in zip(*indices)])
        einsum_string += ',{}->{}'.format(*indices[::-1])
        einsum_args = [self.rotation_matrix] * rank + [tensor]

        return np.einsum(einsum_string, *einsum_args)


Instruction:
How would you explain what the following Python 3 function does
def are_symmetrically_related(self, point_a, point_b, tol=0.001):
        if np.allclose(self.operate(point_a), point_b, atol=tol):
            return True
        if np.allclose(self.operate(point_b), point_a, atol=tol):
            return True
        return False

Response: Checks if two points are symmetrically related.


Instruction:
Here you have a function in Python 3, explain what it does
def inverse(self):
        invr = np.linalg.inv(self.affine_matrix)
        return SymmOp(invr)

Response: Returns inverse of transformation.


Instruction:
Write a Python 3 function for
generating a SymmOp for a rotation about a given axis and a translation vector.

Response:
def from_axis_angle_and_translation(axis, angle, angle_in_radians=False,
                                        translation_vec=(0, 0, 0)):
        """
        Generates a SymmOp for a rotation about a given axis plus translation.

        Args:
            axis: The axis of rotation in cartesian space. For example,
                [1, 0, 0]indicates rotation about x-axis.
            angle (float): Angle of rotation.
            angle_in_radians (bool): Set to True if angles are given in
                radians. Or else, units of degrees are assumed.
            translation_vec: A translation vector. Defaults to zero.

        Returns:
            SymmOp for a rotation about given axis and translation.
        """
        if isinstance(axis, (tuple, list)):
            axis = np.array(axis)

        if isinstance(translation_vec, (tuple, list)):
            vec = np.array(translation_vec)
        else:
            vec = translation_vec

        a = angle if angle_in_radians else angle * pi / 180
        cosa = cos(a)
        sina = sin(a)
        u = axis / np.linalg.norm(axis)
        r = np.zeros((3, 3))
        r[0, 0] = cosa + u[0] ** 2 * (1 - cosa)
        r[0, 1] = u[0] * u[1] * (1 - cosa) - u[2] * sina
        r[0, 2] = u[0] * u[2] * (1 - cosa) + u[1] * sina
        r[1, 0] = u[0] * u[1] * (1 - cosa) + u[2] * sina
        r[1, 1] = cosa + u[1] ** 2 * (1 - cosa)
        r[1, 2] = u[1] * u[2] * (1 - cosa) - u[0] * sina
        r[2, 0] = u[0] * u[2] * (1 - cosa) - u[1] * sina
        r[2, 1] = u[1] * u[2] * (1 - cosa) + u[0] * sina
        r[2, 2] = cosa + u[2] ** 2 * (1 - cosa)

        return SymmOp.from_rotation_and_translation(r, vec)


Instruction:
Can you tell what is the following Python 3 function doing
def from_origin_axis_angle(origin, axis, angle, angle_in_radians=False):
        theta = angle * pi / 180 if not angle_in_radians else angle
        a = origin[0]
        b = origin[1]
        c = origin[2]
        u = axis[0]
        v = axis[1]
        w = axis[2]
        # Set some intermediate values.
        u2 = u * u
        v2 = v * v
        w2 = w * w
        cos_t = cos(theta)
        sin_t = sin(theta)
        l2 = u2 + v2 + w2
        l = sqrt(l2)

        # Build the matrix entries element by element.
        m11 = (u2 + (v2 + w2) * cos_t) / l2
        m12 = (u * v * (1 - cos_t) - w * l * sin_t) / l2
        m13 = (u * w * (1 - cos_t) + v * l * sin_t) / l2
        m14 = (a * (v2 + w2) - u * (b * v + c * w) +
               (u * (b * v + c * w) - a * (v2 + w2)) * cos_t +
               (b * w - c * v) * l * sin_t) / l2

        m21 = (u * v * (1 - cos_t) + w * l * sin_t) / l2
        m22 = (v2 + (u2 + w2) * cos_t) / l2
        m23 = (v * w * (1 - cos_t) - u * l * sin_t) / l2
        m24 = (b * (u2 + w2) - v * (a * u + c * w) +
               (v * (a * u + c * w) - b * (u2 + w2)) * cos_t +
               (c * u - a * w) * l * sin_t) / l2

        m31 = (u * w * (1 - cos_t) - v * l * sin_t) / l2
        m32 = (v * w * (1 - cos_t) + u * l * sin_t) / l2
        m33 = (w2 + (u2 + v2) * cos_t) / l2
        m34 = (c * (u2 + v2) - w * (a * u + b * v) +
               (w * (a * u + b * v) - c * (u2 + v2)) * cos_t +
               (a * v - b * u) * l * sin_t) / l2

        return SymmOp([[m11, m12, m13, m14], [m21, m22, m23, m24],
                       [m31, m32, m33, m34], [0, 0, 0, 1]])

Response: Generates a SymmOp for a rotation about a given axis through an origin.


Instruction:
Can you write a function in Python 3 where it
returns the reflection symmetry operation for the current object.

Response:
def reflection(normal, origin=(0, 0, 0)):
        """
        Returns reflection symmetry operation.

        Args:
            normal (3x1 array): Vector of the normal to the plane of
                reflection.
            origin (3x1 array): A point in which the mirror plane passes
                through.

        Returns:
            SymmOp for the reflection about the plane
        """
        # Normalize the normal vector first.
        n = np.array(normal, dtype=float) / np.linalg.norm(normal)

        u, v, w = n

        translation = np.eye(4)
        translation[0:3, 3] = -np.array(origin)

        xx = 1 - 2 * u ** 2
        yy = 1 - 2 * v ** 2
        zz = 1 - 2 * w ** 2
        xy = -2 * u * v
        xz = -2 * u * w
        yz = -2 * v * w
        mirror_mat = [[xx, xy, xz, 0], [xy, yy, yz, 0], [xz, yz, zz, 0],
                      [0, 0, 0, 1]]

        if np.linalg.norm(origin) > 1e-6:
            mirror_mat = np.dot(np.linalg.inv(translation),
                                np.dot(mirror_mat, translation))
        return SymmOp(mirror_mat)


Instruction:
Write a Python 3 function that can
return a roto - reflection symmetry operation that rotates the object with the specified axis and angle.

Response:
def rotoreflection(axis, angle, origin=(0, 0, 0)):
        """
        Returns a roto-reflection symmetry operation

        Args:
            axis (3x1 array): Axis of rotation / mirror normal
            angle (float): Angle in degrees
            origin (3x1 array): Point left invariant by roto-reflection.
                Defaults to (0, 0, 0).

        Return:
            Roto-reflection operation
        """
        rot = SymmOp.from_origin_axis_angle(origin, axis, angle)
        refl = SymmOp.reflection(axis, origin)
        m = np.dot(rot.affine_matrix, refl.affine_matrix)
        return SymmOp(m)


Instruction:
Write a Python 3 script to
return a string of the form x y z

Response:
def as_xyz_string(self):
        """
        Returns a string of the form 'x, y, z', '-x, -y, z',
        '-y+1/2, x+1/2, z+1/2', etc. Only works for integer rotation matrices
        """
        xyz = ['x', 'y', 'z']
        strings = []

        # test for invalid rotation matrix
        if not np.all(np.isclose(self.rotation_matrix,
                                 np.round(self.rotation_matrix))):
            warnings.warn('Rotation matrix should be integer')

        return transformation_to_string(self.rotation_matrix, translation_vec=self.translation_vector, delim=", ")


Instruction:
Implement a Python 3 function for
applying time reversal operator on the magnetic moment.

Response:
def operate_magmom(self, magmom):
        """
        Apply time reversal operator on the magnetic moment. Note that
        magnetic moments transform as axial vectors, not polar vectors.

        See 'Symmetry and magnetic structures', Rodríguez-Carvajal and
        Bourée for a good discussion. DOI: 10.1051/epjconf/20122200010

        Args:
            magmom: Magnetic moment as electronic_structure.core.Magmom
            class or as list or np array-like

        Returns:
            Magnetic moment after operator applied as Magmom class
        """

        magmom = Magmom(magmom)  # type casting to handle lists as input

        transformed_moment = self.apply_rotation_only(magmom.global_moment) * \
            np.linalg.det(self.rotation_matrix) * self.time_reversal

        # retains input spin axis if different from default
        return Magmom.from_global_moment_and_saxis(transformed_moment, magmom.saxis)


Instruction:
Can you generate the documentation for the following Python 3 function
def from_symmop(cls, symmop, time_reversal):
        magsymmop = cls(symmop.affine_matrix, time_reversal, symmop.tol)
        return magsymmop

Response: Initialize a MagSymmOp object from a SymmOp and time reversal operator.


Instruction:
Make a summary of the following Python 3 code
def from_rotation_and_translation_and_time_reversal(
            rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)),
            translation_vec=(0, 0, 0), time_reversal=1, tol=0.1):
        """
        Creates a symmetry operation from a rotation matrix, translation
        vector and time reversal operator.

        Args:
            rotation_matrix (3x3 array): Rotation matrix.
            translation_vec (3x1 array): Translation vector.
            time_reversal (int): Time reversal operator, +1 or -1.
            tol (float): Tolerance to determine if rotation matrix is valid.

        Returns:
            MagSymmOp object
        """
        symmop = SymmOp.from_rotation_and_translation(rotation_matrix=rotation_matrix,
                                                      translation_vec=translation_vec,
                                                      tol=tol)
        return MagSymmOp.from_symmop(symmop, time_reversal)

Response: Creates a symmetry operation from a rotation matrix translation vector and time reversal operator.


Instruction:
How would you explain what the following Python 3 function does
def from_xyzt_string(xyzt_string):
        symmop = SymmOp.from_xyz_string(xyzt_string.rsplit(',', 1)[0])
        try:
            time_reversal = int(xyzt_string.rsplit(',', 1)[1])
        except:
            raise Exception("Time reversal operator could not be parsed.")
        return MagSymmOp.from_symmop(symmop, time_reversal)

Response: Returns a new object from a string containing the string representation of a set of system - specific elements.


Instruction:
How would you explain what the following Python 3 function does
def as_xyzt_string(self):
        xyzt_string = SymmOp.as_xyz_string(self)
        return xyzt_string + ", {:+}".format(self.time_reversal)

Response: Returns the string representation of the current object as a xyzt string.


Instruction:
Implement a Python 3 function for
creating a new instance of the class object from a Molecule object.

Response:
def from_molecule(cls, mol, theory, charge=None, spin_multiplicity=None,
                      basis_set="6-31g", basis_set_option="cartesian",
                      title=None, operation="optimize", theory_directives=None,
                      alternate_directives=None):
        """
        Very flexible arguments to support many types of potential setups.
        Users should use more friendly static methods unless they need the
        flexibility.

        Args:
            mol: Input molecule
            charge: Charge of the molecule. If None, charge on molecule is
                used. Defaults to None. This allows the input file to be set a
                charge independently from the molecule itself.
            spin_multiplicity: Spin multiplicity of molecule. Defaults to None,
                which means that the spin multiplicity is set to 1 if the
                molecule has no unpaired electrons and to 2 if there are
                unpaired electrons.
            basis_set: The basis set to be used as string or a dict. E.g.,
                {"C": "6-311++G**", "H": "6-31++G**"} or "6-31G". If string,
                same basis set is used for all elements.
            basis_set_option: cartesian (default) | spherical,
            title: Title for the task. Defaults to None, which means a title
                based on the theory and operation of the task is
                autogenerated.
            theory: The theory used for the task. Defaults to "dft".
            operation: The operation for the task. Defaults to "optimize".
            theory_directives: A dict of theory directives. For example,
                if you are running dft calculations, you may specify the
                exchange correlation functional using {"xc": "b3lyp"}.
            alternate_directives: A dict of alternate directives. For
                example, to perform cosmo calculations with DFT, you'd supply
                {'cosmo': "cosmo"}.
        """
        title = title if title is not None else "{} {} {}".format(
            re.sub(r"\s", "", mol.formula), theory, operation)

        charge = charge if charge is not None else mol.charge
        nelectrons = - charge + mol.charge + mol.nelectrons
        if spin_multiplicity is not None:
            spin_multiplicity = spin_multiplicity
            if (nelectrons + spin_multiplicity) % 2 != 1:
                raise ValueError(
                    "Charge of {} and spin multiplicity of {} is"
                    " not possible for this molecule".format(
                        charge, spin_multiplicity))
        elif charge == mol.charge:
            spin_multiplicity = mol.spin_multiplicity
        else:
            spin_multiplicity = 1 if nelectrons % 2 == 0 else 2

        elements = set(mol.composition.get_el_amt_dict().keys())
        if isinstance(basis_set, str):
            basis_set = {el: basis_set for el in elements}

        basis_set_option = basis_set_option

        return NwTask(charge, spin_multiplicity, basis_set,
                      basis_set_option=basis_set_option,
                      title=title, theory=theory, operation=operation,
                      theory_directives=theory_directives,
                      alternate_directives=alternate_directives)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dft_task(cls, mol, xc="b3lyp", **kwargs):
        t = NwTask.from_molecule(mol, theory="dft", **kwargs)
        t.theory_directives.update({"xc": xc,
                                    "mult": t.spin_multiplicity})
        return t

Response: A class method for quickly creating DFT tasks with optional kwargs.


Instruction:
Can you write a function in Python 3 where it
reads an NwInput from a string. Currently tested to work with NwInput files generated from this class itself.

Response:
def from_string(cls, string_input):
        """
        Read an NwInput from a string. Currently tested to work with
        files generated from this class itself.

        Args:
            string_input: string_input to parse.

        Returns:
            NwInput object
        """
        directives = []
        tasks = []
        charge = None
        spin_multiplicity = None
        title = None
        basis_set = None
        basis_set_option = None
        theory_directives = {}
        geom_options = None
        symmetry_options = None
        memory_options = None
        lines = string_input.strip().split("\n")
        while len(lines) > 0:
            l = lines.pop(0).strip()
            if l == "":
                continue

            toks = l.split()
            if toks[0].lower() == "geometry":
                geom_options = toks[1:]
                l = lines.pop(0).strip()
                toks = l.split()
                if toks[0].lower() == "symmetry":
                    symmetry_options = toks[1:]
                    l = lines.pop(0).strip()
                # Parse geometry
                species = []
                coords = []
                while l.lower() != "end":
                    toks = l.split()
                    species.append(toks[0])
                    coords.append([float(i) for i in toks[1:]])
                    l = lines.pop(0).strip()
                mol = Molecule(species, coords)
            elif toks[0].lower() == "charge":
                charge = int(toks[1])
            elif toks[0].lower() == "title":
                title = l[5:].strip().strip("\"")
            elif toks[0].lower() == "basis":
                # Parse basis sets
                l = lines.pop(0).strip()
                basis_set = {}
                while l.lower() != "end":
                    toks = l.split()
                    basis_set[toks[0]] = toks[-1].strip("\"")
                    l = lines.pop(0).strip()
            elif toks[0].lower() in NwTask.theories:
                # read the basis_set_option
                if len(toks) > 1:
                    basis_set_option = toks[1]
                # Parse theory directives.
                theory = toks[0].lower()
                l = lines.pop(0).strip()
                theory_directives[theory] = {}
                while l.lower() != "end":
                    toks = l.split()
                    theory_directives[theory][toks[0]] = toks[-1]
                    if toks[0] == "mult":
                        spin_multiplicity = float(toks[1])
                    l = lines.pop(0).strip()
            elif toks[0].lower() == "task":
                tasks.append(
                    NwTask(charge=charge,
                           spin_multiplicity=spin_multiplicity,
                           title=title, theory=toks[1],
                           operation=toks[2], basis_set=basis_set,
                           basis_set_option=basis_set_option,
                           theory_directives=theory_directives.get(toks[1])))
            elif toks[0].lower() == "memory":
                    memory_options = ' '.join(toks[1:])
            else:
                directives.append(l.strip().split())

        return NwInput(mol, tasks=tasks, directives=directives,
                       geometry_options=geom_options,
                       symmetry_options=symmetry_options,
                       memory_options=memory_options)


Instruction:
Implement a function in Python 3 to
parse TDDFT roots. Adapted from nw_spectrum. py script.

Response:
def parse_tddft(self):
        """
        Parses TDDFT roots. Adapted from nw_spectrum.py script.

        Returns:
            {
                "singlet": [
                    {
                        "energy": float,
                        "osc_strength: float
                    }
                ],
                "triplet": [
                    {
                        "energy": float
                    }
                ]
            }
        """
        start_tag = "Convergence criterion met"
        end_tag = "Excited state energy"
        singlet_tag = "singlet excited"
        triplet_tag = "triplet excited"
        state = "singlet"
        inside = False  # true when we are inside output block

        lines = self.raw.split("\n")

        roots = {"singlet": [], "triplet": []}

        while lines:
            line = lines.pop(0).strip()

            if start_tag in line:
                inside = True

            elif end_tag in line:
                inside = False

            elif singlet_tag in line:
                state = "singlet"

            elif triplet_tag in line:
                state = "triplet"

            elif inside and "Root" in line and "eV" in line:
                toks = line.split()
                roots[state].append({"energy": float(toks[-2])})

            elif inside and "Dipole Oscillator Strength" in line:
                osc = float(line.split()[-1])
                roots[state][-1]["osc_strength"] = osc

        return roots


Instruction:
Write a Python 3 function that can
generate an excitation spectra from the singlet roots of TDDFT and returns it.

Response:
def get_excitation_spectrum(self, width=0.1, npoints=2000):
        """
        Generate an excitation spectra from the singlet roots of TDDFT
        calculations.

        Args:
            width (float): Width for Gaussian smearing.
            npoints (int): Number of energy points. More points => smoother
                curve.

        Returns:
            (ExcitationSpectrum) which can be plotted using
                pymatgen.vis.plotters.SpectrumPlotter.
        """
        roots = self.parse_tddft()
        data = roots["singlet"]
        en = np.array([d["energy"] for d in data])
        osc = np.array([d["osc_strength"] for d in data])

        epad = 20.0 * width
        emin = en[0] - epad
        emax = en[-1] + epad
        de = (emax - emin) / npoints

        # Use width of at least two grid points
        if width < 2 * de:
            width = 2 * de

        energies = [emin + ie * de for ie in range(npoints)]

        cutoff = 20.0 * width
        gamma = 0.5 * width
        gamma_sqrd = gamma * gamma

        de = (energies[-1] - energies[0]) / (len(energies) - 1)
        prefac = gamma / np.pi * de

        x = []
        y = []
        for energy in energies:
            xx0 = energy - en
            stot = osc / (xx0 * xx0 + gamma_sqrd)
            t = np.sum(stot[np.abs(xx0) <= cutoff])
            x.append(energy)
            y.append(t * prefac)
        return ExcitationSpectrum(x, y)


Instruction:
Implement a function in Python 3 to
return a formula string with elements sorted by electronegativity and elements sorted by electronegativity.

Response:
def formula(self):
        """
        Returns a formula string, with elements sorted by electronegativity,
        e.g., Li4 Fe4 P4 O16.
        """
        formula = super().formula
        chg_str = ""
        if self.charge > 0:
            chg_str = " +" + formula_double_format(self.charge, False)
        elif self._charge < 0:
            chg_str = " " + formula_double_format(self.charge, False)
        return formula + chg_str


Instruction:
Write a Python 3 script for
returning a reduced formula string with appended charge.

Response:
def reduced_formula(self):
        """
        Returns a reduced formula string with appended charge.
        """
        reduced_formula = super().reduced_formula
        charge = self._charge / self.get_reduced_composition_and_factor()[1]
        if charge > 0:
            if abs(charge) == 1:
                chg_str = "[+]"
            else:
                chg_str = "[" + formula_double_format(charge, False) + "+]"
        elif charge < 0:
            if abs(charge) == 1:
                chg_str = "[-]"
            else:
                chg_str = "[{}-]".format(formula_double_format(abs(charge),
                                                               False))
        else:
            chg_str = "(aq)"
        return reduced_formula + chg_str


Instruction:
Given the following Python 3 function, write the documentation
def alphabetical_formula(self):
        alph_formula = super().alphabetical_formula
        chg_str = ""
        if self.charge > 0:
            chg_str = " +" + formula_double_format(self.charge, False)
        elif self.charge < 0:
            chg_str = " " + formula_double_format(self.charge, False)
        return alph_formula + chg_str

Response: Returns a reduced formula string with appended charge


Instruction:
How would you implement a function in Python 3 that
generates an ion object from a dict created by as_dict.

Response:
def from_dict(cls, d):
        """
        Generates an ion object from a dict created by as_dict().

        Args:
            d:
                {symbol: amount} dict.
        """
        charge = d.pop('charge')
        composition = Composition(d)
        return Ion(composition, charge)


Instruction:
Write a Python 3 script to
return a reduced dictionary with element symbol and reduced amount e. g..

Response:
def to_reduced_dict(self):
        """
        Returns:
            dict with element symbol and reduced amount e.g.,
            {"Fe": 2.0, "O":3.0}.
        """
        d = self.composition.to_reduced_dict
        d['charge'] = self.charge
        return d


Instruction:
Implement a function in Python 3 to
return the cost of the best assignment of the current object.

Response:
def min_cost(self):
        """
        Returns the cost of the best assignment
        """
        if self._min_cost:
            return self._min_cost
        self._min_cost = np.sum(self.c[np.arange(self.nx), self.solution])
        return self._min_cost


Instruction:
Explain what the following Python 3 code does
def _column_reduction(self):
        #assign each column to its lowest cost row, ensuring that only row
        #or column is assigned once
        i1, j = np.unique(np.argmin(self.c, axis=0), return_index=True)
        self._x[i1] = j

        #if problem is solved, return
        if len(i1) == self.n:
            return False

        self._y[j] = i1

        #reduction_transfer
        #tempc is array with previously assigned matchings masked
        self._v = np.min(self.c, axis=0)
        tempc = self.c.copy()
        tempc[i1, j] = np.inf
        mu = np.min(tempc[i1, :] - self._v[None, :], axis=1)
        self._v[j] -= mu
        return True

Response: Column reduction and reduction transfer steps from LAPJV algorithm