Instruction:
Write a Python 3 function that can
plot the Phonon SCF cycle results with matplotlib.

Response:
def inspect(self, **kwargs):
        """
        Plot the Phonon SCF cycle results with matplotlib.

        Returns:
            `matplotlib` figure, None if some error occurred.
        """
        scf_cycle = abiinspect.PhononScfCycle.from_file(self.output_file.path)
        if scf_cycle is not None:
            if "title" not in kwargs: kwargs["title"] = str(self)
            return scf_cycle.plot(**kwargs)


Instruction:
Can you generate the documentation for the following Python 3 function
def reduce_memory_demand(self):
        # The first digit governs the storage of W(q), the second digit the storage of u(r)
        # Try to avoid the storage of u(r) first since reading W(q) from file will lead to a drammatic slowdown.
        prev_gwmem = int(self.get_inpvar("gwmem", default=11))
        first_dig, second_dig = prev_gwmem // 10, prev_gwmem % 10

        if second_dig == 1:
            self.set_vars(gwmem="%.2d" % (10 * first_dig))
            return True

        if first_dig == 1:
            self.set_vars(gwmem="%.2d" % 00)
            return True

        # gwmem 00 d'oh!
        return False

Response: This method is used to reduce the memory demand of a specific task.


Instruction:
Can you write a function in Python 3 where it
opens the SIGRES file located in the in self. outdir. Returns None if file could not be opened.

Response:
def open_scr(self):
        """
        Open the SIGRES file located in the in self.outdir.
        Returns :class:`ScrFile` object, None if file could not be found or file is not readable.
        """
        scr_path = self.scr_path

        if not scr_path:
            logger.critical("%s didn't produce a SCR.nc file in %s" % (self, self.outdir))
            return None

        # Open the GSR file and add its data to results.out
        from abipy.electrons.scr import ScrFile
        try:
            return ScrFile(scr_path)
        except Exception as exc:
            logger.critical("Exception while reading SCR file at %s:\n%s" % (scr_path, str(exc)))
            return None


Instruction:
Here you have a function in Python 3, explain what it does
def open_sigres(self):
        sigres_path = self.sigres_path

        if not sigres_path:
            logger.critical("%s didn't produce a SIGRES file in %s" % (self, self.outdir))
            return None

        # Open the SIGRES file and add its data to results.out
        from abipy.electrons.gw import SigresFile
        try:
            return SigresFile(sigres_path)
        except Exception as exc:
            logger.critical("Exception while reading SIGRES file at %s:\n%s" % (sigres_path, str(exc)))
            return None

Response: Open the SIGRES file located in the in self. outdir. Returns None if file could not be opened.


Instruction:
Write a Python 3 function that can
return an instance of : class : ScissorsBuilder from the SIGRES file.

Response:
def get_scissors_builder(self):
        """
        Returns an instance of :class:`ScissorsBuilder` from the SIGRES file.

        Raise:
            `RuntimeError` if SIGRES file is not found.
        """
        from abipy.electrons.scissors import ScissorsBuilder
        if self.sigres_path:
            return ScissorsBuilder.from_file(self.sigres_path)
        else:
            raise RuntimeError("Cannot find SIGRES file!")


Instruction:
Write a Python 3 function for
restarting the current set of critical events for the current log file.

Response:
def restart(self):
        """
        BSE calculations with Haydock can be restarted only if we have the
        excitonic Hamiltonian and the HAYDR_SAVE file.
        """
        # TODO: This version seems to work but the main output file is truncated
        # TODO: Handle restart if CG method is used
        # TODO: restart should receive a list of critical events
        # the log file is complete though.
        irdvars = {}

        # Move the BSE blocks to indata.
        # This is done only once at the end of the first run.
        # Successive restarts will use the BSR|BSC files in the indir directory
        # to initialize the excitonic Hamiltonian
        count = 0
        for ext in ("BSR", "BSC"):
            ofile = self.outdir.has_abiext(ext)
            if ofile:
                count += 1
                irdvars.update(irdvars_for_ext(ext))
                self.out_to_in(ofile)

        if not count:
            # outdir does not contain the BSR|BSC file.
            # This means that num_restart > 1 and the files should be in task.indir
            count = 0
            for ext in ("BSR", "BSC"):
                ifile = self.indir.has_abiext(ext)
                if ifile:
                    count += 1

            if not count:
                raise self.RestartError("%s: Cannot find BSR|BSC files in %s" % (self, self.indir))

        # Rename HAYDR_SAVE files
        count = 0
        for ext in ("HAYDR_SAVE", "HAYDC_SAVE"):
            ofile = self.outdir.has_abiext(ext)
            if ofile:
                count += 1
                irdvars.update(irdvars_for_ext(ext))
                self.out_to_in(ofile)

        if not count:
            raise self.RestartError("%s: Cannot find the HAYDR_SAVE file to restart from." % self)

        # Add the appropriate variable for restarting.
        self.set_vars(irdvars)

        # Now we can resubmit the job.
        #self.history.info("Will restart from %s", restart_file)
        return self._restart()


Instruction:
Make a summary of the following Python 3 code
def mdf_path(self):
        # Lazy property to avoid multiple calls to has_abiext.
        try:
            return self._mdf_path
        except AttributeError:
            path = self.outdir.has_abiext("MDF.nc")
            if path: self._mdf_path = path
            return path

Response: Absolute path of the MDF file. Empty string if file is not present.


Instruction:
Given the following Python 3 function, write the documentation
def open_mdf(self):
        mdf_path = self.mdf_path
        if not mdf_path:
            logger.critical("%s didn't produce a MDF file in %s" % (self, self.outdir))
            return None

        # Open the DFF file and add its data to results.out
        from abipy.electrons.bse import MdfFile
        try:
            return MdfFile(mdf_path)
        except Exception as exc:
            logger.critical("Exception while reading MDF file at %s:\n%s" % (mdf_path, str(exc)))
            return None

Response: Open the MDF file located in the in self. outdir. Returns None if file could not be opened.


Instruction:
Given the following Python 3 function, write the documentation
def set_workdir(self, workdir, chroot=False):
        super().set_workdir(workdir, chroot=chroot)
        # Small hack: the log file of optics is actually the main output file.
        self.output_file = self.log_file

Response: Set the working directory of the task.


Instruction:
Can you create a Python 3 function that
sets variables for the current task.

Response:
def set_vars(self, *args, **kwargs):
        """
        Optic does not use `get` or `ird` variables hence we should never try
        to change the input when we connect this task
        """
        kwargs.update(dict(*args))
        self.history.info("OpticTask intercepted set_vars with args %s" % kwargs)

        if "autoparal" in kwargs: self.input.set_vars(autoparal=kwargs["autoparal"])
        if "max_ncpus" in kwargs: self.input.set_vars(max_ncpus=kwargs["max_ncpus"])


Instruction:
How would you code a function in Python 3 to
string with the list of files and prefixes needed to execute ABINIT.

Response:
def filesfile_string(self):
        """String with the list of files and prefixes needed to execute ABINIT."""
        lines = []
        app = lines.append

        #optic.in     ! Name of input file
        #optic.out    ! Unused
        #optic        ! Root name for all files that will be produced
        app(self.input_file.path)                           # Path to the input file
        app(os.path.join(self.workdir, "unused"))           # Path to the output file
        app(os.path.join(self.workdir, self.prefix.odata))  # Prefix for output data

        return "\n".join(lines)


Instruction:
Given the following Python 3 function, write the documentation
def ddk_filepaths(self):
        # This to support new version of optic that used DDK.nc
        paths = [ddk_task.outdir.has_abiext("DDK.nc") for ddk_task in self.ddk_nodes]
        if all(p for p in paths):
            return paths

        # This is deprecated and can be removed when new version of Abinit is released.
        return [ddk_task.outdir.has_abiext("1WF") for ddk_task in self.ddk_nodes]

Response: Returns ( at runtime ) the absolute path of the DDK files produced by the DDK runs.


Instruction:
How would you implement a function in Python 3 that
constructs and write the input file of the calculation.

Response:
def make_input(self):
        """Construct and write the input file of the calculation."""
        # Set the file paths.
        all_files ={"ddkfile_" + str(n + 1): ddk for n, ddk in enumerate(self.ddk_filepaths)}
        all_files.update({"wfkfile": self.wfk_filepath})
        files_nml = {"FILES": all_files}
        files= nmltostring(files_nml)

        # Get the input specified by the user
        user_file = nmltostring(self.input.as_dict())

        # Join them.
        return files + user_file


Instruction:
Write a Python 3 function for
restarting the job from scratch.

Response:
def reset_from_scratch(self):
        """
        restart from scratch, this is to be used if a job is restarted with more resources after a crash
        """
        # Move output files produced in workdir to _reset otherwise check_status continues
        # to see the task as crashed even if the job did not run
        # Create reset directory if not already done.
        reset_dir = os.path.join(self.workdir, "_reset")
        reset_file = os.path.join(reset_dir, "_counter")
        if not os.path.exists(reset_dir):
            os.mkdir(reset_dir)
            num_reset = 1
        else:
            with open(reset_file, "rt") as fh:
                num_reset = 1 + int(fh.read())

        # Move files to reset and append digit with reset index.
        def move_file(f):
            if not f.exists: return
            try:
                f.move(os.path.join(reset_dir, f.basename + "_" + str(num_reset)))
            except OSError as exc:
                logger.warning("Couldn't move file {}. exc: {}".format(f, str(exc)))

        for fname in ("output_file", "log_file", "stderr_file", "qout_file", "qerr_file", "mpiabort_file"):
            move_file(getattr(self, fname))

        with open(reset_file, "wt") as fh:
            fh.write(str(num_reset))

        self.start_lockfile.remove()

        # Reset datetimes
        self.datetimes.reset()

        return self._restart(submit=False)


Instruction:
Can you generate the documentation for the following Python 3 function
def temp_shell_task(cls, inp, ddb_node, mpi_procs=1,
                        gkk_node=None, md_node=None, ddk_node=None, workdir=None, manager=None):
        """
        Build a :class:`AnaddbTask` with a temporary workdir. The task is executed via
        the shell with 1 MPI proc. Mainly used for post-processing the DDB files.

        Args:
            mpi_procs: Number of MPI processes to use.
            anaddb_input: string with the anaddb variables.
            ddb_node: The node that will produce the DDB file. Accept :class:`Task`, :class:`Work` or filepath.

        See `AnaddbInit` for the meaning of the other arguments.
        """
        # Build a simple manager to run the job in a shell subprocess
        import tempfile
        workdir = tempfile.mkdtemp() if workdir is None else workdir
        if manager is None: manager = TaskManager.from_user_config()

        # Construct the task and run it
        return cls(inp, ddb_node,
                   gkk_node=gkk_node, md_node=md_node, ddk_node=ddk_node,
                   workdir=workdir, manager=manager.to_shell_manager(mpi_procs=mpi_procs))

Response: Build a Task object with a temporary workdir.


Instruction:
Can you generate the documentation for the following Python 3 function
def filesfile_string(self):
        lines = []
        app = lines.append

        app(self.input_file.path)          # 1) Path of the input file
        app(self.output_file.path)         # 2) Path of the output file
        app(self.ddb_filepath)             # 3) Input derivative database e.g. t13.ddb.in
        app(self.md_filepath)              # 4) Output molecular dynamics e.g. t13.md
        app(self.gkk_filepath)             # 5) Input elphon matrix elements  (GKK file)
        app(self.outdir.path_join("out"))  # 6) Base name for elphon output files e.g. t13
        app(self.ddk_filepath)             # 7) File containing ddk filenames for elphon/transport.

        return "\n".join(lines)

Response: Returns a string with the list of files and prefixes needed to execute ABINIT.


Instruction:
How would you code a function in Python 3 to
return ( at runtime ) the absolute path of the input DDB file.

Response:
def ddb_filepath(self):
        """Returns (at runtime) the absolute path of the input DDB file."""
        # This is not very elegant! A possible approach could to be path self.ddb_node.outdir!
        if isinstance(self.ddb_node, FileNode): return self.ddb_node.filepath
        path = self.ddb_node.outdir.has_abiext("DDB")
        return path if path else "DDB_FILE_DOES_NOT_EXIST"


Instruction:
Can you generate the documentation for the following Python 3 function
def md_filepath(self):
        if self.md_node is None: return "MD_FILE_DOES_NOT_EXIST"
        if isinstance(self.md_node, FileNode): return self.md_node.filepath

        path = self.md_node.outdir.has_abiext("MD")
        return path if path else "MD_FILE_DOES_NOT_EXIST"

Response: Returns ( at runtime ) the absolute path of the input MD file.


Instruction:
Write a Python 3 function that can
return ( at runtime ) the absolute path of the input GKK file.

Response:
def gkk_filepath(self):
        """Returns (at runtime) the absolute path of the input GKK file."""
        if self.gkk_node is None: return "GKK_FILE_DOES_NOT_EXIST"
        if isinstance(self.gkk_node, FileNode): return self.gkk_node.filepath

        path = self.gkk_node.outdir.has_abiext("GKK")
        return path if path else "GKK_FILE_DOES_NOT_EXIST"


Instruction:
Given the following Python 3 function, write the documentation
def ddk_filepath(self):
        if self.ddk_node is None: return "DDK_FILE_DOES_NOT_EXIST"
        if isinstance(self.ddk_node, FileNode): return self.ddk_node.filepath

        path = self.ddk_node.outdir.has_abiext("DDK")
        return path if path else "DDK_FILE_DOES_NOT_EXIST"

Response: Returns ( at runtime ) the absolute path of the input DKK file.


Instruction:
Write a Python 3 script for
opening a PHBST file produced by Anaddb and returns a PhbstFile object.

Response:
def open_phbst(self):
        """Open PHBST file produced by Anaddb and returns :class:`PhbstFile` object."""
        from abipy.dfpt.phonons import PhbstFile
        phbst_path = os.path.join(self.workdir, "run.abo_PHBST.nc")
        if not phbst_path:
            if self.status == self.S_OK:
                logger.critical("%s reached S_OK but didn't produce a PHBST file in %s" % (self, self.outdir))
            return None

        try:
            return PhbstFile(phbst_path)
        except Exception as exc:
            logger.critical("Exception while reading GSR file at %s:\n%s" % (phbst_path, str(exc)))
            return None


Instruction:
Given the following Python 3 function, write the documentation
def open_phdos(self):
        from abipy.dfpt.phonons import PhdosFile
        phdos_path = os.path.join(self.workdir, "run.abo_PHDOS.nc")
        if not phdos_path:
            if self.status == self.S_OK:
                logger.critical("%s reached S_OK but didn't produce a PHBST file in %s" % (self, self.outdir))
            return None

        try:
            return PhdosFile(phdos_path)
        except Exception as exc:
            logger.critical("Exception while reading GSR file at %s:\n%s" % (phdos_path, str(exc)))
            return None

Response: Open the PHDOS file produced by Anaddb and returns a PhdosFile object.


Instruction:
Can you generate the documentation for the following Python 3 function
def structure_from_ncdata(ncdata, site_properties=None, cls=Structure):
    ncdata, closeit = as_ncreader(ncdata)

    # TODO check whether atomic units are used
    lattice = ArrayWithUnit(ncdata.read_value("primitive_vectors"), "bohr").to("ang")

    red_coords = ncdata.read_value("reduced_atom_positions")
    natom = len(red_coords)

    znucl_type = ncdata.read_value("atomic_numbers")

    # type_atom[0:natom] --> index Between 1 and number of atom species
    type_atom = ncdata.read_value("atom_species")

    # Fortran to C index and float --> int conversion.
    species = natom * [None]
    for atom in range(natom):
        type_idx = type_atom[atom] - 1
        species[atom] = int(znucl_type[type_idx])

    d = {}
    if site_properties is not None:
        for prop in site_properties:
            d[property] = ncdata.read_value(prop)

    structure = cls(lattice, species, red_coords, site_properties=d)

    # Quick and dirty hack.
    # I need an abipy structure since I need to_abivars and other methods.
    try:
        from abipy.core.structure import Structure as AbipyStructure
        structure.__class__ = AbipyStructure
    except ImportError:
        pass

    if closeit:
        ncdata.close()

    return structure

Response: Reads and returns a pymatgen structure from a NetCDF file containing crystallographic data in the ETSF - IO format.


Instruction:
Can you create a Python 3 function that
walks the tree of all the user - defined groups and their children.

Response:
def walk_tree(self, top=None):
        """
        Navigate all the groups in the file starting from top.
        If top is None, the root group is used.
        """
        if top is None:
            top = self.rootgrp

        values = top.groups.values()
        yield values
        for value in top.groups.values():
            for children in self.walk_tree(value):
                yield children


Instruction:
Explain what the following Python 3 code does
def read_dimvalue(self, dimname, path="/", default=NO_DEFAULT):
        try:
            dim = self._read_dimensions(dimname, path=path)[0]
            return len(dim)
        except self.Error:
            if default is NO_DEFAULT: raise
            return default

Response: Reads the value of a dimension.


Instruction:
Here you have a function in Python 3, explain what it does
def read_varnames(self, path="/"):
        if path == "/":
            return self.rootgrp.variables.keys()
        else:
            group = self.path2group[path]
            return group.variables.keys()

Response: List of variable names stored in the group specified by path.


Instruction:
How would you code a function in Python 3 to
read the value of a variable in the group specified by path.

Response:
def read_value(self, varname, path="/", cmode=None, default=NO_DEFAULT):
        """
        Returns the values of variable with name varname in the group specified by path.

        Args:
            varname: Name of the variable
            path: path to the group.
            cmode: if cmode=="c", a complex ndarrays is constructed and returned
                (netcdf does not provide native support from complex datatype).
            default: returns default if varname is not present.
                self.Error is raised if default is default is NO_DEFAULT

        Returns:
            numpy array if varname represents an array, scalar otherwise.
        """
        try:
            var = self.read_variable(varname, path=path)
        except self.Error:
            if default is NO_DEFAULT: raise
            return default

        if cmode is None:
            # scalar or array
            # getValue is not portable!
            try:
                return var.getValue()[0] if not var.shape else var[:]
            except IndexError:
                return var.getValue() if not var.shape else var[:]

        else:
            assert var.shape[-1] == 2
            if cmode == "c":
                return var[...,0] + 1j*var[...,1]
            else:
                raise ValueError("Wrong value for cmode %s" % cmode)


Instruction:
Can you tell what is the following Python 3 function doing
def read_keys(self, keys, dict_cls=AttrDict, path="/"):
        od = dict_cls()
        for k in keys:
            try:
                # Try to read a variable.
                od[k] = self.read_value(k, path=path)
            except self.Error:
                try:
                    # Try to read a dimension.
                    od[k] = self.read_dimvalue(k, path=path)
                except self.Error:
                    od[k] = None

        return od

Response: Read a list of variables and dimensions from file.


Instruction:
Can you generate the documentation for the following Python 3 function
def chemical_symbols(self):
        charr = self.read_value("chemical_symbols")
        symbols = []
        for v in charr:
            s = "".join(c.decode("utf-8") for c in v)
            symbols.append(s.strip())

        return symbols

Response: Chemical symbols char [ number of atom species][symbol length ].


Instruction:
Create a Python 3 function to
return the crystalline structure.

Response:
def read_structure(self, cls=Structure):
        """Returns the crystalline structure."""
        if self.ngroups != 1:
            raise NotImplementedError("In file %s: ngroups != 1" % self.path)

        return structure_from_ncdata(self, cls=cls)


Instruction:
Explain what the following Python 3 code does
def read_abinit_hdr(self):
        d = {}
        for hvar in _HDR_VARIABLES.values():
            ncname = hvar.etsf_name if hvar.etsf_name is not None else hvar.name
            if ncname in self.rootgrp.variables:
                d[hvar.name] = self.read_value(ncname)
            elif ncname in self.rootgrp.dimensions:
                d[hvar.name] = self.read_dimvalue(ncname)
            else:
                raise ValueError("Cannot find `%s` in `%s`" % (ncname, self.path))
            # Convert scalars to (well) scalars.
            if hasattr(d[hvar.name], "shape") and not d[hvar.name].shape:
                d[hvar.name] = np.asscalar(d[hvar.name])
            if hvar.name in ("title", "md5_pseudos", "codvsn"):
                # Convert array of numpy bytes to list of strings
                if hvar.name == "codvsn":
                    d[hvar.name] = "".join(bs.decode("utf-8").strip() for bs in d[hvar.name])
                else:
                    d[hvar.name] = ["".join(bs.decode("utf-8") for bs in astr).strip()
                            for astr in d[hvar.name]]

        return AbinitHeader(d)

Response: Reads the variables associated to the Abinit header.


Instruction:
Create a Python 3 function to
return a string representation of the current object.

Response:
def to_string(self, verbose=0, title=None, **kwargs):
        """
        String representation. kwargs are passed to `pprint.pformat`.

        Args:
            verbose: Verbosity level
            title: Title string.
        """
        from pprint import pformat
        s = pformat(self, **kwargs)
        if title is not None:
            return "\n".join([marquee(title, mark="="), s])
        return s


Instruction:
Write a Python 3 function that can
add an electrode to the plot.

Response:
def add_electrode(self, electrode, label=None):
        """
        Add an electrode to the plot.

        Args:
            electrode: An electrode. All electrodes satisfying the
                AbstractElectrode interface should work.
            label: A label for the electrode. If None, defaults to a counting
                system, i.e. 'Electrode 1', 'Electrode 2', ...
        """
        if not label:
            label = "Electrode {}".format(len(self._electrodes) + 1)
        self._electrodes[label] = electrode


Instruction:
Write a Python 3 script to
return a matplotlib plot object.

Response:
def get_plot(self, width=8, height=8):
        """
        Returns a plot object.

        Args:
            width: Width of the plot. Defaults to 8 in.
            height: Height of the plot. Defaults to 6 in.

        Returns:
            A matplotlib plot object.
        """
        plt = pretty_plot(width, height)
        for label, electrode in self._electrodes.items():
            (x, y) = self.get_plot_data(electrode)
            plt.plot(x, y, '-', linewidth=2, label=label)

        plt.legend()
        if self.xaxis == "capacity":
            plt.xlabel('Capacity (mAh/g)')
        else:
            plt.xlabel('Fraction')
        plt.ylabel('Voltage (V)')
        plt.tight_layout()
        return plt


Instruction:
Here you have a function in Python 3, explain what it does
def save(self, filename, image_format="eps", width=8, height=6):
        self.get_plot(width, height).savefig(filename, format=image_format)

Response: Save the plot to an image file.


Instruction:
Can you write a function in Python 3 where it
returns the final structure from the previous run.

Response:
def get_structure_from_prev_run(vasprun, outcar=None, sym_prec=0.1,
                                international_monoclinic=True):
    """
    Process structure from previous run.

    Args:
        vasprun (Vasprun): Vasprun that contains the final structure
            from previous run.
        outcar (Outcar): Outcar that contains the magnetization info from
            previous run.
        sym_prec (float): Tolerance for symmetry finding for standardization. If
            no standardization is desired, set to 0 or a False.
        international_monoclinic (bool): Whether to use international
            convention (vs Curtarolo) for monoclinic. Defaults True.

    Returns:
        Returns the magmom-decorated structure that can be passed to get
        Vasp input files, e.g. get_kpoints.
    """
    structure = vasprun.final_structure

    site_properties = {}
    # magmom
    if vasprun.is_spin:
        if outcar and outcar.magnetization:
            site_properties.update({"magmom": [i['tot']
                                               for i in outcar.magnetization]})
        else:
            site_properties.update({"magmom": vasprun.parameters['MAGMOM']})
    # ldau
    if vasprun.parameters.get("LDAU", False):
        for k in ("LDAUU", "LDAUJ", "LDAUL"):
            vals = vasprun.incar[k]
            m = {}
            l = []
            s = 0
            for site in structure:
                if site.specie.symbol not in m:
                    m[site.specie.symbol] = vals[s]
                    s += 1
                l.append(m[site.specie.symbol])
            if len(l) == len(structure):
                site_properties.update({k.lower(): l})
            else:
                raise ValueError("length of list {} not the same as"
                                 "structure".format(l))

    structure = structure.copy(site_properties=site_properties)

    if sym_prec:
        sym_finder = SpacegroupAnalyzer(structure, symprec=sym_prec)
        new_structure = sym_finder.get_primitive_standard_structure(
            international_monoclinic=international_monoclinic)
        # the primitive structure finding has had several bugs in the past
        # defend through validation
        vpa_old = structure.volume / structure.num_sites
        vpa_new = new_structure.volume / new_structure.num_sites
        if abs(vpa_old - vpa_new) / vpa_old > 0.02:
            raise ValueError(
                "Standardizing cell failed! VPA old: {}, VPA new: {}".format(
                    vpa_old, vpa_new))
        sm = StructureMatcher()
        if not sm.fit(structure, new_structure):
            raise ValueError(
                "Standardizing cell failed! Old structure doesn't match new.")
        structure = new_structure

    return structure


Instruction:
Write a Python 3 script to
write a batch of VASP input files for a sequence of structures to a directory.

Response:
def batch_write_input(structures, vasp_input_set=MPRelaxSet, output_dir=".",
                      make_dir_if_not_present=True, subfolder=None,
                      sanitize=False, include_cif=False, **kwargs):
    """
    Batch write vasp input for a sequence of structures to
    output_dir, following the format output_dir/{group}/{formula}_{number}.

    Args:
        structures ([Structure]): Sequence of Structures.
        vasp_input_set (VaspInputSet): VaspInputSet class that creates
            vasp input files from structures. Note that a class should be
            supplied. Defaults to MPRelaxSet.
        output_dir (str): Directory to output files. Defaults to current
            directory ".".
        make_dir_if_not_present (bool): Create the directory if not present.
            Defaults to True.
        subfolder (callable): Function to create subdirectory name from
            structure. Defaults to simply "formula_count".
        sanitize (bool): Boolean indicating whether to sanitize the
            structure before writing the VASP input files. Sanitized output
            are generally easier for viewing and certain forms of analysis.
            Defaults to False.
        include_cif (bool): Whether to output a CIF as well. CIF files are
            generally better supported in visualization programs.
        \\*\\*kwargs: Additional kwargs are passed to the vasp_input_set class
            in addition to structure.
    """
    output_dir = Path(output_dir)
    for i, s in enumerate(structures):
        formula = re.sub(r'\s+', "", s.formula)
        if subfolder is not None:
            subdir = subfolder(s)
            d = output_dir / subdir
        else:
            d = output_dir / '{}_{}'.format(formula, i)
        if sanitize:
            s = s.copy(sanitize=True)
        v = vasp_input_set(s, **kwargs)
        v.write_input(str(d), make_dir_if_not_present=make_dir_if_not_present,
                      include_cif=include_cif)


Instruction:
How would you implement a function in Python 3 that
returns a list of POTCAR symbols.

Response:
def potcar_symbols(self):
        """
        List of POTCAR symbols.
        """
        elements = self.poscar.site_symbols
        potcar_symbols = []
        settings = self._config_dict["POTCAR"]

        if isinstance(settings[elements[-1]], dict):
            for el in elements:
                potcar_symbols.append(settings[el]['symbol']
                                      if el in settings else el)
        else:
            for el in elements:
                potcar_symbols.append(settings.get(el, el))

        return potcar_symbols


Instruction:
Here you have a function in Python 3, explain what it does
def all_input(self):
        return {'INCAR': self.incar,
                'KPOINTS': self.kpoints,
                'POSCAR': self.poscar,
                'POTCAR': self.potcar}

Response: Returns all input files as a dict of object names.


Instruction:
Can you implement a function in Python 3 that
writes a set of VASP input files to a directory.

Response:
def write_input(self, output_dir,
                    make_dir_if_not_present=True, include_cif=False):
        """
        Writes a set of VASP input to a directory.

        Args:
            output_dir (str): Directory to output the VASP input files
            make_dir_if_not_present (bool): Set to True if you want the
                directory (and the whole path) to be created if it is not
                present.
            include_cif (bool): Whether to write a CIF file in the output
                directory for easier opening by VESTA.
        """
        vinput = self.get_vasp_input()
        vinput.write_input(
            output_dir, make_dir_if_not_present=make_dir_if_not_present)
        if include_cif:
            s = vinput["POSCAR"].structure
            fname = Path(output_dir) / ("%s.cif" % re.sub(r'\s', "", s.formula))
            s.to(filename=fname)


Instruction:
How would you implement a function in Python 3 that
gets the default number of electrons for a given structure.

Response:
def nelect(self):
        """
        Gets the default number of electrons for a given structure.
        """
        # if structure is not sorted this can cause problems, so must take
        # care to remove redundant symbols when counting electrons
        site_symbols = list(set(self.poscar.site_symbols))
        nelect = 0.
        for ps in self.potcar:
            if ps.element in site_symbols:
                site_symbols.remove(ps.element)
                nelect += self.structure.composition.element_composition[
                              ps.element] * ps.ZVAL

        if self.use_structure_charge:
            return nelect - self.structure.charge
        else:
            return nelect


Instruction:
Given the following Python 3 function, write the documentation
def kpoints(self):
        settings = self.user_kpoints_settings or self._config_dict["KPOINTS"]

        if isinstance(settings, Kpoints):
            return settings

        # If grid_density is in the kpoints_settings use
        # Kpoints.automatic_density
        if settings.get('grid_density'):
            return Kpoints.automatic_density(
                self.structure, int(settings['grid_density']),
                self.force_gamma)

        # If reciprocal_density is in the kpoints_settings use
        # Kpoints.automatic_density_by_vol
        elif settings.get('reciprocal_density'):
            return Kpoints.automatic_density_by_vol(
                self.structure, int(settings['reciprocal_density']),
                self.force_gamma)

        # If length is in the kpoints_settings use Kpoints.automatic
        elif settings.get('length'):
            return Kpoints.automatic(settings['length'])

        # Raise error. Unsure of which kpoint generation to use
        else:
            raise ValueError(
                "Invalid KPoint Generation algo : Supported Keys are "
                "grid_density: for Kpoints.automatic_density generation, "
                "reciprocal_density: for KPoints.automatic_density_by_vol "
                "generation, and length  : for Kpoints.automatic generation")

Response: Writes out a KPOINTS file using the fully automated grid method.


Instruction:
Can you tell what is the following Python 3 function doing
def from_prev_calc(cls, prev_calc_dir, standardize=False, sym_prec=0.1,
                       international_monoclinic=True, reciprocal_density=100,
                       small_gap_multiply=None, **kwargs):
        """
        Generate a set of Vasp input files for static calculations from a
        directory of previous Vasp run.

        Args:
            prev_calc_dir (str): Directory containing the outputs(
                vasprun.xml and OUTCAR) of previous vasp run.
            standardize (float): Whether to standardize to a primitive
                standard cell. Defaults to False.
            sym_prec (float): Tolerance for symmetry finding. If not 0,
                the final structure from the previous run will be symmetrized
                to get a primitive standard cell. Set to 0 if you don't want
                that.
            international_monoclinic (bool): Whether to use international
                    convention (vs Curtarolo) for monoclinic. Defaults True.
            reciprocal_density (int): density of k-mesh by reciprocal
                                    volume (defaults to 100)
            small_gap_multiply ([float, float]): If the gap is less than
                1st index, multiply the default reciprocal_density by the 2nd
                index.
            \\*\\*kwargs: All kwargs supported by MPStaticSet,
                other than prev_incar and prev_structure and prev_kpoints which
                are determined from the prev_calc_dir.
        """
        vasprun, outcar = get_vasprun_outcar(prev_calc_dir)

        prev_incar = vasprun.incar
        prev_kpoints = vasprun.kpoints

        if standardize:
            warnings.warn("Use of standardize=True with from_prev_run is not "
                          "recommended as there is no guarantee the copied "
                          "files will be appropriate for the standardized "
                          "structure. copy_chgcar is enforced to be false.")

        # We will make a standard structure for the given symprec.
        prev_structure = get_structure_from_prev_run(
            vasprun, outcar, sym_prec=standardize and sym_prec,
            international_monoclinic=international_monoclinic)

        # multiply the reciprocal density if needed:
        if small_gap_multiply:
            gap = vasprun.eigenvalue_band_properties[0]
            if gap <= small_gap_multiply[0]:
                reciprocal_density = reciprocal_density * small_gap_multiply[1]

        return cls(
            structure=prev_structure, prev_incar=prev_incar,
            prev_kpoints=prev_kpoints,
            reciprocal_density=reciprocal_density, **kwargs)

Response: Generate a set of Vasp input files for static calculations from the previous Vasp run.


Instruction:
Here you have a function in Python 3, explain what it does
def from_prev_calc(cls, prev_calc_dir, mode="gap",
                       reciprocal_density=50, copy_chgcar=True, **kwargs):
        """
        Generate a set of Vasp input files for HSE calculations from a
        directory of previous Vasp run. if mode=="gap", it explicitly adds VBM
        and CBM of the prev run to the k-point list of this run.

        Args:
            prev_calc_dir (str): Directory containing the outputs
                (vasprun.xml and OUTCAR) of previous vasp run.
            mode (str): Either "uniform", "gap" or "line"
            reciprocal_density (int): density of k-mesh
            copy_chgcar (bool): whether to copy CHGCAR of previous run
            \\*\\*kwargs: All kwargs supported by MPHSEBSStaticSet,
                other than prev_structure which is determined from the previous
                calc dir.
        """

        vasprun, outcar = get_vasprun_outcar(prev_calc_dir)

        # note: don't standardize the cell because we want to retain k-points
        prev_structure = get_structure_from_prev_run(vasprun, outcar,
                                                     sym_prec=0)

        added_kpoints = []

        if mode.lower() == "gap":
            bs = vasprun.get_band_structure()
            vbm, cbm = bs.get_vbm()["kpoint"], bs.get_cbm()["kpoint"]
            if vbm:
                added_kpoints.append(vbm.frac_coords)
            if cbm:
                added_kpoints.append(cbm.frac_coords)

        files_to_transfer = {}
        if copy_chgcar:
            chgcars = sorted(glob.glob(str(Path(prev_calc_dir) / "CHGCAR*")))
            if chgcars:
                files_to_transfer["CHGCAR"] = str(chgcars[-1])

        return cls(
            structure=prev_structure,
            added_kpoints=added_kpoints, reciprocal_density=reciprocal_density,
            mode=mode, files_to_transfer=files_to_transfer, **kwargs)

Response: Generate a set of HSE input files for HSE calculations from a previous Vasp run.


Instruction:
Can you write a function in Python 3 where it
generates a set of Vasp input files for NonSCF calculations from the previous Vasp run directory.

Response:
def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True,
                       nbands_factor=1.2, standardize=False, sym_prec=0.1,
                       international_monoclinic=True, reciprocal_density=100,
                       kpoints_line_density=20, small_gap_multiply=None,
                       **kwargs):
        """
        Generate a set of Vasp input files for NonSCF calculations from a
        directory of previous static Vasp run.

        Args:
            prev_calc_dir (str): The directory contains the outputs(
                vasprun.xml and OUTCAR) of previous vasp run.
            copy_chgcar: Whether to copy the old CHGCAR. Defaults to True.
            nbands_factor (float): Multiplicative factor for NBANDS. Choose a
                higher number if you are doing an LOPTICS calculation.
            standardize (float): Whether to standardize to a primitive
                standard cell. Defaults to False.
            sym_prec (float): Tolerance for symmetry finding. If not 0,
                the final structure from the previous run will be symmetrized
                to get a primitive standard cell. Set to 0 if you don't want
                that.
            international_monoclinic (bool): Whether to use international
                convention (vs Curtarolo) for monoclinic. Defaults True.
            reciprocal_density (int): density of k-mesh by reciprocal
                volume in uniform mode (defaults to 100)
            kpoints_line_density (int): density of k-mesh in line mode
                (defaults to 20)
            small_gap_multiply ([float, float]): If the gap is less than
                1st index, multiply the default reciprocal_density by the 2nd
                index.
            \\*\\*kwargs: All kwargs supported by MPNonSCFSet,
                other than structure, prev_incar and prev_chgcar which
                are determined from the prev_calc_dir.
        """
        vasprun, outcar = get_vasprun_outcar(prev_calc_dir)

        incar = vasprun.incar
        # Get a Magmom-decorated structure
        structure = get_structure_from_prev_run(
            vasprun, outcar, sym_prec=standardize and sym_prec,
            international_monoclinic=international_monoclinic)
        # Turn off spin when magmom for every site is smaller than 0.02.
        if outcar and outcar.magnetization:
            site_magmom = np.array([i['tot'] for i in outcar.magnetization])
            ispin = 2 if np.any(site_magmom[np.abs(site_magmom) > 0.02]) else 1
        elif vasprun.is_spin:
            ispin = 2
        else:
            ispin = 1
        nbands = int(np.ceil(vasprun.parameters["NBANDS"] * nbands_factor))
        incar.update({"ISPIN": ispin, "NBANDS": nbands})

        files_to_transfer = {}

        if standardize:
            warnings.warn("Use of standardize=True with from_prev_run is not "
                          "recommended as there is no guarantee the copied "
                          "files will be appropriate for the standardized"
                          " structure. copy_chgcar is enforced to be false.")
            copy_chgcar = False

        if copy_chgcar:
            chgcars = sorted(glob.glob(str(Path(prev_calc_dir) / "CHGCAR*")))
            if chgcars:
                files_to_transfer["CHGCAR"] = str(chgcars[-1])

        # multiply the reciprocal density if needed:
        if small_gap_multiply:
            gap = vasprun.eigenvalue_band_properties[0]
            if gap <= small_gap_multiply[0]:
                reciprocal_density = reciprocal_density * small_gap_multiply[1]
                kpoints_line_density = kpoints_line_density * \
                    small_gap_multiply[1]

        return cls(structure=structure, prev_incar=incar,
                   reciprocal_density=reciprocal_density,
                   kpoints_line_density=kpoints_line_density,
                   files_to_transfer=files_to_transfer, **kwargs)


Instruction:
How would you code a function in Python 3 to
generate a set of SOC input files for SOC calculations from the previous Vasp run.

Response:
def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True,
                       nbands_factor=1.2, standardize=False, sym_prec=0.1,
                       international_monoclinic=True, reciprocal_density=100,
                       small_gap_multiply=None, **kwargs):
        """
        Generate a set of Vasp input files for SOC calculations from a
        directory of previous static Vasp run. SOC calc requires all 3
        components for MAGMOM for each atom in the structure.

        Args:
            prev_calc_dir (str): The directory contains the outputs(
                vasprun.xml and OUTCAR) of previous vasp run.
            copy_chgcar: Whether to copy the old CHGCAR. Defaults to True.
            nbands_factor (float): Multiplicative factor for NBANDS. Choose a
                higher number if you are doing an LOPTICS calculation.
            standardize (float): Whether to standardize to a primitive
                standard cell. Defaults to False.
            sym_prec (float): Tolerance for symmetry finding. If not 0,
                the final structure from the previous run will be symmetrized
                to get a primitive standard cell. Set to 0 if you don't want
                that.
            international_monoclinic (bool): Whether to use international
                convention (vs Curtarolo) for monoclinic. Defaults True.
            reciprocal_density (int): density of k-mesh by reciprocal
                volume (defaults to 100)
            small_gap_multiply ([float, float]): If the gap is less than
                1st index, multiply the default reciprocal_density by the 2nd
                index.
            \\*\\*kwargs: All kwargs supported by MPSOCSet,
                other than structure, prev_incar and prev_chgcar which
                are determined from the prev_calc_dir.
        """
        vasprun, outcar = get_vasprun_outcar(prev_calc_dir)

        incar = vasprun.incar

        # Remove magmoms from previous INCAR, since we will prefer
        # the final calculated magmoms
        # TODO: revisit in context of MPStaticSet incar logic
        if 'MAGMOM' in incar:
            del incar['magmom']

        # Get a magmom-decorated structure
        structure = get_structure_from_prev_run(
            vasprun, outcar, sym_prec=standardize and sym_prec,
            international_monoclinic=international_monoclinic)
        # override magmom if provided
        if kwargs.get("magmom", None):
            structure = structure.copy(
                site_properties={"magmom": kwargs["magmom"]})
            kwargs.pop("magmom", None)
        # magmom has to be 3D for SOC calculation.
        if hasattr(structure[0], "magmom"):
            if not isinstance(structure[0].magmom, list):
                structure = structure.copy(site_properties={
                    "magmom": [[0, 0, site.magmom] for site in structure]})
        else:
            raise ValueError("Neither the previous structure has mamgom "
                             "property nor magmom provided")

        nbands = int(np.ceil(vasprun.parameters["NBANDS"] * nbands_factor))
        incar.update({"NBANDS": nbands})

        if standardize:
            warnings.warn("Use of standardize=True with from_prev_run is not "
                          "recommended as there is no guarantee the copied "
                          "files will be appropriate for the standardized"
                          " structure. copy_chgcar is enforced to be false.")
            copy_chgcar = False

        files_to_transfer = {}
        if copy_chgcar:
            chgcars = sorted(glob.glob(str(Path(prev_calc_dir) / "CHGCAR*")))
            if chgcars:
                files_to_transfer["CHGCAR"] = str(chgcars[-1])

        # multiply the reciprocal density if needed:
        if small_gap_multiply:
            gap = vasprun.eigenvalue_band_properties[0]
            if gap <= small_gap_multiply[0]:
                reciprocal_density = reciprocal_density * small_gap_multiply[1]

        return cls(structure, prev_incar=incar,
                   files_to_transfer=files_to_transfer,
                   reciprocal_density=reciprocal_density, **kwargs)


Instruction:
Write a Python 3 script to
generate gamma center k - points mesh grid for GW calculation

Response:
def kpoints(self):
        """
        Generate gamma center k-points mesh grid for GW calc,
        which is requested by GW calculation.
        """
        return Kpoints.automatic_density_by_vol(self.structure,
                                                self.reciprocal_density,
                                                force_gamma=True)


Instruction:
Given the following Python 3 function, write the documentation
def from_prev_calc(cls, prev_calc_dir, copy_wavecar=True, mode="DIAG",
                       nbands_factor=5, ncores=16, **kwargs):
        """
        Generate a set of Vasp input files for GW or BSE calculations from a
        directory of previous Exact Diag Vasp run.

        Args:
            prev_calc_dir (str): The directory contains the outputs(
                vasprun.xml of previous vasp run.
            copy_wavecar: Whether to copy the old WAVECAR, WAVEDER and
                associated files. Defaults to True.
            mode (str): Supported modes are "STATIC", "DIAG" (default), "GW",
                and "BSE".
            nbands_factor (int): Multiplicative factor for NBANDS. Only applies
                if mode=="DIAG". Need to be tested for convergence.
            ncores (int): numbers of cores you do calculations. VASP will alter
                NBANDS if it was not dividable by ncores. Only applies
                if mode=="DIAG".
            \\*\\*kwargs: All kwargs supported by MVLGWSet,
                other than structure, prev_incar and mode, which
                are determined from the prev_calc_dir.
        """
        vasprun, outcar = get_vasprun_outcar(prev_calc_dir)
        prev_incar = vasprun.incar
        structure = vasprun.final_structure

        nbands = int(vasprun.parameters["NBANDS"])
        if mode.upper() == "DIAG":
            nbands = int(np.ceil(nbands * nbands_factor / ncores) * ncores)

        # copy WAVECAR, WAVEDER (derivatives)
        files_to_transfer = {}
        if copy_wavecar:
            for fname in ("WAVECAR", "WAVEDER", "WFULL"):
                w = sorted(glob.glob(str(Path(prev_calc_dir) / (fname + "*"))))
                if w:
                    if fname == "WFULL":
                        for f in w:
                            fname = Path(f).name
                            fname = fname.split(".")[0]
                            files_to_transfer[fname] = f
                    else:
                        files_to_transfer[fname] = str(w[-1])

        return cls(structure=structure, prev_incar=prev_incar,
                   nbands=nbands, mode=mode,
                   files_to_transfer=files_to_transfer, **kwargs)

Response: Generate a set of Vasp input files for GW or BSE calculations from a directory containing the previous Exact Diag Vasp run.


Instruction:
How would you explain what the following Python 3 function does
def kpoints(self):

        # To get input sets, the input structure has to has the same number
        # of required parameters as a Structure object (ie. 4). Slab
        # attributes aren't going to affect the VASP inputs anyways so
        # converting the slab into a structure should not matter

        kpt = super().kpoints
        kpt.comment = "Automatic mesh"
        kpt.style = 'Gamma'

        # use k_product to calculate kpoints, k_product = kpts[0][0] * a
        abc = self.structure.lattice.abc
        kpt_calc = [int(self.k_product / abc[0] + 0.5),
                    int(self.k_product / abc[1] + 0.5), 1]
        self.kpt_calc = kpt_calc
        # calculate kpts (c direction) for bulk. (for slab, set to 1)
        if self.bulk:
            kpt_calc[2] = int(self.k_product / abc[2] + 0.5)

        kpt.kpts[0] = kpt_calc

        return kpt

Response: get the kpoints for the slab


Instruction:
Can you generate a brief explanation for the following Python 3 code
def kpoints(self):

        # To get input sets, the input structure has to has the same number
        # of required parameters as a Structure object.

        kpt = super().kpoints
        kpt.comment = "Generated by pymatgen's MVLGBSet"
        kpt.style = 'Gamma'

        # use k_product to calculate kpoints, k_product = kpts[0][0] * a
        lengths = self.structure.lattice.abc
        kpt_calc = [int(self.k_product / lengths[0] + 0.5),
                    int(self.k_product / lengths[1] + 0.5),
                    int(self.k_product / lengths[2] + 0.5)]

        if self.slab_mode:
            kpt_calc[2] = 1

        kpt.kpts[0] = kpt_calc

        return kpt

Response: Return a kpoint set for the input structure.


Instruction:
Can you implement a function in Python 3 that
removes any atom jumps across the cell

Response:
def _process_structures(structures):
        """
        Remove any atom jumps across the cell
        """
        input_structures = structures
        structures = [input_structures[0]]
        for s in input_structures[1:]:
            prev = structures[-1]
            for i in range(len(s)):
                t = np.round(prev[i].frac_coords - s[i].frac_coords)
                if np.any(np.abs(t) > 0.5):
                    s.translate_sites([i], t, to_unit_cell=False)
            structures.append(s)
        return structures


Instruction:
Implement a function in Python 3 to
write the input files for the NEB and returns the path to the output directory.

Response:
def write_input(self, output_dir, make_dir_if_not_present=True,
                    write_cif=False, write_path_cif=False,
                    write_endpoint_inputs=False):
        """
        NEB inputs has a special directory structure where inputs are in 00,
        01, 02, ....

        Args:
            output_dir (str): Directory to output the VASP input files
            make_dir_if_not_present (bool): Set to True if you want the
                directory (and the whole path) to be created if it is not
                present.
            write_cif (bool): If true, writes a cif along with each POSCAR.
            write_path_cif (bool): If true, writes a cif for each image.
            write_endpoint_inputs (bool): If true, writes input files for
                running endpoint calculations.
        """
        output_dir = Path(output_dir)
        if make_dir_if_not_present and not output_dir.exists():
            output_dir.mkdir(parents=True)
        self.incar.write_file(str(output_dir / 'INCAR'))
        self.kpoints.write_file(str(output_dir / 'KPOINTS'))
        self.potcar.write_file(str(output_dir / 'POTCAR'))

        for i, p in enumerate(self.poscars):
            d = output_dir / str(i).zfill(2)
            if not d.exists():
                d.mkdir(parents=True)
            p.write_file(str(d / 'POSCAR'))
            if write_cif:
                p.structure.to(filename=str(d / '{}.cif'.format(i)))
        if write_endpoint_inputs:
            end_point_param = MITRelaxSet(
                self.structures[0],
                user_incar_settings=self.user_incar_settings)

            for image in ['00', str(len(self.structures) - 1).zfill(2)]:
                end_point_param.incar.write_file(
                    str(output_dir / image / 'INCAR'))
                end_point_param.kpoints.write_file(
                    str(output_dir / image / 'KPOINTS'))
                end_point_param.potcar.write_file(
                    str(output_dir / image / 'POTCAR'))
        if write_path_cif:
            sites = set()
            l = self.structures[0].lattice
            for site in chain(*(s.sites for s in self.structures)):
                sites.add(
                    PeriodicSite(site.species, site.frac_coords, l))
            nebpath = Structure.from_sites(sorted(sites))
            nebpath.to(filename=str(output_dir / 'path.cif'))


Instruction:
Here you have a function in Python 3, explain what it does
def get_uvec(vec):
    l = np.linalg.norm(vec)
    if l < 1e-8:
        return vec
    return vec / l

Response: Gets a unit vector parallel to input vector


Instruction:
Create a Python 3 function for
functioning that converts a list of tensors corresponding to a structure and returns a dictionary consisting of unique tensors with symmops corresponding to the remaining tensors.

Response:
def symmetry_reduce(tensors, structure, tol=1e-8, **kwargs):
    """
    Function that converts a list of tensors corresponding to a structure
    and returns a dictionary consisting of unique tensor keys with symmop
    values corresponding to transformations that will result in derivative
    tensors from the original list

    Args:
        tensors (list of tensors): list of Tensor objects to test for
            symmetrically-equivalent duplicates
        structure (Structure): structure from which to get symmetry
        tol (float): tolerance for tensor equivalence
        kwargs: keyword arguments for the SpacegroupAnalyzer

    returns:
        dictionary consisting of unique tensors with symmetry operations
        corresponding to those which will reconstruct the remaining
        tensors as values
    """
    sga = SpacegroupAnalyzer(structure, **kwargs)
    symmops = sga.get_symmetry_operations(cartesian=True)
    unique_mapping = TensorMapping([tensors[0]], [[]], tol=tol)
    for tensor in tensors[1:]:
        is_unique = True
        for unique_tensor, symmop in itertools.product(unique_mapping, symmops):
            if np.allclose(unique_tensor.transform(symmop), tensor, atol=tol):
                unique_mapping[unique_tensor].append(symmop)
                is_unique = False
                break
        if is_unique:
            unique_mapping[tensor] = []
    return unique_mapping


Instruction:
Explain what the following Python 3 code does
def get_tkd_value(tensor_keyed_dict, tensor, allclose_kwargs=None):
    if allclose_kwargs is None:
        allclose_kwargs = {}
    for tkey, value in tensor_keyed_dict.items():
        if np.allclose(tensor, tkey, **allclose_kwargs):
            return value

Response: Helper function to find a value in a tensor - keyed - dict using an approximation to the key.


Instruction:
Write a Python 3 function for
returning a copy of the matrix with all entries below a certain threshold

Response:
def zeroed(self, tol=1e-3):
        """
        returns the matrix with all entries below a certain threshold
        (i.e. tol) set to zero
        """
        new_tensor = self.copy()
        new_tensor[abs(new_tensor) < tol] = 0
        return new_tensor


Instruction:
Write a Python 3 script to
rotate the object to the specified rotation matrix.

Response:
def rotate(self, matrix, tol=1e-3):
        """
        Applies a rotation directly, and tests input matrix to ensure a valid
        rotation.

        Args:
            matrix (3x3 array-like): rotation matrix to be applied to tensor
            tol (float): tolerance for testing rotation matrix validity
        """
        matrix = SquareTensor(matrix)
        if not matrix.is_rotation(tol):
            raise ValueError("Rotation matrix is not valid.")
        sop = SymmOp.from_rotation_and_translation(matrix,
                                                   [0., 0., 0.])
        return self.transform(sop)


Instruction:
How would you code a function in Python 3 to
calculate the result of an einstein summation expression for the given set of other_arrays.

Response:
def einsum_sequence(self, other_arrays, einsum_string=None):
        """
        Calculates the result of an einstein summation expression
        """
        if not isinstance(other_arrays, list):
            raise ValueError("other tensors must be list of "
                             "tensors or tensor input")

        other_arrays = [np.array(a) for a in other_arrays]
        if not einsum_string:
            lc = string.ascii_lowercase
            einsum_string = lc[:self.rank]
            other_ranks = [len(a.shape) for a in other_arrays]
            idx = self.rank - sum(other_ranks)
            for length in other_ranks:
                einsum_string += ',' + lc[idx:idx + length]
                idx += length

        einsum_args = [self] + list(other_arrays)
        return np.einsum(einsum_string, *einsum_args)


Instruction:
Can you implement a function in Python 3 that
returns the tensor dotted into a unit vector with the given n.

Response:
def project(self, n):
        """
        Convenience method for projection of a tensor into a
        vector.  Returns the tensor dotted into a unit vector
        along the input n.

        Args:
            n (3x1 array-like): direction to project onto

        Returns (float):
            scalar value corresponding to the projection of
            the tensor into the vector

        """
        n = get_uvec(n)
        return self.einsum_sequence([n] * self.rank)


Instruction:
Here you have a function in Python 3, explain what it does
def get_grouped_indices(self, voigt=False, **kwargs):
        if voigt:
            array = self.voigt
        else:
            array = self

        indices = list(itertools.product(*[range(n) for n in array.shape]))
        remaining = indices.copy()
        # Start with everything near zero
        grouped = [list(zip(*np.where(np.isclose(array, 0, **kwargs))))]
        remaining = [i for i in remaining if i not in grouped[0]]
        # Iteratively run through remaining indices
        while remaining:
            new = list(zip(*np.where(np.isclose(
                array, array[remaining[0]], **kwargs))))
            grouped.append(new)
            remaining = [i for i in remaining if i not in new]
        # Don't return any empty lists
        return [g for g in grouped if g]

Response: Returns a list of indices for equivalent tensor values.


Instruction:
Can you implement a function in Python 3 that
returns a dictionary that associates the symbol with the corresponding key.

Response:
def get_symbol_dict(self, voigt=True, zero_index=False, **kwargs):
        """
        Creates a summary dict for tensor with associated symbol

        Args:
            voigt (bool): whether to get symbol dict for voigt
                notation tensor, as opposed to full notation,
                defaults to true
            zero_index (bool): whether to set initial index to zero,
                defaults to false, since tensor notations tend to use
                one-indexing, rather than zero indexing like python
            **kwargs: keyword args for np.isclose.  Can take atol
                and rtol for absolute and relative tolerance, e. g.

                >>> tensor.get_symbol_dict(atol=1e-8)

                or

                >>> tensor.get_symbol_dict(rtol=1e-5)

        Returns:
            list of index groups where tensor values are equivalent to
            within tolerances

        Returns:

        """
        d = {}
        if voigt:
            array = self.voigt
        else:
            array = self
        grouped = self.get_grouped_indices(voigt=voigt, **kwargs)
        if zero_index:
            p = 0
        else:
            p = 1
        for indices in grouped:
            sym_string = self.symbol + '_'
            sym_string += ''.join([str(i + p) for i in indices[0]])
            value = array[indices[0]]
            if not np.isclose(value, 0):
                d[sym_string] = array[indices[0]]
        return d


Instruction:
Can you generate the documentation for the following Python 3 function
def round(self, decimals=0):
        return self.__class__(np.round(self, decimals=decimals))

Response:
Wrapper around numpy. round to ensure that object
            is returned.


Instruction:
Implement a function in Python 3 to
return a generally symmetrized tensor calculated by taking the sum of the tensor and its transpose with respect to all possible permutations of indices

Response:
def symmetrized(self):
        """
        Returns a generally symmetrized tensor, calculated by taking
        the sum of the tensor and its transpose with respect to all
        possible permutations of indices
        """
        perms = list(itertools.permutations(range(self.rank)))
        return sum([np.transpose(self, ind) for ind in perms]) / len(perms)


Instruction:
Can you tell what is the following Python 3 function doing
def voigt_symmetrized(self):
        if not (self.rank % 2 == 0 and self.rank >= 2):
            raise ValueError("V-symmetrization requires rank even and >= 2")

        v = self.voigt
        perms = list(itertools.permutations(range(len(v.shape))))
        new_v = sum([np.transpose(v, ind) for ind in perms]) / len(perms)
        return self.__class__.from_voigt(new_v)

Response: Returns a voigt - notation version of the current object.


Instruction:
How would you explain what the following Python 3 function does
def fit_to_structure(self, structure, symprec=0.1):
        sga = SpacegroupAnalyzer(structure, symprec)
        symm_ops = sga.get_symmetry_operations(cartesian=True)
        return sum([self.transform(symm_op)
                    for symm_op in symm_ops]) / len(symm_ops)

Response:
Fits the symmetry operations corresponding to a structure and returns a tensor that is invariant with respect to symmetry
COOKIE operations corresponding to a structure.


Instruction:
Explain what the following Python 3 code does
def is_fit_to_structure(self, structure, tol=1e-2):
        return (self - self.fit_to_structure(structure) < tol).all()

Response: Tests whether a tensor is invariant with respect to the symmetric portion of the structure.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_voigt_symmetric(self, tol=1e-6):
        transpose_pieces = [[[0 for i in range(self.rank % 2)]]]
        transpose_pieces += [[range(j, j + 2)] for j in
                             range(self.rank % 2, self.rank, 2)]
        for n in range(self.rank % 2, len(transpose_pieces)):
            if len(transpose_pieces[n][0]) == 2:
                transpose_pieces[n] += [transpose_pieces[n][0][::-1]]
        for trans_seq in itertools.product(*transpose_pieces):
            trans_seq = list(itertools.chain(*trans_seq))
            if (self - self.transpose(trans_seq) > tol).any():
                return False
        return True

Response:
Tests symmetry of tensor to that necessary for voigt - conversion
        by grouping indices into pairs and constructing a sequence of possible permutations to be used in a tensor transpose


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_voigt_dict(rank):
        vdict = {}
        for ind in itertools.product(*[range(3)] * rank):
            v_ind = ind[:rank % 2]
            for j in range(rank // 2):
                pos = rank % 2 + 2 * j
                v_ind += (reverse_voigt_map[ind[pos:pos + 2]],)
            vdict[ind] = v_ind
        return vdict

Response:
Returns a dictionary that maps indices in the tensor to those
        in a voigt representation based on input rank


Instruction:
Given the following Python 3 function, write the documentation
def from_voigt(cls, voigt_input):
        voigt_input = np.array(voigt_input)
        rank = sum(voigt_input.shape) // 3
        t = cls(np.zeros([3] * rank))
        if voigt_input.shape != t._vscale.shape:
            raise ValueError("Invalid shape for voigt matrix")
        voigt_input = voigt_input / t._vscale
        this_voigt_map = t.get_voigt_dict(rank)
        for ind in this_voigt_map:
            t[ind] = voigt_input[this_voigt_map[ind]]
        return cls(t)

Response: Returns a new object from a voigt notation vector or matrix.


Instruction:
How would you explain what the following Python 3 function does
def get_ieee_rotation(structure, refine_rotation=True):
        # Check conventional setting:
        sga = SpacegroupAnalyzer(structure)
        dataset = sga.get_symmetry_dataset()
        trans_mat = dataset['transformation_matrix']
        conv_latt = Lattice(np.transpose(np.dot(np.transpose(
            structure.lattice.matrix), np.linalg.inv(trans_mat))))
        xtal_sys = sga.get_crystal_system()

        vecs = conv_latt.matrix
        lengths = np.array(conv_latt.abc)
        angles = np.array(conv_latt.angles)
        rotation = np.zeros((3, 3))

        # IEEE rules: a,b,c || x1,x2,x3
        if xtal_sys == "cubic":
            rotation = [vecs[i] / lengths[i] for i in range(3)]

        # IEEE rules: a=b in length; c,a || x3, x1
        elif xtal_sys == "tetragonal":
            rotation = np.array([vec / mag for (mag, vec) in
                                 sorted(zip(lengths, vecs),
                                        key=lambda x: x[0])])
            if abs(lengths[2] - lengths[1]) < abs(lengths[1] - lengths[0]):
                rotation[0], rotation[2] = rotation[2], rotation[0].copy()
            rotation[1] = get_uvec(np.cross(rotation[2], rotation[0]))

        # IEEE rules: c<a<b; c,a || x3,x1
        elif xtal_sys == "orthorhombic":
            rotation = [vec / mag for (mag, vec) in sorted(zip(lengths, vecs))]
            rotation = np.roll(rotation, 2, axis=0)

        # IEEE rules: c,a || x3,x1, c is threefold axis
        # Note this also includes rhombohedral crystal systems
        elif xtal_sys in ("trigonal", "hexagonal"):
            # find threefold axis:
            tf_index = np.argmin(abs(angles - 120.))
            non_tf_mask = np.logical_not(angles == angles[tf_index])
            rotation[2] = get_uvec(vecs[tf_index])
            rotation[0] = get_uvec(vecs[non_tf_mask][0])
            rotation[1] = get_uvec(np.cross(rotation[2], rotation[0]))

        # IEEE rules: b,c || x2,x3; alpha=beta=90, c<a
        elif xtal_sys == "monoclinic":
            # Find unique axis
            u_index = np.argmax(abs(angles - 90.))
            n_umask = np.logical_not(angles == angles[u_index])
            rotation[1] = get_uvec(vecs[u_index])
            # Shorter of remaining lattice vectors for c axis
            c = [vec / mag for (mag, vec) in
                 sorted(zip(lengths[n_umask], vecs[n_umask]))][0]
            rotation[2] = np.array(c)
            rotation[0] = np.cross(rotation[1], rotation[2])

        # IEEE rules: c || x3, x2 normal to ac plane
        elif xtal_sys == "triclinic":
            rotation = [vec / mag for (mag, vec) in sorted(zip(lengths, vecs))]
            rotation[1] = get_uvec(np.cross(rotation[2], rotation[0]))
            rotation[0] = np.cross(rotation[1], rotation[2])

        rotation = SquareTensor(rotation)
        if refine_rotation:
            rotation = rotation.refine_rotation()

        return rotation

Response: This function determines the rotation matrix for the IEEE conversion according to the 1987 IEEE standards.


Instruction:
Can you create a Python 3 function that
converts a structure to IEEE format.

Response:
def convert_to_ieee(self, structure, initial_fit=True,
                        refine_rotation=True):
        """
        Given a structure associated with a tensor, attempts a
        calculation of the tensor in IEEE format according to
        the 1987 IEEE standards.

        Args:
            structure (Structure): a structure associated with the
                tensor to be converted to the IEEE standard
            initial_fit (bool): flag to indicate whether initial
                tensor is fit to the symmetry of the structure.
                Defaults to true. Note that if false, inconsistent
                results may be obtained due to symmetrically
                equivalent, but distinct transformations
                being used in different versions of spglib.
            refine_rotation (bool): whether to refine the rotation
                produced by the ieee transform generator, default True
        """
        rotation = self.get_ieee_rotation(structure, refine_rotation)
        result = self.copy()
        if initial_fit:
            result = result.fit_to_structure(structure)
        return result.rotate(rotation, tol=1e-2)


Instruction:
Write a Python 3 script for
transforming a tensor from one basis for an original structure into a new basis defined by a new structure.

Response:
def structure_transform(self, original_structure, new_structure,
                            refine_rotation=True):
        """
        Transforms a tensor from one basis for an original structure
        into a new basis defined by a new structure.

        Args:
            original_structure (Structure): structure corresponding
                to the basis of the current tensor
            new_structure (Structure): structure corresponding to the
                desired basis
            refine_rotation (bool): whether to refine the rotations
                generated in get_ieee_rotation

        Returns:
            Tensor that has been transformed such that its basis
            corresponds to the new_structure's basis
        """
        sm = StructureMatcher()
        if not sm.fit(original_structure, new_structure):
            warnings.warn("original and new structures do not match!")
        trans_1 = self.get_ieee_rotation(original_structure, refine_rotation)
        trans_2 = self.get_ieee_rotation(new_structure, refine_rotation)
        # Get the ieee format tensor
        new = self.rotate(trans_1)
        # Reverse the ieee format rotation for the second structure
        new = new.rotate(np.transpose(trans_2))
        return new


Instruction:
Implement a Python 3 function for
creating a tensor from values and indices.

Response:
def from_values_indices(cls, values, indices, populate=False,
                            structure=None, voigt_rank=None,
                            vsym=True, verbose=False):
        """
        Creates a tensor from values and indices, with options
        for populating the remainder of the tensor.

        Args:
            values (floats): numbers to place at indices
            indices (array-likes): indices to place values at
            populate (bool): whether to populate the tensor
            structure (Structure): structure to base population
                or fit_to_structure on
            voigt_rank (int): full tensor rank to indicate the
                shape of the resulting tensor.  This is necessary
                if one provides a set of indices more minimal than
                the shape of the tensor they want, e.g.
                Tensor.from_values_indices((0, 0), 100)
            vsym (bool): whether to voigt symmetrize during the
                optimization procedure
            verbose (bool): whether to populate verbosely
        """
        # auto-detect voigt notation
        # TODO: refactor rank inheritance to make this easier
        indices = np.array(indices)
        if voigt_rank:
            shape = ([3]*(voigt_rank % 2) + [6]*(voigt_rank // 2))
        else:
            shape = np.ceil(np.max(indices+1, axis=0) / 3.) * 3
        base = np.zeros(shape.astype(int))
        for v, idx in zip(values, indices):
            base[tuple(idx)] = v
        if 6 in shape:
            obj = cls.from_voigt(base)
        else:
            obj = cls(base)
        if populate:
            assert structure, "Populate option must include structure input"
            obj = obj.populate(structure, vsym=vsym, verbose=verbose)
        elif structure:
            obj = obj.fit_to_structure(structure)
        return obj


Instruction:
Write a Python 3 script to
populate the non - zero entries of the current tensor with the values of the non - zero entries of the original tensor.

Response:
def populate(self, structure, prec=1e-5, maxiter=200, verbose=False,
                 precond=True, vsym=True):
        """
        Takes a partially populated tensor, and populates the non-zero
        entries according to the following procedure, iterated until
        the desired convergence (specified via prec) is achieved.

        1. Find non-zero entries
        2. Symmetrize the tensor with respect to crystal symmetry and
           (optionally) voigt symmetry
        3. Reset the non-zero entries of the original tensor

        Args:
            structure (structure object)
            prec (float): precision for determining a non-zero value
            maxiter (int): maximum iterations for populating the tensor
            verbose (bool): whether to populate verbosely
            precond (bool): whether to precondition by cycling through
                all symmops and storing new nonzero values, default True
            vsym (bool): whether to enforce voigt symmetry, defaults
                to True
        """
        if precond:
            # Generate the guess from populated
            sops = SpacegroupAnalyzer(structure).get_symmetry_operations()
            guess = Tensor(np.zeros(self.shape))
            mask = abs(self) > prec
            guess[mask] = self[mask]

            def merge(old, new):
                gmask = np.abs(old) > prec
                nmask = np.abs(new) > prec
                new_mask = np.logical_not(gmask)*nmask
                avg_mask = gmask*nmask
                old[avg_mask] = (old[avg_mask] + new[avg_mask]) / 2.
                old[new_mask] = new[new_mask]
            if verbose:
                print("Preconditioning for {} symmops".format(len(sops)))
            for sop in sops:
                rot = guess.transform(sop)
                # Store non-zero entries of new that weren't previously
                # in the guess in the guess
                merge(guess, rot)
            if verbose:
                print("Preconditioning for voigt symmetry".format(len(sops)))
            if vsym:
                v = guess.voigt
                perms = list(itertools.permutations(range(len(v.shape))))
                for perm in perms:
                    vtrans = np.transpose(v, perm)
                    merge(v, vtrans)
                guess = Tensor.from_voigt(v)
        else:
            guess = np.zeros(self.shape)

        assert guess.shape == self.shape, "Guess must have same shape"
        converged = False
        test_new, test_old = [guess.copy()]*2
        for i in range(maxiter):
            test_new = test_old.fit_to_structure(structure)
            if vsym:
                test_new = test_new.voigt_symmetrized
            diff = np.abs(test_old - test_new)
            converged = (diff < prec).all()
            if converged:
                break
            test_new[mask] = self[mask]
            test_old = test_new
            if verbose:
                print("Iteration {}: {}".format(i, np.max(diff)))
        if not converged:
            max_diff = np.max(np.abs(self - test_new))
            warnings.warn("Warning, populated tensor is not converged "
                          "with max diff of {}".format(max_diff))
        return self.__class__(test_new)


Instruction:
Create a Python 3 function to
return the object as a dictionary.

Response:
def as_dict(self, voigt=False):
        """
        Serializes the tensor object

        Args:
            voigt (bool): flag for whether to store entries in
                voigt-notation.  Defaults to false, as information
                may be lost in conversion.

        Returns (Dict):
            serialized format tensor object

        """
        input_array = self.voigt if voigt else self
        d = {"@module": self.__class__.__module__,
             "@class": self.__class__.__name__,
             "input_array": input_array.tolist()}
        if voigt:
            d.update({"voigt": voigt})
        return d


Instruction:
Can you generate a brief explanation for the following Python 3 code
def inv(self):
        if self.det == 0:
            raise ValueError("SquareTensor is non-invertible")
        return SquareTensor(np.linalg.inv(self))

Response: shorthand for matrix inverse on SquareTensor


Instruction:
How would you implement a function in Python 3 that
tests to see if the matrix is a valid rotation matrix.

Response:
def is_rotation(self, tol=1e-3, include_improper=True):
        """
        Test to see if tensor is a valid rotation matrix, performs a
        test to check whether the inverse is equal to the transpose
        and if the determinant is equal to one within the specified
        tolerance

        Args:
            tol (float): tolerance to both tests of whether the
                the determinant is one and the inverse is equal
                to the transpose
            include_improper (bool): whether to include improper
                rotations in the determination of validity
        """
        det = np.abs(np.linalg.det(self))
        if include_improper:
            det = np.abs(det)
        return (np.abs(self.inv - self.trans) < tol).all() \
            and (np.abs(det - 1.) < tol)


Instruction:
Make a summary of the following Python 3 code
def refine_rotation(self):
        new_x, y = get_uvec(self[0]), get_uvec(self[1])
        # Get a projection on y
        new_y = y - np.dot(new_x, y) * new_x
        new_z = np.cross(new_x, new_y)
        return SquareTensor([new_x, new_y, new_z])

Response: Refines the rotation matrix by ensuring that the second and third rows are perpindicular to the first.


Instruction:
Write a Python 3 function that can
calculate the average oxidation state of a site.

Response:
def compute_average_oxidation_state(site):
    """
    Calculates the average oxidation state of a site

    Args:
        site: Site to compute average oxidation state

    Returns:
        Average oxidation state of site.
    """
    try:
        avg_oxi = sum([sp.oxi_state * occu
                       for sp, occu in site.species.items()
                       if sp is not None])
        return avg_oxi
    except AttributeError:
        pass
    try:
        return site.charge
    except AttributeError:
        raise ValueError("Ewald summation can only be performed on structures "
                         "that are either oxidation state decorated or have "
                         "site charges.")


Instruction:
Implement a Python 3 function for
computing the total ewald energy for certain sites being removed.

Response:
def compute_partial_energy(self, removed_indices):
        """
        Gives total ewald energy for certain sites being removed, i.e. zeroed
        out.
        """
        total_energy_matrix = self.total_energy_matrix.copy()
        for i in removed_indices:
            total_energy_matrix[i, :] = 0
            total_energy_matrix[:, i] = 0
        return sum(sum(total_energy_matrix))


Instruction:
Write a Python 3 script to
compute total ewald energy for a given sub - structure.

Response:
def compute_sub_structure(self, sub_structure, tol=1e-3):
        """
        Gives total ewald energy for an sub structure in the same
        lattice. The sub_structure must be a subset of the original
        structure, with possible different charges.

        Args:
            substructure (Structure): Substructure to compute Ewald sum for.
            tol (float): Tolerance for site matching in fractional coordinates.

        Returns:
            Ewald sum of substructure.
        """
        total_energy_matrix = self.total_energy_matrix.copy()

        def find_match(site):
            for test_site in sub_structure:
                frac_diff = abs(np.array(site.frac_coords)
                                - np.array(test_site.frac_coords)) % 1
                frac_diff = [abs(a) < tol or abs(a) > 1 - tol
                             for a in frac_diff]
                if all(frac_diff):
                    return test_site
            return None

        matches = []
        for i, site in enumerate(self._s):
            matching_site = find_match(site)
            if matching_site:
                new_charge = compute_average_oxidation_state(matching_site)
                old_charge = self._oxi_states[i]
                scaling_factor = new_charge / old_charge
                matches.append(matching_site)
            else:
                scaling_factor = 0
            total_energy_matrix[i, :] *= scaling_factor
            total_energy_matrix[:, i] *= scaling_factor

        if len(matches) != len(sub_structure):
            output = ["Missing sites."]
            for site in sub_structure:
                if site not in matches:
                    output.append("unmatched = {}".format(site))
            raise ValueError("\n".join(output))

        return sum(sum(total_energy_matrix))


Instruction:
Can you generate the documentation for the following Python 3 function
def get_site_energy(self, site_index):
        if self._charged:
            warn('Per atom energies for charged structures not supported in EwaldSummation')
        return np.sum(self._recip[:,site_index]) + np.sum(self._real[:,site_index]) \
            + self._point[site_index]

Response: Compute the energy of a single site in the structure


Instruction:
Implement a Python 3 function for
performing the reciprocal space summation. Calculates the quantity of the entries in the entry - set of the entry - set of the entry - set of the entry - set of the entry - set of the entry - set of the entry - set of the entry - set of the entry - set of the entry that is used to calculate the reciprocal space summation.

Response:
def _calc_recip(self):
        """
        Perform the reciprocal space summation. Calculates the quantity
        E_recip = 1/(2PiV) sum_{G < Gmax} exp(-(G.G/4/eta))/(G.G) S(G)S(-G)
        where
        S(G) = sum_{k=1,N} q_k exp(-i G.r_k)
        S(G)S(-G) = |S(G)|**2

        This method is heavily vectorized to utilize numpy's C backend for
        speed.
        """
        numsites = self._s.num_sites
        prefactor = 2 * pi / self._vol
        erecip = np.zeros((numsites, numsites), dtype=np.float)
        forces = np.zeros((numsites, 3), dtype=np.float)
        coords = self._coords
        rcp_latt = self._s.lattice.reciprocal_lattice
        recip_nn = rcp_latt.get_points_in_sphere([[0, 0, 0]], [0, 0, 0],
                                                 self._gmax)

        frac_coords = [fcoords for (fcoords, dist, i, img) in recip_nn if dist != 0]

        gs = rcp_latt.get_cartesian_coords(frac_coords)
        g2s = np.sum(gs ** 2, 1)
        expvals = np.exp(-g2s / (4 * self._eta))
        grs = np.sum(gs[:, None] * coords[None, :], 2)

        oxistates = np.array(self._oxi_states)

        # create array where q_2[i,j] is qi * qj
        qiqj = oxistates[None, :] * oxistates[:, None]

        # calculate the structure factor
        sreals = np.sum(oxistates[None, :] * np.cos(grs), 1)
        simags = np.sum(oxistates[None, :] * np.sin(grs), 1)

        for g, g2, gr, expval, sreal, simag in zip(gs, g2s, grs, expvals,
                                                   sreals, simags):

            # Uses the identity sin(x)+cos(x) = 2**0.5 sin(x + pi/4)
            m = (gr[None, :] + pi / 4) - gr[:, None]
            np.sin(m, m)
            m *= expval / g2

            erecip += m

            if self._compute_forces:
                pref = 2 * expval / g2 * oxistates
                factor = prefactor * pref * (
                    sreal * np.sin(gr) - simag * np.cos(gr))

                forces += factor[:, None] * g[None, :]

        forces *= EwaldSummation.CONV_FACT
        erecip *= prefactor * EwaldSummation.CONV_FACT * qiqj * 2 ** 0.5
        return erecip, forces


Instruction:
Make a summary of the following Python 3 code
def _calc_real_and_point(self):
        fcoords = self._s.frac_coords
        forcepf = 2.0 * self._sqrt_eta / sqrt(pi)
        coords = self._coords
        numsites = self._s.num_sites
        ereal = np.empty((numsites, numsites), dtype=np.float)

        forces = np.zeros((numsites, 3), dtype=np.float)

        qs = np.array(self._oxi_states)

        epoint = - qs ** 2 * sqrt(self._eta / pi)

        for i in range(numsites):
            nfcoords, rij, js, _ = self._s.lattice.get_points_in_sphere(fcoords,
                                    coords[i], self._rmax, zip_results=False)

            # remove the rii term
            inds = rij > 1e-8
            js = js[inds]
            rij = rij[inds]
            nfcoords = nfcoords[inds]

            qi = qs[i]
            qj = qs[js]

            erfcval = erfc(self._sqrt_eta * rij)
            new_ereals = erfcval * qi * qj / rij

            # insert new_ereals
            for k in range(numsites):
                ereal[k, i] = np.sum(new_ereals[js == k])

            if self._compute_forces:
                nccoords = self._s.lattice.get_cartesian_coords(nfcoords)

                fijpf = qj / rij ** 3 * (erfcval + forcepf * rij *
                                         np.exp(-self._eta * rij ** 2))
                forces[i] += np.sum(np.expand_dims(fijpf, 1) *
                                    (np.array([coords[i]]) - nccoords) *
                                    qi * EwaldSummation.CONV_FACT, axis=0)

        ereal *= 0.5 * EwaldSummation.CONV_FACT
        epoint *= EwaldSummation.CONV_FACT
        return ereal, epoint, forces

Response: Calculates the real and point of the resource in the system.


Instruction:
Explain what the following Python 3 code does
def minimize_matrix(self):
        if self._algo == EwaldMinimizer.ALGO_FAST or \
                        self._algo == EwaldMinimizer.ALGO_BEST_FIRST:
            return self._recurse(self._matrix, self._m_list,
                                 set(range(len(self._matrix))))

Response: This method returns the permutations that produce the lowest


Instruction:
Can you generate the documentation for the following Python 3 function
def add_m_list(self, matrix_sum, m_list):
        if self._output_lists is None:
            self._output_lists = [[matrix_sum, m_list]]
        else:
            bisect.insort(self._output_lists, [matrix_sum, m_list])
        if self._algo == EwaldMinimizer.ALGO_BEST_FIRST and \
                        len(self._output_lists) == self._num_to_return:
            self._finished = True
        if len(self._output_lists) > self._num_to_return:
            self._output_lists.pop()
        if len(self._output_lists) == self._num_to_return:
            self._current_minimum = self._output_lists[-1][0]

Response: Adds a list of entries to the output_lists and updates the current_minimum if the list is full.


Instruction:
Given the following Python 3 function, write the documentation
def best_case(self, matrix, m_list, indices_left):
        m_indices = []
        fraction_list = []
        for m in m_list:
            m_indices.extend(m[2])
            fraction_list.extend([m[0]] * m[1])

        indices = list(indices_left.intersection(m_indices))

        interaction_matrix = matrix[indices, :][:, indices]

        fractions = np.zeros(len(interaction_matrix)) + 1
        fractions[:len(fraction_list)] = fraction_list
        fractions = np.sort(fractions)

        # Sum associated with each index (disregarding interactions between
        # indices)
        sums = 2 * np.sum(matrix[indices], axis=1)
        sums = np.sort(sums)

        # Interaction corrections. Can be reduced to (1-x)(1-y) for x,y in
        # fractions each element in a column gets multiplied by (1-x), and then
        # the sum of the columns gets multiplied by (1-y) since fractions are
        # less than 1, there is no effect of one choice on the other
        step1 = np.sort(interaction_matrix) * (1 - fractions)
        step2 = np.sort(np.sum(step1, axis=1))
        step3 = step2 * (1 - fractions)
        interaction_correction = np.sum(step3)

        if self._algo == self.ALGO_TIME_LIMIT:
            elapsed_time = datetime.utcnow() - self._start_time
            speedup_parameter = elapsed_time.total_seconds() / 1800
            avg_int = np.sum(interaction_matrix, axis=None)
            avg_frac = np.average(np.outer(1 - fractions, 1 - fractions))
            average_correction = avg_int * avg_frac

            interaction_correction = average_correction * speedup_parameter \
                + interaction_correction * (1 - speedup_parameter)

        best_case = np.sum(matrix) + np.inner(sums[::-1], fractions - 1) \
            + interaction_correction

        return best_case

Response: Computes a best case given a matrix and manipulation list.


Instruction:
Given the following Python 3 function, write the documentation
def get_next_index(self, matrix, manipulation, indices_left):
        f = manipulation[0]
        indices = list(indices_left.intersection(manipulation[2]))
        sums = np.sum(matrix[indices], axis=1)
        if f < 1:
            next_index = indices[sums.argmax(axis=0)]
        else:
            next_index = indices[sums.argmin(axis=0)]

        return next_index

Response:
Returns an index that should have the most negative effect on the
            matrix sum


Instruction:
Can you tell what is the following Python 3 function doing
def _recurse(self, matrix, m_list, indices, output_m_list=[]):
        # check to see if we've found all the solutions that we need
        if self._finished:
            return

        # if we're done with the current manipulation, pop it off.
        while m_list[-1][1] == 0:
            m_list = copy(m_list)
            m_list.pop()
            # if there are no more manipulations left to do check the value
            if not m_list:
                matrix_sum = np.sum(matrix)
                if matrix_sum < self._current_minimum:
                    self.add_m_list(matrix_sum, output_m_list)
                return

        # if we wont have enough indices left, return
        if m_list[-1][1] > len(indices.intersection(m_list[-1][2])):
            return

        if len(m_list) == 1 or m_list[-1][1] > 1:
            if self.best_case(matrix, m_list, indices) > self._current_minimum:
                return

        index = self.get_next_index(matrix, m_list[-1], indices)

        m_list[-1][2].remove(index)

        # Make the matrix and new m_list where we do the manipulation to the
        # index that we just got
        matrix2 = np.copy(matrix)
        m_list2 = deepcopy(m_list)
        output_m_list2 = copy(output_m_list)

        matrix2[index, :] *= m_list[-1][0]
        matrix2[:, index] *= m_list[-1][0]
        output_m_list2.append([index, m_list[-1][3]])
        indices2 = copy(indices)
        indices2.remove(index)
        m_list2[-1][1] -= 1

        # recurse through both the modified and unmodified matrices

        self._recurse(matrix2, m_list2, indices2, output_m_list2)
        self._recurse(matrix, m_list, indices, output_m_list)

Response: This method recursively finds the minimal permutations of the current set of entries in the matrix and adds them to the output_m_list.


Instruction:
Implement a Python 3 function for
calculating the ensemble averaged Voronoi coordination numbers for a list of Structures.

Response:
def average_coordination_number(structures, freq=10):
    """
    Calculates the ensemble averaged Voronoi coordination numbers
    of a list of Structures using VoronoiNN.
    Typically used for analyzing the output of a Molecular Dynamics run.
    Args:
        structures (list): list of Structures.
        freq (int): sampling frequency of coordination number [every freq steps].
    Returns:
        Dictionary of elements as keys and average coordination numbers as values.
    """
    coordination_numbers = {}
    for spec in structures[0].composition.as_dict().keys():
        coordination_numbers[spec] = 0.0
    count = 0
    for t in range(len(structures)):
        if t % freq != 0:
            continue
        count += 1
        vnn = VoronoiNN()
        for atom in range(len(structures[0])):
            cn = vnn.get_cn(structures[t], atom, use_weights=True)
            coordination_numbers[structures[t][atom].species_string] += cn
    elements = structures[0].composition.as_dict()
    for el in coordination_numbers:
        coordination_numbers[el] = coordination_numbers[el] / elements[
            el] / count
    return coordination_numbers


Instruction:
Can you generate the documentation for the following Python 3 function
def solid_angle(center, coords):
    o = np.array(center)
    r = [np.array(c) - o for c in coords]
    r.append(r[0])
    n = [np.cross(r[i + 1], r[i]) for i in range(len(r) - 1)]
    n.append(np.cross(r[1], r[0]))
    vals = []
    for i in range(len(n) - 1):
        v = -np.dot(n[i], n[i + 1]) \
            / (np.linalg.norm(n[i]) * np.linalg.norm(n[i + 1]))
        vals.append(acos(abs_cap(v)))
    phi = sum(vals)
    return phi + (3 - len(r)) * pi

Response: Calculates the solid angle of a set of coords from the center.


Instruction:
How would you explain what the following Python 3 function does
def get_max_bond_lengths(structure, el_radius_updates=None):
    #jmc = JMolCoordFinder(el_radius_updates)
    jmnn = JmolNN(el_radius_updates=el_radius_updates)

    bonds_lens = {}
    els = sorted(structure.composition.elements, key=lambda x: x.Z)

    for i1 in range(len(els)):
        for i2 in range(len(els) - i1):
            bonds_lens[els[i1], els[i1 + i2]] = jmnn.get_max_bond_distance(
                els[i1].symbol, els[i1 + i2].symbol)

    return bonds_lens

Response:
Returns the maximum bond length estimates for a structure based on JMol
    table and algorithms.


Instruction:
How would you explain what the following Python 3 function does
def contains_peroxide(structure, relative_cutoff=1.1):
    ox_type = oxide_type(structure, relative_cutoff)
    if ox_type == "peroxide":
        return True
    else:
        return False

Response: Determines if a structure contains a peroxide anion.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def oxide_type(structure, relative_cutoff=1.1, return_nbonds=False):

    ox_obj = OxideType(structure, relative_cutoff)
    if return_nbonds:
        return ox_obj.oxide_type, ox_obj.nbonds
    else:
        return ox_obj.oxide_type

Response: Determines if an oxide is a peroxide superoxide or ozonide or normal oxide.