Instruction:
Here you have a function in Python 3, explain what it does
def decode(self, covertext):

        if not isinstance(covertext, str):
            raise InvalidInputException('Input must be of type string.')

        insufficient = (len(covertext) < self._fixed_slice)
        if insufficient:
            raise DecodeFailureError(
                "Covertext is shorter than self._fixed_slice, can't decode.")

        maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0))

        rank_payload = self._dfa.rank(covertext[:self._fixed_slice])
        X = fte.bit_ops.long_to_bytes(rank_payload)

        X = string.rjust(X, maximumBytesToRank, '\x00')
        msg_len_header = self._encrypter.decryptOneBlock(
            X[:DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT])
        msg_len_header = msg_len_header[8:16]
        msg_len = fte.bit_ops.bytes_to_long(
            msg_len_header[:DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT])

        retval = X[16:16 + msg_len]
        retval += covertext[self._fixed_slice:]
        ctxt_len = self._encrypter.getCiphertextLen(retval)
        remaining_buffer = retval[ctxt_len:]
        retval = retval[:ctxt_len]
        retval = self._encrypter.decrypt(retval)

        return retval, remaining_buffer

Response: Given an input string X returns an unranked version of X.


Instruction:
How would you explain what the following Python 3 function does
def define_symbol(name, open_brace, comma, i, j,
                  close_brace, variables, **kwds):
    r"""Define a nice symbol with matrix indices.

    >>> name = "rho"
    >>> from sympy import symbols
    >>> t, x, y, z = symbols("t, x, y, z", positive=True)
    >>> variables = [t, x, y, z]
    >>> open_brace = ""
    >>> comma = ""
    >>> close_brace = ""
    >>> i = 0
    >>> j = 1
    >>> f = define_symbol(name, open_brace, comma, i, j, close_brace,
    ...                   variables, positive=True)
    >>> print f
    rho12(t, x, y, z)

    """
    if variables is None:
        return Symbol(name+open_brace+str(i+1)+comma+str(j+1) +
                      close_brace, **kwds)
    else:
        return Function(name+open_brace+str(i+1)+comma+str(j+1) +
                        close_brace, **kwds)(*variables)

Response: r Define a nice symbol with matrix indices.


Instruction:
Make a summary of the following Python 3 code
def polarization_vector(phi, theta, alpha, beta, p,
                        numeric=False, abstract=False):
    """This function returns a unitary vector describing the polarization
    of plane waves.:

    INPUT:

    -  ``phi`` - The spherical coordinates azimuthal angle of the wave vector\
 k.
    -  ``theta`` - The spherical coordinates polar angle of the wave vector k.
    -  ``alpha`` - The rotation of a half-wave plate.
    -  ``beta`` - The rotation of a quarter-wave plate.
    -  ``p`` - either 1 or -1 to indicate whether to return epsilon^(+) or\
 epsilon^(-) respectively.

    If alpha and beta are zero, the result will be linearly polarized light
    along some fast axis. alpha and beta are measured from that fast axis.

    Propagation towards y, linear polarization (for pi transitions):

    >>> from sympy import pi
    >>> polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta= 0,p=1)
    Matrix([
    [0],
    [0],
    [1]])

    Propagation towards +z, circular polarization (for sigma + transitions):

    >>> polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p=1)
    Matrix([
    [  -sqrt(2)/2],
    [-sqrt(2)*I/2],
    [           0]])

    Propagation towards -z, circular polarization for sigma + transitions:

    >>> polarization_vector(phi=0, theta=pi, alpha=   0, beta=-pi/8,p=1)
    Matrix([
    [  -sqrt(2)/2],
    [-sqrt(2)*I/2],
    [           0]])

    Components + and - are complex conjugates of each other

    >>> from sympy import symbols
    >>> phi, theta, alpha, beta = symbols("phi theta alpha beta", real=True)
    >>> ep = polarization_vector(phi,theta,alpha,beta, 1)
    >>> em = polarization_vector(phi,theta,alpha,beta,-1)
    >>> ep-em.conjugate()
    Matrix([
    [0],
    [0],
    [0]])

    We can also define abstract polarization vectors without explicit \
    components

    >>> polarization_vector(0, 0, 0, 0, 1, abstract=True)
    epsilonp
    >>> polarization_vector(0, 0, 0, 0, -1, abstract=True)
    epsilonm

    """
    if abstract:
        Nl = symbols("N_l", integer=True)
        if p == 1:
            epsilon = Vector3D(IndexedBase("epsilonp", shape=(Nl,)))
        else:
            epsilon = Vector3D(IndexedBase("epsilonm", shape=(Nl,)))
        return epsilon

    epsilon = Matrix([cos(2*beta), p*I*sin(2*beta), 0])

    R1 = Matrix([[cos(2*alpha), -sin(2*alpha), 0],
                [sin(2*alpha), cos(2*alpha), 0],
                [0, 0, 1]])

    R2 = Matrix([[cos(theta), 0, sin(theta)],
                 [0, 1, 0],
                 [-sin(theta), 0, cos(theta)]])

    R3 = Matrix([[cos(phi), -sin(phi), 0],
                 [sin(phi), cos(phi), 0],
                 [0, 0, 1]])

    epsilon = R3*R2*R1*epsilon
    if numeric:
        epsilon = nparray([complex(epsilon[i]) for i in range(3)])
    return epsilon

Response: This function returns a unitary vector describing the polarization of a single - plane wave.


Instruction:
Here you have a function in Python 3, explain what it does
def cartesian_to_helicity(vector, numeric=False):
    if numeric:
        vector = list(vector)
        vector[0] = nparray(vector[0])
        vector[1] = nparray(vector[1])
        vector[2] = nparray(vector[2])

        v = [(vector[0]-1j*vector[1])/npsqrt(2),
             vector[2],
             -(vector[0]+1j*vector[1])/npsqrt(2)]
        v = nparray(v)
    else:
        v = [(vector[0]-I*vector[1])/sqrt(2),
             vector[2],
             -(vector[0]+I*vector[1])/sqrt(2)]

    if type(vector[0]) in [type(Matrix([1, 0])), type(nparray([1, 0]))]:
        return v
    else:
        return Matrix(v)

Response: r This function takes a cartesian basis and converts it to the helicity basis.


Instruction:
Given the following Python 3 function, write the documentation
def vector_element(r, i, j):
    return Matrix([r[p][i, j] for p in range(3)])

Response: r Extract an matrix element of a vector operator.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ketbra(i, j, Ne):
    return ket(i, Ne)*bra(j, Ne)

Response:
This function returns the outer product of a canonical basis of an \
 Ne - dimensional Hilbert space.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def lindblad_operator(A, rho):
    a, b = sigma_operator_indices(A)
    # print(111, a, b)
    if a is not None and b is not None:
        Ne = A.shape[0]
        L = zeros(Ne, Ne)
        L[a, a] += rho[b, b]

        for j in range(Ne):
            L[b, j] += -rho[b, j]/2

        for i in range(Ne):
            L[i, b] += -rho[i, b]/2

        return L
    else:
        return A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2

Response: r This function returns the action of a Lindblad operator A on a density matrix rho.


Instruction:
Write a Python 3 script for
returning the Lindblad terms for decays gamma in matrix form.

Response:
def lindblad_terms(gamma, rho, Ne, verbose=1):
    u"""Return the Lindblad terms for decays gamma in matrix form.

    >>> from sympy import pprint
    >>> aux = define_frequencies(4, explicitly_antisymmetric=True)
    >>> omega_level, omega, gamma = aux
    >>> gamma = gamma.subs({gamma[2, 0]:0, gamma[3, 0]:0, gamma[3, 1]:0})
    >>> pprint(gamma, use_unicode=True)
    ⎡ 0   -γ₂₁   0     0  ⎤
    ⎢                     ⎥
    ⎢γ₂₁   0    -γ₃₂   0  ⎥
    ⎢                     ⎥
    ⎢ 0   γ₃₂    0    -γ₄₃⎥
    ⎢                     ⎥
    ⎣ 0    0    γ₄₃    0  ⎦
    >>> rho = define_density_matrix(4)
    >>> pprint(lindblad_terms(gamma, rho, 4), use_unicode=True)
    ⎡                -γ₂₁⋅ρ₁₂             -γ₃₂⋅ρ₁₃             -γ₄₃⋅ρ₁₄      ⎤
    ⎢ γ₂₁⋅ρ₂₂        ─────────            ─────────            ─────────     ⎥
    ⎢                    2                    2                    2         ⎥
    ⎢                                                                        ⎥
    ⎢-γ₂₁⋅ρ₂₁                          γ₂₁⋅ρ₂₃   γ₃₂⋅ρ₂₃    γ₂₁⋅ρ₂₄   γ₄₃⋅ρ₂₄⎥
    ⎢─────────  -γ₂₁⋅ρ₂₂ + γ₃₂⋅ρ₃₃   - ─────── - ───────  - ─────── - ───────⎥
    ⎢    2                                2         2          2         2   ⎥
    ⎢                                                                        ⎥
    ⎢-γ₃₂⋅ρ₃₁     γ₂₁⋅ρ₃₂   γ₃₂⋅ρ₃₂                         γ₃₂⋅ρ₃₄   γ₄₃⋅ρ₃₄⎥
    ⎢─────────  - ─────── - ───────  -γ₃₂⋅ρ₃₃ + γ₄₃⋅ρ₄₄   - ─────── - ───────⎥
    ⎢    2           2         2                               2         2   ⎥
    ⎢                                                                        ⎥
    ⎢-γ₄₃⋅ρ₄₁     γ₂₁⋅ρ₄₂   γ₄₃⋅ρ₄₂    γ₃₂⋅ρ₄₃   γ₄₃⋅ρ₄₃                     ⎥
    ⎢─────────  - ─────── - ───────  - ─────── - ───────       -γ₄₃⋅ρ₄₄      ⎥
    ⎣    2           2         2          2         2                        ⎦

    Notice that there are more terms than simply adding a decay
    gamma_ij*rho_ij/2 for each coherence.

    """
    # We count the necessary Lindblad operators.
    Nterms = 0
    for i in range(Ne):
        for j in range(i):
            if gamma[i, j] != 0:
                Nterms += 1

    L = zeros(Ne)
    counter = 0
    t0 = time()
    for i in range(Ne):
        for j in range(i):
            if gamma[i, j] != 0:
                counter += 1
                sig = ket(j+1, Ne)*bra(i+1, Ne)
                L += gamma[i, j]*lindblad_operator(sig, rho)
                tn = time()
                if tn-t0 > 1:
                    aux = "Calculated up to i={}, j={}, or {}/{} = {:2.2f} %."
                    if verbose > 0:
                        print(aux.format(i, j, counter, Nterms,
                                         float(counter+1)/Nterms*100))
                    t0 = tn
    return L


Instruction:
Can you tell what is the following Python 3 function doing
def phase_transformation(Ne, Nl, r, Lij, omega_laser, phase):
    ph = find_phase_transformation(Ne, Nl, r, Lij)

    return {phase[i]: sum([ph[i][j]*omega_laser[j] for j in range(Nl)])
            for i in range(Ne)}

Response: r Return a phase transformation to eliminate explicit time dependence.


Instruction:
Explain what the following Python 3 code does
def hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, omega_laser, xi,
                RWA=True, RF=True):
    r"""Return symbolic Hamiltonian.

    >>> from sympy import zeros, pi, pprint, symbols
    >>> Ne = 3
    >>> Nl = 2
    >>> Ep, omega_laser = define_laser_variables(Nl)
    >>> epsilonp = [polarization_vector(0, -pi/2, 0, 0, 1) for l in range(Nl)]
    >>> detuning_knob = symbols("delta1 delta2", real=True)

    >>> xi = [zeros(Ne, Ne) for l in range(Nl)]
    >>> coup = [[(1, 0)], [(2, 0)]]
    >>> for l in range(Nl):
    ...     for pair in coup[l]:
    ...         xi[l][pair[0], pair[1]] = 1
    ...         xi[l][pair[1], pair[0]] = 1

    >>> rm = define_r_components(Ne, xi, explicitly_hermitian=True,
    ...                          helicity=True, p=-1)

    >>> rm = helicity_to_cartesian(rm)
    >>> omega_level, omega, gamma = define_frequencies(Ne, True)

    >>> H = hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level,
    ...                 omega_laser, xi, RWA=True, RF=False)

    >>> print H[1, 0]
    -E_{01}*e*r_{0;21}*exp(-I*t*varpi_1)/2
    >>> print H[2, 0]
    -E_{02}*e*r_{0;31}*exp(-I*t*varpi_2)/2
    >>> print H[2, 2]
    hbar*omega_3

    """
    # We check what RF is.
    if type(RF) == list:
        theta = RF[:]
        RF = True
    elif type(RF) == Matrix:
        theta = [RF[i, 0] for i in range(RF.shape[0])]
        RF = True
    elif RF:
        # theta should be calculate here!
        s = "We are still missing automatic calculation of phase "
        s += "transformations."
        raise ValueError(s)

    if not RWA and RF:
        s = "The rotating frame does not exist without the rotating wave \
approximation, as far as I know."
        raise ValueError(s)

    # We check that the epsilonp is a list of vectors.
    if not isinstance(epsilonp, list):
        raise ValueError("epsilonp must be a list of polarization vectors.")
    if not isinstance(epsilonp[0], Matrix):
        raise ValueError("epsilonp must be a list of polarization vectors.")

    Ne = len(omega_level)
    Nl = len(omega_laser)

    H = zeros(Ne, Ne)
    hbar, e = symbols("hbar e", positive=True)
    t = symbols("t", real=True)

    for i in range(Ne):
        for j in range(Ne):
            rmij = vector_element(rm, i, j)
            rpij = vector_element(rm, j, i).conjugate()
            for l in range(Nl):
                epsilonpl = epsilonp[l]
                epsilonml = epsilonpl.conjugate()

                if RF:
                    Epl = xi[l][i, j]*Ep[l]
                    Epl *= exp(-I*(theta[j]-theta[i]-t*omega_laser[l]))
                    Eml = xi[l][i, j]*Ep[l].conjugate()
                    Eml *= exp(-I*(theta[j]-theta[i]+t*omega_laser[l]))
                else:
                    Epl = Ep[l]*xi[l][i, j]*exp(-I*omega_laser[l]*t)
                    Eml = Epl.conjugate()

                # The E^(+)r^(-) term
                H[i, j] += -e*Epl/2*cartesian_dot_product(epsilonpl, rmij)
                # The E^(-)r^(+) term
                H[i, j] += -e*Eml/2*cartesian_dot_product(epsilonml, rpij)
                if not RWA:
                    # The E^(+)r^(+) term
                    H[i, j] += -e*Epl/2*cartesian_dot_product(epsilonpl, rpij)
                    # The E^(-)r^(-) term
                    H[i, j] += -e*Eml/2*cartesian_dot_product(epsilonml, rmij)

            if i == j:
                if RF:
                    H[i, j] += hbar*(omega_level[i]+diff(theta[i], t))
                else:
                    H[i, j] += hbar*omega_level[i]

    return H

Response: r Return symbolic Hamiltonian.


Instruction:
How would you explain what the following Python 3 function does
def cross(a, b):
    if isinstance(a, Mul):
        a = a.expand()
        avect = 1
        aivect = -1
        for ai, fact in enumerate(a.args):
            if isinstance(fact, Vector3D):
                avect = fact
                aivect = ai
                break

        acoef = a.args[:aivect] + a.args[aivect+1:]
        acoef = Mul(*acoef)
        return acoef*cross(avect, b)

    if isinstance(b, Mul):
        b = b.expand()
        bvect = 1
        bivect = -1
        for bi, fact in enumerate(b.args):
            if isinstance(fact, Vector3D):
                bvect = fact
                bivect = bi
                break

        bcoef = b.args[:bivect] + b.args[bivect+1:]
        bcoef = Mul(*bcoef)
        return bcoef*cross(a, bvect)

    if isinstance(a, Vector3D) and isinstance(b, Vector3D):
        return CrossProduct(a, b)

Response: r Cross product of two 3d vectors.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_settings(settings):
    '''
    Saves user's settings
    @returns True on success
    @returns False on failure
    '''
    if not os.access(DATA_DIR, os.W_OK): return False
    try:
        f = open(DATA_DIR + os.sep + SETTINGS_FILE, 'w')
        f.writelines(json.dumps(settings, indent=0))
        f.close()
        os.chmod(os.path.abspath(DATA_DIR + os.sep + SETTINGS_FILE), 0o777) # to avoid (or create?) IO problems with multiple users
    except IOError:
        return False
    else:
        return True

Response: Saves user s settings to a file in the user s data directory.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_field_unique_by_group(df, field_col, group_col):
    ''' Determine if field is constant by group in df
    '''
    def num_unique(x):
        return len(pd.unique(x))
    num_distinct = df.groupby(group_col)[field_col].agg(num_unique)
    return all(num_distinct == 1)

Response: Determine if a field is constant by group in df


Instruction:
How would you explain what the following Python 3 function does
def _list_files_in_path(path, pattern="*.stan"):

    results = []
    for dirname, subdirs, files in os.walk(path):
        for name in files:
            if fnmatch(name, pattern):
                results.append(os.path.join(dirname, name))
    return(results)

Response: List files in a directory of stan


Instruction:
Can you tell what is the following Python 3 function doing
def generate_random_perovskite(lat=None):
    '''
    This generates a random valid perovskite structure in ASE format.
    Useful for testing.
    Binary and organic perovskites are not considered.
    '''
    if not lat:
        lat = round(random.uniform(3.5, Perovskite_tilting.OCTAHEDRON_BOND_LENGTH_LIMIT*2), 3)
    A_site = random.choice(Perovskite_Structure.A)
    B_site = random.choice(Perovskite_Structure.B)
    Ci_site = random.choice(Perovskite_Structure.C)
    Cii_site = random.choice(Perovskite_Structure.C)

    while covalent_radii[chemical_symbols.index(A_site)] - \
        covalent_radii[chemical_symbols.index(B_site)] < 0.05 or \
        covalent_radii[chemical_symbols.index(A_site)] - \
        covalent_radii[chemical_symbols.index(B_site)] > 0.5:

        A_site = random.choice(Perovskite_Structure.A)
        B_site = random.choice(Perovskite_Structure.B)

    return crystal(
        [A_site, B_site, Ci_site, Cii_site],
        [(0.5, 0.25, 0.0), (0.0, 0.0, 0.0), (0.0, 0.25, 0.0), (0.25, 0.0, 0.75)],
        spacegroup=62, cellpar=[lat*math.sqrt(2), 2*lat, lat*math.sqrt(2), 90, 90, 90]
    )

Response: Generates a random valid perovskite structure in ASE format.


Instruction:
Can you write a function in Python 3 where it
checks a value is a positive integer. Returns the value if so raises ValueError otherwise.

Response:
def check_positive_integer(name, value):
    """Check a value is a positive integer.

    Returns the value if so, raises ValueError otherwise.

    """
    try:
        value = int(value)
        is_positive = (value > 0)
    except ValueError:
        raise ValueError('%s should be an integer; got %r' % (name, value))

    if is_positive:
        return value
    else:
        raise ValueError('%s should be positive; got %r' % (name, value))


Instruction:
Can you write a function in Python 3 where it
checks a value is a valid colour input.

Response:
def check_color_input(value):
    """Check a value is a valid colour input.

    Returns a parsed `RGBColor` instance if so, raises ValueError
    otherwise.

    """
    value = value.lower()
    # Trim a leading hash
    if value.startswith('#'):
        value = value[1:]

    if len(value) != 6:
        raise ValueError(
            'Color should be six hexadecimal digits, got %r (%s)' %
            (value, len(value)))

    if re.sub(r'[a-f0-9]', '', value):
        raise ValueError(
            'Color should only contain hex characters, got %r' % value)

    red = int(value[0:2], base=16)
    green = int(value[2:4], base=16)
    blue = int(value[4:6], base=16)
    return RGBColor(red, green, blue)


Instruction:
Can you create a Python 3 function that
extracts octahedra as lists of sequence numbers of corner atoms.

Response:
def get_octahedra(self, atoms, periodicity=3):
        '''
        Extract octahedra as lists of sequence numbers of corner atoms
        '''
        octahedra = []
        for n, i in enumerate(atoms):
            found = []
            if i.symbol in Perovskite_Structure.B:
                for m, j in enumerate(self.virtual_atoms):
                    if j.symbol in Perovskite_Structure.C and self.virtual_atoms.get_distance(n, m) <= self.OCTAHEDRON_BOND_LENGTH_LIMIT:
                        found.append(m)

            if (periodicity == 3 and len(found) == 6) or (periodicity == 2 and len(found) in [5, 6]):
                octahedra.append([n, found])

        if not len(octahedra): raise ModuleError("Cannot extract valid octahedra: not enough corner atoms found!")
        return octahedra


Instruction:
Here you have a function in Python 3, explain what it does
def get_tiltplane(self, sequence):
        '''
        Extract the main tilting plane basing on Z coordinate
        '''
        sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z)
        in_plane = []
        for i in range(0, len(sequence)-4):
            if abs(self.virtual_atoms[ sequence[i] ].z - self.virtual_atoms[ sequence[i+1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ sequence[i+1] ].z - self.virtual_atoms[ sequence[i+2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ sequence[i+2] ].z - self.virtual_atoms[ sequence[i+3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE:
                in_plane = [sequence[j] for j in range(i, i+4)]
        return in_plane

Response: Extract the main tilting plane based on Z coordinate


Instruction:
Given the following Python 3 function, write the documentation
def get_tiltplanes(self, sequence):
        '''
        Extract tilting planes basing on distance map
        '''
        tilting_planes = []
        distance_map = []

        for i in range(1, len(sequence)):
            distance_map.append([ sequence[i], self.virtual_atoms.get_distance( sequence[0], sequence[i] ) ])

        distance_map = sorted(distance_map, key=lambda x: x[1])

        if len(distance_map) == 4:
            # surface edge case
            # semi-octahedron at surface edge has only one tilting plane to consider
            sorted_dist = [i[0] for i in distance_map]
            if distance_map[-1][1] - distance_map[-2][1] < 0.5:
                # 1st case: max diff < 0.5 Angstrom,
                # meaning all distances to reference atom are similar,
                # therefore the reference atom is above the searched plane
                # and the searched plane consists of other atoms
                tilting_planes.append( [ i[0] for i in distance_map ] )
            else:
                # 2nd case: reference atom belongs to the searched plane,
                # procedure needs to be repeated with the next atom as reference atom
                candidates = [sequence[0], sorted_dist[-1]]
                next_distance_map = []
                next_distance_map.append([ sorted_dist[1], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[1] ) ])
                next_distance_map.append([ sorted_dist[2], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[2] ) ])
                next_distance_map = sorted(next_distance_map, key=lambda x: x[1])
                next_sorted_dist = [i[0] for i in next_distance_map]

                # the next reference atom is taken above the plane (distances are similar)
                if next_distance_map[1][1] - next_distance_map[0][1] < 0.5: candidates.extend([ next_sorted_dist[0], next_sorted_dist[1] ])

                # the next reference atom is taken in the plane (distances are different)
                else: candidates.extend([ sorted_dist[0], next_sorted_dist[1] ])
                tilting_planes.append(candidates)

        elif len(distance_map) == 5:
            # full octahedron case
            # full octahedron has 3 different tilting planes (perpendicular in ideal case)
            sorted_dist = [i[0] for i in distance_map]

            # 1st plane is found as:
            first_plane = sorted_dist[0:4]
            tilting_planes.append(first_plane)
            distance_map_first_plane = []
            for i in range(1, 4):
                distance_map_first_plane.append([ first_plane[i], self.virtual_atoms.get_distance( first_plane[0], first_plane[i] ) ])
            distance_map_first_plane = sorted(distance_map_first_plane, key=lambda x: x[1])
            sorted_first_plane = [i[0] for i in distance_map_first_plane]

            # 2nd and 3rd planes are found as:
            tilting_planes.append([ sequence[0], sorted_dist[4], first_plane[0], sorted_first_plane[2] ])
            tilting_planes.append([ sequence[0], sorted_dist[4], sorted_first_plane[0], sorted_first_plane[1] ])

        # filter planes by Z according to octahedral spatial compound
        filtered = list(filter(lambda x:
            abs(self.virtual_atoms[ x[0] ].z - self.virtual_atoms[ x[1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ x[1] ].z - self.virtual_atoms[ x[2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ x[2] ].z - self.virtual_atoms[ x[3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE,
            tilting_planes
        )) # Py3
        if len(filtered): tilting_planes = filtered

        return tilting_planes

Response: Extract tilting planes based on distance map


Instruction:
Write a Python 3 script for
returning dict of help_context keys.

Response:
def get_help_keys(self):
        """
        Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method).
        """
        help_keys = {}
        for k, v in self.help_context.items():
            if isinstance(v, tuple):
                help_keys[k] = v[0]
            else:
                help_keys[k] = v
        return help_keys


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_help_values(self):
        help_values = {}
        for k, v in self.help_context.items():
            if isinstance(v, tuple) and len(v) == 2:
                help_values[k] = v[1]
            else:
                help_values[k] = u"<%s>" % k
        return help_values

Response: Returns dict of help_context values.


Instruction:
Write a Python 3 script to
register an email template file path.

Response:
def register(self, path, help_text=None, help_context=None):
        """
        Registers email template.

        Example usage:
            email_templates.register('hello_template.html', help_text=u'Hello template',
                help_context={'username': u'Name of user in hello expression'})

        :param path: Template file path. It will become immutable registry lookup key.
        :param help_text: Help text to describe template in admin site
        :param help_context: Dictionary of possible keys used in the context and description of their content

        `help_context` items values may be strings or tuples of two strings. If strings, then email template preview
        will use variable names to fill context, otherwise the second tuple element will become example value.

        If an email template is already registered, this will raise AlreadyRegistered.
        """
        if path in self._registry:
            raise AlreadyRegistered('The template %s is already registered' % path)
        self._registry[path] = RegistrationItem(path, help_text, help_context)
        logger.debug("Registered email template %s", path)


Instruction:
How would you code a function in Python 3 to
return the registration item for the specified path.

Response:
def get_registration(self, path):
        """
        Returns registration item for specified path.

        If an email template is not registered, this will raise NotRegistered.
        """
        if not self.is_registered(path):
            raise NotRegistered("Email template not registered")
        return self._registry[path]


Instruction:
Can you generate the documentation for the following Python 3 function
def get_form_help_text(self, path):
        try:
            form_help_text = self.get_registration(path).as_form_help_text()
        except NotRegistered:
            form_help_text = u""
        return form_help_text

Response: Returns the form help text for creating email templates.


Instruction:
How would you code a function in Python 3 to
analyze the parsed results from Flake8 or PEP 8 output and creates HTML file result instances.

Response:
def analyze(self, output_file=None):
        """
        Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResult instances
        :param output_file: If specified, output will be written to this file instead of stdout.
        """

        fr = None
        for path, code, line, char, desc in self.parser.parse():

            # Create a new FileResult and register it if we have changed to a new file
            if path not in self.files:
                # Update statistics
                if fr:
                    self.update_stats(fr)
                fr = FileResult(path)
                self.files[path] = fr

            # Add line to the FileResult
            fr.add_error(code, line, char, desc)

        # Add final FileResult to statistics, if any were parsed
        if fr:
            self.update_stats(fr)

        # Generate HTML file
        self.generate(output_file=output_file)


Instruction:
Can you tell what is the following Python 3 function doing
def generate(self, output_file=None):

        fd = output_file

        # Write to stdout if we do not have a file to write to
        if not fd:
            fd = stdout
        else:
            try:
                fd = open(output_file, 'w')
            except IOError as e:
                stderr.write('Unable to open outputfile %s: %s' % (output_file, e))

        with open(os.path.join(os.path.dirname(__file__), 'templates/base.html')) as template:
            html = Template(template.read())

            # Write potential build messages to stdout if we are writing to HTML file
            # If dest is stdout and supposed to be piped or redirected, build messages like TeamCity's will
            # have no effect, since they require to read from stdin.
            if output_file:
                self.report_build_messages()

            # Write our rendered template to the file descriptor
            fd.write(
                html.render(
                    files=sorted(self.files.values(), key=lambda x: x.path),
                    total_warnings=self.total_warnings,
                    total_errors=self.total_errors,
                    total_other=self.total_other,
                    violations=sorted(
                        ((code, count) for code, count in self.violations.items()),
                        key=lambda x: x[1],
                        reverse=True,
                    )
                )
            )

            # If file descriptor is stdout
            if not output_file:
                fd.flush()
            else:
                fd.close()

Response: Generates an HTML file based on the data from the Parser object and Jinja2 templates.


Instruction:
Create a Python 3 function for
reading the data from a FileResult and updates the overall statistics with the sum of the error and warning counts.

Response:
def update_stats(self, file_result):
        """
        Reads the data from a FileResult and updates overall statistics
        :param file_result: A FileResult instance
        """

        for code, count in file_result.violations.items():
            if code not in self.violations:
                self.violations[code] = 0
            self.violations[code] += file_result.violations[code]

            if 'E' in code.upper():
                self.total_errors += file_result.violations[code]
            elif 'W' in code.upper():
                self.total_warnings += file_result.violations[code]
            else:
                self.total_other += file_result.violations[code]


Instruction:
Implement a function in Python 3 to
report the build messages for a specific build agent.

Response:
def report_build_messages(self):
        """
        Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity
        and performs the adequate actions to report statistics.

        Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout.
        Currently only supports TeamCity.

        :return: A list of build message strings destined for stdout
        """

        if os.getenv('TEAMCITY_VERSION'):
            tc_build_message_warning = "##teamcity[buildStatisticValue key='pepper8warnings' value='{}']\n"
            tc_build_message_error = "##teamcity[buildStatisticValue key='pepper8errors' value='{}']\n"

            stdout.write(tc_build_message_warning.format(self.total_warnings))
            stdout.write(tc_build_message_error.format(self.total_errors))
            stdout.flush()


Instruction:
Can you generate the documentation for the following Python 3 function
def phase_transformation(Ne, Nl, rm, xi, return_equations=False):
    # We first define the needed variables
    E0, omega_laser = define_laser_variables(Nl)
    theta = [Symbol('theta'+str(i+1)) for i in range(Ne)]

    # We check for the case of xi being a list of matrices.
    if type(xi) == list:
        xi = np.array([[[xi[l][i, j]
                       for j in range(Ne)] for i in range(Ne)]
                       for l in range(Nl)])

    # We find all the equations that the specified problem has to fulfil.
    eqs = []
    for i in range(Ne):
        for j in range(0, i):
            if (rm[0][i, j] != 0) or \
               (rm[1][i, j] != 0) or \
               (rm[2][i, j] != 0):
                for l in range(Nl):
                    if xi[l, i, j] == 1:
                        eqs += [-omega_laser[l] + theta[j] - theta[i]]

    if return_equations:
        return eqs

    # We solve the system of equations.
    sol = sympy.solve(eqs, theta, dict=True)
    sol = sol[0]
    # We add any missing theta that may be left outside if the system is
    # under determined.

    extra_thetas = []
    for i in range(Ne):
        if theta[i] not in sol.keys():
            sol.update({theta[i]: theta[i]})
            extra_thetas += [theta[i]]

    # We make the solution such that theta1 + omega_level1 = 0.
    omega_level, omega, gamma = define_frequencies(Ne)
    eq_crit = sol[theta[0]] + omega_level[0]
    ss = sympy.solve(eq_crit, extra_thetas[0])[0]
    ss = {extra_thetas[0]: ss}

    sol_simple = [sol[theta[i]].subs(ss)
                  for i in range(Ne)]

    # sol = []
    # for i in range(Ne):
    #     soli = []
    #     for l in range(Nl):
    #         soli += [sympy.diff(sol_simple[theta[i]], omega_laser[l])]
    #     sol += [soli]

    return sol_simple

Response: This function returns a phase transformation theta_i.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def define_simplification(omega_level, xi, Nl):
    try:
        Ne = len(omega_level)
    except:
        Ne = omega_level.shape[0]
    #####################################
    # 1 We calculate the symplifying functions.
    om = omega_level[0]
    iu = 0; Neu = 1
    omega_levelu = [om]
    d = {}; di = {0: 0}
    for i in range(Ne):
        if omega_level[i] != om:
            iu += 1
            om = omega_level[i]
            Neu += 1
            omega_levelu += [om]
            di.update({iu: i})
        d.update({i: iu})

    def u(i):
        return d[i]

    def invu(iu):
        return di[iu]

    #####################################
    # 2 We build the simplified xi.
    Neu = len(omega_levelu)
    xiu = np.array([[[xi[l, invu(i), invu(j)]
                    for j in range(Neu)] for i in range(Neu)]
                    for l in range(Nl)])
    #####################################
    return u, invu, omega_levelu, Neu, xiu

Response: Return a simplifying function its inverse and simplified frequencies.


Instruction:
Given the following Python 3 function, write the documentation
def find_omega_min(omega_levelu, Neu, Nl, xiu):
    omega_min = []; iu0 = []; ju0 = []
    for l in range(Nl):
        omegasl = []
        for iu in range(Neu):
            for ju in range(iu):
                if xiu[l, iu, ju] == 1:
                    omegasl += [(omega_levelu[iu]-omega_levelu[ju], iu, ju)]
        omegasl = list(sorted(omegasl))
        omega_min += [omegasl[0][0]]
        iu0 += [omegasl[0][1]]
        ju0 += [omegasl[0][2]]

    return omega_min, iu0, ju0

Response: r Find the smallest transition frequency for each field.


Instruction:
Can you generate the documentation for the following Python 3 function
def detunings_indices(Neu, Nl, xiu):
    pairs = []
    for l in range(Nl):
        ind = []
        for iu in range(Neu):
            for ju in range(iu):
                if xiu[l, iu, ju] == 1:
                    ind += [(iu, ju)]
        pairs += [ind]
    return pairs

Response: r Get the indices of the transitions of all fields.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0):
    code_det = ""
    for l in range(Nl):
        for pair in pairs[l]:
            iu, ju = pair
            code_det += "    delta"+str(l+1)
            code_det += "_"+str(iu+1)
            code_det += "_"+str(ju+1)
            code_det += " = detuning_knob["+str(l)+"]"
            corr = -omega_levelu[iu]+omega_levelu[iu0[l]]
            corr = -omega_levelu[ju0[l]]+omega_levelu[ju] + corr

            if corr != 0:
                code_det += " + ("+str(corr)+")"
            code_det += "\n"
    return code_det

Response: r Get the code to calculate the simplified detunings.


Instruction:
Can you tell what is the following Python 3 function doing
def detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu,
                      omega_levelu, iu0, ju0):
    r"""Rewrite a symbolic expression in terms of allowed transition detunings.

    >>> Ne = 6
    >>> Nl = 2
    >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
    >>> xi = np.zeros((Nl, Ne, Ne))
    >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
    >>> for l in range(Nl):
    ...     for pair in coup[l]:
    ...         xi[l, pair[0], pair[1]] = 1.0
    ...         xi[l, pair[1], pair[0]] = 1.0

    >>> aux = define_simplification(omega_level, xi, Nl)
    >>> u, invu, omega_levelu, Neu, xiu = aux
    >>> omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu)
    >>> pairs = detunings_indices(Neu, Nl, xiu)
    >>> combs = detunings_combinations(pairs)
    >>> symb_omega_levelu, omega, gamma = define_frequencies(Neu)
    >>> E0, omega_laser = define_laser_variables(Nl)

    Most times it is possible to express these combinations of optical
    frequencies in terms of allowed transition detunings.

    >>> expr = +(omega_laser[0]-(symb_omega_levelu[1]-symb_omega_levelu[0]))
    >>> expr += -(omega_laser[1]-(symb_omega_levelu[3]-symb_omega_levelu[0]))
    >>> expr
    -omega_2 + omega_4 + varpi_1 - varpi_2
    >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu,
    ...                   omega_levelu, iu0, ju0)
    '+delta1_2_1-delta2_4_1'

    But some times it is not possible:

    >>> expr = +(omega_laser[1]-(symb_omega_levelu[1]-symb_omega_levelu[0]))
    >>> expr += -(omega_laser[0]-(symb_omega_levelu[3]-symb_omega_levelu[0]))
    >>> expr
    -omega_2 + omega_4 - varpi_1 + varpi_2
    >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu,
    ...                   omega_levelu, iu0, ju0)
    '300.000000000000-detuning_knob[0]+detuning_knob[1]'

    """
    Nl = len(omega_laser)
    Neu = len(symb_omega_levelu)
    # We find the coefficients a_i of the field frequencies.
    a = [diff(expr, omega_laser[l]) for l in range(Nl)]

    # We look for a combination of the detunings obtained with the
    # function detunings_code. For each combination we sum the
    # detunings weighed by a_i.
    success = False
    for comb in combs:
        expr_try = 0
        for l in range(Nl):
            expr_try += a[l]*(omega_laser[l] -
                              symb_omega_levelu[comb[l][0]] +
                              symb_omega_levelu[comb[l][1]])
        if expr-expr_try == 0:
            success = True
            break

    assign = ""
    if success:
        for l in range(Nl):
            if a[l] != 0:
                if a[l] == 1:
                    assign += "+"
                elif a[l] == -1:
                    assign += "-"
                assign += "delta"+str(l+1)
                assign += "_"+str(comb[l][0]+1)
                assign += "_"+str(comb[l][1]+1)
    else:
        # We get the code for Hii using detuning knobs.
        # We find out the remainder terms.
        _remainder = expr - sum([a[l]*omega_laser[l]
                                 for l in range(Nl)])
        # We find the coefficients of the remainder.
        b = [diff(_remainder, symb_omega_levelu[j]) for j in range(Neu)]
        # We calculate the remainder numerically.
        remainder = sum([b[j]*omega_levelu[j] for j in range(Neu)])
        # We add the contributions from the detuning knobs.
        remainder += sum([a[l]*(omega_levelu[iu0[l]] -
                                omega_levelu[ju0[l]])
                          for l in range(Nl)])
        assign = str(remainder)
        # We get the code for Hii using detuning knobs.
        for l in range(Nl):
            if a[l] != 0:
                if a[l] == 1:
                    assign += "+"
                elif a[l] == -1:
                    assign += "-"
                assign += "detuning_knob["+str(l)+"]"

    return assign

Response: r Rewrites a symbolic expression in terms of allowed transition detunings.


Instruction:
Given the following Python 3 function, write the documentation
def fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, xi, theta,
                     file_name=None):
    r"""Return a fast function that returns a Hamiltonian as an array.

    INPUT:

    -  ``Ep`` - A list with the electric field amplitudes (real or complex).
    -  ``epsilonp`` - A list of the polarization vectors of the fields \
    (real or complex).
    -  ``detuning_knob`` - A list of the detunings of each field (relative \
    to the transition of lowest energy).
    -  ``rm`` -     The below-diagonal components
        of the position operator in the cartesian basis:

        .. math::
            \vec{r}^{(-)}_{i j} = [ x_{ij}, y_{ij}, z_{ij} ]
            \hspace{1cm} \forall \hspace{1cm} 0 < j < i
    -  ``omega_level`` - The angular frequencies of each state.
    -  ``xi`` - An array whose ``xi[l, i, j]`` element is 1 if the \
     transition :math:`|i\rangle \rightarrow |j\rangle`\ is driven by field \
     ``l`` and 0 otherwise.
    -  ``theta`` - A list of symbolic expressions representing a phase \
    transformation.
    -  ``file_name`` - A string indicating a file to save the function's \
    code.

    If the arguments Ep, epsilonp, and detuning_knob are symbolic amounts, \
    the returned function will accept numeric values of Ep, epsilonp, and \
    detuning_knob as arguments.

    All quantities should be in SI units.

    EXAMPLES:
    We build an example using states coupled like this:

     --- |4>        --- |5>          --- |6>
      ^              ^                ^
      |              |                |
      |    --- |2>   |     --- |3>    |
    2 |     ^      2 |      ^         | 2
      |   1 |        |    1 |         |
      |     |        |      |         |
    ------------------------------------- |1>

    With the numbers on kets labeling states and the plain numbers labeling
    fields.

    The number of states and fields:
    >>> Ne = 6
    >>> Nl = 2

    We invent some energy levels:
    >>> omega_level = np.array([0.0, 100.0, 100.0, 200.0, 200.0, 300.0])
    >>> omega_level = omega_level*1e6*2*np.pi

    We build the symbol xi, that chooses which laser couples which
    transition.
    >>> xi = np.zeros((Nl, Ne, Ne))
    >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
    >>> for l in range(Nl):
    ...     for pair in coup[l]:
    ...         xi[l, pair[0], pair[1]] = 1.0
    ...         xi[l, pair[1], pair[0]] = 1.0

    We invent some electric dipole matrix elements:
    >>> from scipy.constants import physical_constants
    >>> a0 = physical_constants["Bohr radius"][0]
    >>> rm = np.zeros((3, Ne, Ne))
    >>> for l in range(Nl):
    ...     for i in range(Ne):
    ...         for j in range(i):
    ...             if xi[l, i, j] != 0:
    ...                 rm[2, i, j] = float(i)*a0

    The phase transformation:
    >>> theta = phase_transformation(Ne, Nl, rm, xi)

    We define the possible arguments:
    >>> from sympy import symbols, pi
    >>> from fast.symbolic import polarization_vector
    >>> detuning_knob = symbols("delta1 delta2")
    >>> detuning_knob_vals = np.array([-1.0, 3.0])*1e6*2*np.pi

    >>> Ep, omega_laser = define_laser_variables(Nl)
    >>> Ep_vals = [1e2, 1e2]

    >>> alpha = symbols("alpha")
    >>> epsilon = polarization_vector(0, pi/2, alpha, 0, 1)
    >>> epsilonp = [epsilon, epsilon]
    >>> epsilonp_vals = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]

    There are 8 ways to call fast_hamiltonian:

    1 .- Get a function of detunings, field amplitudes, polarizations:
    >>> H1 = fast_hamiltonian(Ep, epsilonp, detuning_knob, rm,
    ...                       omega_level, xi, theta)

    2 .- Get a function of field amplitudes, polarizations:
    >>> H2 = fast_hamiltonian(Ep, epsilonp, detuning_knob_vals, rm,
    ...                       omega_level, xi, theta)

    3 .- Get a function of detunings, polarizations:
    >>> H3 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob, rm,
    ...                       omega_level, xi, theta)

    4 .- Get a function of detunings, field amplitudes:
    >>> H4 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob, rm,
    ...                       omega_level, xi, theta)

    5 .- Get a function of detunings:
    >>> H5 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob, rm,
    ...                       omega_level, xi, theta)

    6 .- Get a function of field amplitudes:
    >>> H6 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob_vals, rm,
    ...                       omega_level, xi, theta)

    7 .- Get a function of polarizations:
    >>> H7 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob_vals, rm,
    ...                       omega_level, xi, theta)

    8 .- Get a function of nothing:
    >>> H8 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob_vals, rm,
    ...                       omega_level, xi, theta)

    We test all of these combinations.
    >>> print(H1(Ep_vals, epsilonp_vals, detuning_knob_vals) \
    ...     /hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    >>> print(H2(Ep_vals, epsilonp_vals)/hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    >>> print(H3(epsilonp_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    >>> print(H4(Ep_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    >>> print(H5(detuning_knob_vals)/hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    >>> print(H6(Ep_vals)/hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    >>> print(H7(epsilonp_vals)/hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    >>> print(H8()/hbar_num/2/np.pi*1e-6)
    [[ 0.    +0.j  0.6398+0.j  1.2795+0.j  1.9193+0.j  2.5591+0.j  3.1989+0.j]
     [ 0.6398+0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.2795+0.j  0.    +0.j  1.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j]
     [ 1.9193+0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j  0.    +0.j]
     [ 2.5591+0.j  0.    +0.j  0.    +0.j  0.    +0.j -3.    +0.j  0.    +0.j]
     [ 3.1989+0.j  0.    +0.j  0.    +0.j  0.    +0.j  0.    +0.j 97.    +0.j]]

    """
    # We determine which arguments are constants.
    if True:
        Nl = len(Ep)
        Ne = np.array(rm[0]).shape[0]
        try:
            Ep = np.array([complex(Ep[l]) for l in range(Nl)])
            variable_Ep = False
        except:
            variable_Ep = True

        try:
            epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)])
                        for l in range(Nl)]
            variable_epsilonp = False
        except:
            variable_epsilonp = True

        try:
            detuning_knob = np.array([float(detuning_knob[l])
                                      for l in range(Nl)])
            variable_detuning_knob = False
        except:
            variable_detuning_knob = True

        # We convert rm to a numpy array
        rm = np.array([[[complex(rm[k][i, j])
                       for j in range(Ne)] for i in range(Ne)]
                       for k in range(3)])
    # We establish the arguments of the output function.
    if True:
        code = ""
        code += "def hamiltonian("
        if variable_Ep: code += "Ep, "
        if variable_epsilonp: code += "epsilonp, "
        if variable_detuning_knob: code += "detuning_knob, "
        if code[-2:] == ", ":
            code = code[:-2]
        code += "):\n"

        code += '    r"""A fast calculation of the hamiltonian."""\n'
        code += "    H = np.zeros(("+str(Ne)+", "+str(Ne)+"), complex)\n\n"
    # We get the code for the below-diagonal elements
    # (Rabi frequencies).
    if True:
        code += "    # We calculate the below-diagonal elements.\n"
        for i in range(Ne):
            for j in range(i):
                for l in range(Nl):
                    if xi[l, i, j] == 1.0:
                        # We get the below-diagonal terms.
                        code += "    H["+str(i)+", "+str(j)+"] = "
                        # We get the code for Ep.
                        if variable_Ep:
                            code += "0.5*Ep["+str(l)+"]"

                        else:
                            code += str(0.5*Ep[l])
                        # We get the code for epsilonp dot rm
                        rmij = rm[:, i, j]
                        if variable_epsilonp:
                            code += "*cartesian_dot_product("
                            code += "epsilonp["+str(l)+"],"
                            code += str(list(rmij*e_num))+" )"
                        else:
                            dp = cartesian_dot_product(epsilonp[l], rmij)
                            dp = dp*e_num
                            code += "*("+str(dp)+")"

                        code += "\n"
    # We get the code for the above-diagonal elements
    # (Conjugate Rabi frequencies).
    if True:
        code += "\n"
        code += """    # We calculate the above-diagonal elements.\n"""
        code += """    for i in range("""+str(Ne)+"""):\n"""
        code += """        for j in range(i+1, """+str(Ne)+"""):\n"""
        code += """            H[i, j] = H[j, i].conjugate()\n\n"""
    # We get the code for the diagonal elements (detunings).
    if True:
        code += "    # We calculate the diagonal elements.\n"
        # We build the degeneration simplification and is inverse (to avoid
        # large combinatorics).
        aux = define_simplification(omega_level, xi, Nl)
        u, invu, omega_levelu, Neu, xiu = aux
        # For each field we find the smallest transition frequency, and its
        # simplified indices.
        omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu)
        #####################################
        # We get the code to calculate the non degenerate detunings.
        pairs = detunings_indices(Neu, Nl, xiu)
        if not variable_detuning_knob:
            code += "    detuning_knob = np.zeros("+str(Nl)+")\n"
            for l in range(Nl):
                code += "    detuning_knob["+str(l)+"] = " +\
                    str(detuning_knob[l])+"\n"

        code_det = detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0)
        code += code_det
        code += "\n"
        #####################################
        # We find the coefficients a_l that multiply omega_laser_l in
        # H_ii = omega_level_iu + theta_iu = \sum_i a_i varpi_i + remainder
        _omega_level, omega, gamma = define_frequencies(Ne)
        _omega_levelu, omega, gamma = define_frequencies(Neu)
        E0, omega_laser = define_laser_variables(Nl)
        # So we build all combinations.
        combs = detunings_combinations(pairs)
        for i in range(Ne):
            _Hii = theta[i] + _omega_levelu[u(i)]
            aux = (_Hii, combs, omega_laser,
                   _omega_levelu, omega_levelu, iu0, ju0)
            assign = detunings_rewrite(*aux)

            if assign != "":
                code += "    H["+str(i)+", "+str(i)+"] = "+assign+"\n"

    code += "\n"
    code += """    for i in range("""+str(Ne)+"""):\n"""
    code += """        H[i, i] = H[i, i]*"""+str(hbar_num)+"\n"

    code += "    return H\n"

    if file_name is not None:
        f = file(file_name, "w")
        f.write(code)
        f.close()

    hamiltonian = code
    exec hamiltonian
    return hamiltonian

Response: r Returns a fast function that returns a Hamiltonian.


Instruction:
How would you explain what the following Python 3 function does
def linear_get_coefficients(coef, rhouv, s, i, j, k, u, v,
                            unfolding, matrix_form):
    r"""Get the indices mu, nu, and term coefficients for linear terms.

    We determine mu and nu, the indices labeling the density matrix components
          d rho[mu] /dt = sum_nu A[mu, nu]*rho[nu]
    for this complex and rho_u,v.

    >>> from fast.symbolic import define_density_matrix
    >>> Ne = 2
    >>> coef = 1+2j
    >>> rhouv = define_density_matrix(Ne)[1, 1]
    >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1)
    >>> unfolding = Unfolding(Ne, real=True, normalized=True)

    >>> linear_get_coefficients(coef, rhouv, s, i, j, k, u, v,
    ...                              unfolding, False)
    [[1, 0, -2.00000000000000, False, False]]

    """
    Ne = unfolding.Ne
    Mu = unfolding.Mu
    # We determine mu, the index labeling the equation.
    mu = Mu(s, i, j)

    if unfolding.normalized and u == 0 and v == 0:
        # We find the nu and coefficients for a term of the form.
        # coef*rho_{00} = coef*(1-sum_{i=1}^{Ne-1} rho_{ii})
        if unfolding.real:
            ss = 1
        else:
            ss = 0

        mu11 = Mu(ss, 1, 1)
        muNeNe = Mu(ss, Ne-1, Ne-1)
        rhouv_isconjugated = False
        if s == 1:
            coef_list = [[mu, nu, im(coef), matrix_form, rhouv_isconjugated]
                         for nu in range(mu11, muNeNe+1)]
        elif s == -1:
            coef_list = [[mu, nu, -re(coef), matrix_form, rhouv_isconjugated]
                         for nu in range(mu11, muNeNe+1)]
        elif s == 0:
            coef_list = [[mu, nu, -coef, matrix_form, rhouv_isconjugated]
                         for nu in range(mu11, muNeNe+1)]
        return coef_list

    #####################################################################

    if (unfolding.lower_triangular and
       isinstance(rhouv, sympy.conjugate)):
        u, v = (v, u)
        rhouv_isconjugated = True
    else:
        rhouv_isconjugated = False
    # If the unfolding is real, there are two terms for this
    # component rhouv of equation mu.
    if unfolding.real:
        nur = Mu(1, u, v)
        nui = Mu(-1, u, v)
    else:
        nu = Mu(0, u, v)
    #####################################################################
    # We determine the coefficients for each term.
    if unfolding.real:
        # There are two sets of forumas for the coefficients depending
        # on whether rhouv_isconjugated.
        # re(I*x*conjugate(y)) = -im(x)*re(y) + re(x)*im(y)
        # re(I*x*y)            = -im(x)*re(y) - re(x)*im(y)
        # im(I*x*conjugate(y)) = +re(x)*re(y) + im(x)*im(y)
        # im(I*x*y)            = +re(x)*re(y) - im(x)*im(y)
        if s == 1:
            # The real part
            if rhouv_isconjugated:
                coef_rerhouv = -im(coef)
                coef_imrhouv = re(coef)
            else:
                coef_rerhouv = -im(coef)
                coef_imrhouv = -re(coef)
        elif s == -1:
            if rhouv_isconjugated:
                coef_rerhouv = re(coef)
                coef_imrhouv = im(coef)
            else:
                coef_rerhouv = re(coef)
                coef_imrhouv = -im(coef)

        coef_list = [[mu, nur, coef_rerhouv, matrix_form, rhouv_isconjugated]]
        if nui is not None:
            coef_list += [[mu, nui, coef_imrhouv,
                           matrix_form, rhouv_isconjugated]]
    else:
        coef_list = [[mu, nu, coef, matrix_form, rhouv_isconjugated]]

    return coef_list

Response: r This function calculates the coefficients for a linear term.


Instruction:
Can you write a function in Python 3 where it
returns a fast function that returns the Lindblad terms.

Response:
def fast_lindblad_terms(gamma, unfolding, matrix_form=False, file_name=None,
                        return_code=False):
    r"""Return a fast function that returns the Lindblad terms.

    We test a basic two-level system.

    >>> import numpy as np
    >>> Ne = 2
    >>> gamma21 = 2*np.pi*6e6
    >>> gamma = np.array([[0.0, -gamma21],
    ...                   [gamma21, 0.0]])
    >>> rhos = np.array([[0.6, 3+2j],
    ...                  [3-2j, 0.4]])

    An map to unfold the density matrix.
    >>> unfolding = Unfolding(Ne, True, True, True)

    We obtain a function to calculate Lindblad terms.
    >>> lindblad_terms = fast_lindblad_terms(gamma, unfolding)

    Apply this to a density matrix.
    >>> rhos = np.array([[0.6, 3+2j],
    ...                  [3-2j, 0.4]])
    >>> rhosv = unfolding(rhos)
    >>> rhs_lindblad = lindblad_terms(rhosv)
    >>> print(rhs_lindblad)
    [-15079644.7372 -56548667.7646  37699111.8431]

    """
    Ne = unfolding.Ne
    Nrho = unfolding.Nrho
    Mu = unfolding.Mu

    # We establish the arguments of the output function.
    if True:
        code = ""
        code += "def lindblad_terms("
        if not matrix_form: code += "rho, "
        if code[-2:] == ", ": code = code[:-2]
        code += "):\n"
    # We initialize the output and auxiliaries.
    if True:
        # We introduce the factor that multiplies all terms.
        if matrix_form:
            code += "    A = np.zeros(("+str(Nrho)+", "+str(Nrho)
            if not unfolding.real:
                code += "), complex)\n\n"
            else:
                code += "))\n\n"
            if unfolding.normalized:
                code += "    b = np.zeros(("+str(Nrho)
                if not unfolding.real:
                    code += "), complex)\n\n"
                else:
                    code += "))\n\n"
        else:
            code += "    rhs = np.zeros(("+str(Nrho)
            if not unfolding.real:
                code += "), complex)\n\n"
            else:
                code += "))\n\n"

    for a in range(Ne):
        for b in range(a):
            # The first term is of the from
            # gamma_ab * rho_aa |b><b|
            if not (unfolding.normalized and b == 0):
                coef = gamma[a, b]
                if unfolding.real:
                    mu = Mu(1, b, b)
                    nu = Mu(1, a, a)
                else:
                    mu = Mu(0, b, b)
                    nu = Mu(0, a, a)
                code += term_code(mu, nu, coef, matrix_form, False)

            # The second term is of the form
            #  sum_j -gamma_ab/2 rho_aj |a><j|
            # for a lower triangular unfolding, this j runs from 1 to a.
            for j in range(a):
                coef = -gamma[a, b]*0.5
                if unfolding.real:
                    mur = Mu(1, a, j)
                    code += term_code(mur, mur, coef, matrix_form, False)
                    mui = Mu(-1, a, j)
                    code += term_code(mui, mui, coef, matrix_form, False)
                else:
                    mu = Mu(0, a, j)
                    code += term_code(mu, mu, coef, matrix_form, False)

            # The third term is of the form
            #  - sum_i 1/2 rho_ia |i><a|
            # for a lower triangular unfolding, this i runs from a to Ne.
            for i in range(a+1, Ne):
                coef = -gamma[a, b]*0.5
                if unfolding.real:
                    mur = Mu(1, i, a)
                    code += term_code(mur, mur, coef, matrix_form, False)
                    mui = Mu(-1, i, a)
                    code += term_code(mui, mui, coef, matrix_form, False)
                else:
                    mu = Mu(0, i, a)
                    code += term_code(mu, mu, coef, matrix_form, False)

            # We missed one term in each of the previous fors, that together
            # correspond to
            # -gamma_ab * rho_aa |a><a|
            coef = -gamma[a, b]
            if unfolding.real:
                mu = Mu(1, a, a)
            else:
                mu = Mu(0, a, a)
            code += term_code(mu, mu, coef, matrix_form, False)

    # We finish the code.
    if True:
        if matrix_form:
            if unfolding.normalized:
                code += "    return A, b\n"
            else:
                code += "    return A\n"
        else:
            code += "    return rhs\n"
    # We write the code to file if provided, and execute it.
    if True:
        if file_name is not None:
            f = file(file_name+".py", "w")
            f.write(code)
            f.close()

        lindblad_terms = code
        if not return_code:
            exec lindblad_terms
    return lindblad_terms


Instruction:
Explain what the following Python 3 code does
def observable(operator, rho, unfolding, complex=False):
    if len(rho.shape) == 2:
        return np.array([observable(operator, i, unfolding) for i in rho])

    Ne = unfolding.Ne
    Mu = unfolding.Mu
    obs = 0

    if unfolding.normalized:
        rho11 = 1 - sum([rho[Mu(1, i, i)] for i in range(1, Ne)])

    for i in range(Ne):
        for k in range(Ne):
            if unfolding.real:
                if k == 0 and i == 0:
                    obs += operator[i, k]*rho11
                else:
                    if k < i:
                        u, v = (i, k)
                    else:
                        u, v = (k, i)
                    obs += operator[i, k]*rho[Mu(1, u, v)]
                    if k != i:
                        if k < i:
                            obs += 1j*operator[i, k]*rho[Mu(-1, u, v)]
                        else:
                            obs += -1j*operator[i, k]*rho[Mu(-1, u, v)]

            else:
                if k == 0 and i == 0:
                    obs += operator[i, k]*rho11
                else:
                    obs += operator[i, k]*rho[Mu(0, k, i)]

    if not complex:
        obs = np.real(obs)
    return obs

Response: r Returns an observable ammount.


Instruction:
Make a summary of the following Python 3 code
def electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, part=0):
    epsilonm = epsilonp.conjugate()
    rp = np.array([rm[i].transpose().conjugate() for i in range(3)])
    if part == 1:
        op = cartesian_dot_product(rp, epsilonm[0])
        op += cartesian_dot_product(rm, epsilonp[0])
        op = -e_num*n/epsilon_0_num/np.abs(Ep[0])*op
    elif part == -1:
        op = cartesian_dot_product(rm, epsilonp[0])
        op += - cartesian_dot_product(rp, epsilonm[0])
        op = -1j*e_num*n/epsilon_0_num/np.abs(Ep[0])*op
    elif part == 0:
        chire = electric_succeptibility(l, Ep, epsilonp, rm,
                                        n, rho, unfolding, +1)
        chiim = electric_succeptibility(l, Ep, epsilonp, rm,
                                        n, rho, unfolding, -1)
        return chire + 1j*chiim

    return np.real(observable(op, rho, unfolding))

Response: r Returns the electric succeptibility for a given field.


Instruction:
Can you tell what is the following Python 3 function doing
def inverse(self, rhov, time_derivative=False):
        Ne = self.Ne
        Nrho = self.Nrho
        IJ = self.IJ

        if isinstance(rhov, np.ndarray):
            rho = np.zeros((Ne, Ne), complex)
            numeric = True
        elif isinstance(rhov, sympy.Matrix):
            rho = sympy.zeros(Ne, Ne)
            numeric = False

        for mu in range(Nrho):
            s, i, j = IJ(mu)
            if numeric:
                if s == 1:
                    rho[i, j] += rhov[mu]
                elif s == -1:
                    rho[i, j] += 1j*rhov[mu]
                elif s == 0:
                    rho[i, j] += rhov[mu]
            else:
                if s == 1:
                    rho[i, j] += rhov[mu]
                elif s == -1:
                    rho[i, j] += sympy.I*rhov[mu]
                elif s == 0:
                    rho[i, j] += rhov[mu]

        if self.lower_triangular:
            for i in range(Ne):
                for j in range(i):
                    rho[j, i] = rho[i, j].conjugate()

        if self.normalized:
            if time_derivative:
                rho[0, 0] = -sum([rho[i, i] for i in range(1, Ne)])
            else:
                rho[0, 0] = 1-sum([rho[i, i] for i in range(1, Ne)])

        return rho

Response: r Folds a vector into a matrix.


Instruction:
Can you tell what is the following Python 3 function doing
def bdplotter(task, **kwargs):
    '''
    bdplotter is based on the fact that phonon DOS/bands and
    electron DOS/bands are the objects of the same kind.
    1) DOS is formatted precomputed / smeared according to a normal distribution
    2) bands are formatted precomputed / interpolated through natural cubic spline function
    '''
    if task == 'bands': # CRYSTAL, "VASP", EXCITING

        results = []

        if 'precomputed' in kwargs:
            for n in range(len(kwargs['precomputed']['ticks'])):
                if kwargs['precomputed']['ticks'][n][1] == 'GAMMA': kwargs['precomputed']['ticks'][n][1] = 'Γ'

            for stripe in kwargs['precomputed']['stripes']:
                results.append({'color':'#000000', 'data':[], 'ticks':kwargs['precomputed']['ticks']})
                for n, val in enumerate(stripe):
                    results[-1]['data'].append([ kwargs['precomputed']['abscissa'][n], val])

        else:
            if not 'order' in kwargs: order = sorted( kwargs['values'].keys() ) # TODO
            else: order = kwargs['order']

            nullstand = '0 0 0'
            if not '0 0 0' in kwargs['values']: # possible case when there is shifted Gamma point
                nullstand = order[0]

            # reduce k if too much
            if len(order)>20:
                red_order = []
                for i in range(0, len(order), int(math.floor(len(order)/10))):
                    red_order.append(order[i])
                order = red_order

            for N in range(len( kwargs['values'][nullstand] )):
                # interpolate for each curve throughout the BZ
                results.append({'color':'#000000', 'data':[], 'ticks':[]})
                d = 0.0
                x = []
                y = []
                bz_vec_ref = [0, 0, 0]

                for bz in order:
                    y.append( kwargs['values'][bz][N] )
                    bz_coords = map(frac2float, bz.split() )
                    bz_vec_cur = dot( bz_coords, linalg.inv( kwargs['xyz_matrix'] ).transpose() )
                    bz_vec_dir = map(sum, zip(bz_vec_cur, bz_vec_ref))
                    bz_vec_ref = bz_vec_cur
                    d += linalg.norm( bz_vec_dir )
                    x.append(d)
                    results[-1]['ticks'].append( [d, bz.replace(' ', '')] )

                # end in nullstand point (normally, Gamma)
                #y.append(kwargs['values'][nullstand][N])
                #if d == 0: d+=0.5
                #else: d += linalg.norm( bz_vec_ref )
                #x.append(d)
                #results[-1]['ticks'].append( [d, nullstand.replace(' ', '')] )

                divider = 10 if len(order)<10 else 1.5
                step = (max(x)-min(x)) / len(kwargs['values']) / divider

                xnew = arange(min(x), max(x)+step/2, step).tolist()
                ynew = []
                f = NaturalCubicSpline( array(x), array(y) )
                for i in xnew:
                    results[-1]['data'].append([ round(  i, 3  ), round(  f(i), 3  ) ]) # round to reduce output

        return results

    elif task == 'dos': # CRYSTAL, VASP, EXCITING

        results = []

        if 'precomputed' in kwargs:
            total_dos = [[i, kwargs['precomputed']['total'][n]] for n, i in enumerate(kwargs['precomputed']['x'])]

        else:
            tdos = TotalDos( kwargs['eigenvalues'], sigma=kwargs['sigma'] )
            tdos.set_draw_area(omega_min=kwargs['omega_min'], omega_max=kwargs['omega_max'], omega_pitch=kwargs['omega_pitch'])
            total_dos = tdos.calculate()

        results.append({'label':'total', 'color': '#000000', 'data': total_dos})

        if 'precomputed' in kwargs:
            partial_doses = []
            for k in kwargs['precomputed'].keys():
                if k in ['x', 'total']: continue
                partial_doses.append({ 'label': k, 'data': [[i, kwargs['precomputed'][k][n]] for n, i in enumerate(kwargs['precomputed']['x'])] })

        elif 'impacts' in kwargs and 'atomtypes' in kwargs:
            # get the order of atoms to evaluate their partial impact
            labels = {}
            types = []
            index, subtractor = 0, 0
            for k, atom in enumerate(kwargs['atomtypes']): # determine the order of atoms for the partial impact of every type
                if atom not in labels:
                    #if atom == 'X' and not calc.phonons: # artificial GHOST case for phonons, decrease atomic index
                    #    subtractor += 1
                    #    continue
                    labels[atom] = index
                    types.append([k+1-subtractor])
                    index += 1
                else:
                    types[ labels[atom] ].append(k+1-subtractor)

            pdos = PartialDos( kwargs['eigenvalues'], kwargs['impacts'], sigma=kwargs['sigma'] )
            pdos.set_draw_area(omega_min=kwargs['omega_min'], omega_max=kwargs['omega_max'], omega_pitch=kwargs['omega_pitch'])
            partial_doses = pdos.calculate( types, labels )

            # add colors to partials
            for i in range(len(partial_doses)):
                if partial_doses[i]['label'] == 'X': color = '#000000'
                elif partial_doses[i]['label'] == 'H': color = '#CCCCCC'
                else:
                    try: color = jmol_to_hex( jmol_colors[ chemical_symbols.index(partial_doses[i]['label']) ] )
                    except ValueError: color = '#FFCC66'
                partial_doses[i].update({'color': color})
            results.extend(partial_doses)

        return results

Response: This function is used to plot the BZ in order to get the order of the objects in the order they are in.


Instruction:
Given the following Python 3 function, write the documentation
def eplotter(task, data): # CRYSTAL, VASP, EXCITING
    '''
    eplotter is like bdplotter but less complicated
    '''
    results, color, fdata = [], None, []

    if task == 'optstory':
        color = '#CC0000'
        clickable = True
        for n, i in enumerate(data):
            fdata.append([n, i[4]])
        fdata = array(fdata)
        fdata[:,1] -= min(fdata[:,1]) # this normalizes values to minimum (by 2nd col)
        fdata = fdata.tolist()

    elif task == 'convergence':
        color = '#0066CC'
        clickable = False
        for n, i in enumerate(data):
            fdata.append([n, i])

    for n in range(len(fdata)):
        #fdata[n][1] = "%10.5f" % fdata[n][1]
        fdata[n][1] = round(fdata[n][1], 5)

    results.append({'color': color, 'clickable:': clickable, 'data': fdata})
    return results

Response: eplotter is like bdplotter but less complicated


Instruction:
Create a Python 3 function to
assign a parser to the current parser.

Response:
def assign_parser(self, name):
        '''
        Restricts parsing
        **name** is a name of the parser class
        NB: this is the PUBLIC method
        @procedure
        '''
        for n, p in list(self.Parsers.items()):
            if n != name:
                del self.Parsers[n]
        if len(self.Parsers) != 1:
            raise RuntimeError('Parser cannot be assigned!')


Instruction:
Implement a Python 3 function for
constructing a standardized chemical formula for the given atom sequence.

Response:
def formula(self, atom_sequence):
        '''
        Constructs standardized chemical formula
        NB: this is the PUBLIC method
        @returns formula_str
        '''
        labels = {}
        types = []
        y = 0
        for k, atomi in enumerate(atom_sequence):
            lbl = re.sub("[0-9]+", "", atomi).capitalize()
            if lbl not in labels:
                labels[lbl] = y
                types.append([k+1])
                y += 1
            else:
                types[ labels[lbl] ].append(k+1)
        atoms = list(labels.keys())
        atoms = [x for x in self.formula_sequence if x in atoms] + [x for x in atoms if x not in self.formula_sequence] # accordingly
        formula = ''
        for atom in atoms:
            n = len(types[labels[atom]])
            if n==1: n = ''
            else: n = str(n)
            formula += atom + n
        return formula


Instruction:
Given the following Python 3 function, write the documentation
def savvyize(self, input_string, recursive=False, stemma=False):
        '''
        Determines which files should be processed
        NB: this is the PUBLIC method
        @returns filenames_list
        '''
        input_string = os.path.abspath(input_string)
        tasks = []

        restricted = [ symbol for symbol in self.settings['skip_if_path'] ] if self.settings['skip_if_path'] else []

        # given folder
        if os.path.isdir(input_string):
            if recursive:
                for root, dirs, files in os.walk(input_string): # beware of broken links on unix! (NB find ~ -type l -exec rm -f {} \;)
                    # skip_if_path directive
                    to_filter = []
                    for dir in dirs:
                        dir = u(dir)
                        for rs in restricted:
                            if dir.startswith(rs) or dir.endswith(rs):
                                to_filter.append(dir)
                                break
                    dirs[:] = [x for x in dirs if x not in to_filter]
                    for filename in files:
                        # skip_if_path directive
                        filename = u(filename)
                        if restricted:
                            for rs in restricted:
                                if filename.startswith(rs) or filename.endswith(rs):
                                    break
                            else:
                                tasks.append(root + os.sep + filename)
                        else:
                            tasks.append(root + os.sep + filename)
            else:
                for filename in os.listdir(input_string):
                    filename = u(filename)
                    if os.path.isfile(input_string + os.sep + filename):
                        # skip_if_path directive
                        if restricted:
                            for rs in restricted:
                                if filename.startswith(rs) or filename.endswith(rs):
                                    break
                            else:
                                tasks.append(input_string + os.sep + filename)
                        else:
                            tasks.append(input_string + os.sep + filename)

        # given full filename
        elif os.path.isfile(input_string):
            tasks.append(input_string) # skip_if_path directive is not applicable here

        # given filename stemma
        else:
            if stemma:
                parent = os.path.dirname(input_string)
                for filename in os.listdir(parent):
                    filename = u(filename)
                    if input_string in parent + os.sep + filename and not os.path.isdir(parent + os.sep + filename):
                        # skip_if_path directive
                        if restricted:
                            for rs in restricted:
                                if filename.startswith(rs) or filename.endswith(rs):
                                    break
                            else:
                                tasks.append(parent + os.sep + filename)
                        else:
                            tasks.append(parent + os.sep + filename)
        return tasks

Response: This method will take a string and return a list of filenames that can be processed.


Instruction:
Make a summary of the following Python 3 code
def _parse(self, parsable, parser_name):
        '''
        Low-level parsing
        NB: this is the PRIVATE method
        @returns tilde_obj, error
        '''
        calc, error = None, None
        try:
            for calc in self.Parsers[parser_name].iparse(parsable):
                yield calc, None
            return
        except RuntimeError as e:
            error = "routine %s parser error in %s: %s" % ( parser_name, parsable, e )
        except:
            exc_type, exc_value, exc_tb = sys.exc_info()
            error = "unexpected %s parser error in %s:\n %s" % ( parser_name, parsable, "".join(traceback.format_exception( exc_type, exc_value, exc_tb )) )
        yield None, error

Response: Parse a set of items from a parsable object.


Instruction:
Can you generate the documentation for the following Python 3 function
def parse(self, parsable):
        '''
        High-level parsing:
        determines the data format
        and combines parent-children outputs
        NB: this is the PUBLIC method
        @returns tilde_obj, error
        '''
        calc, error = None, None
        try:
            f = open(parsable, 'rb')
            if is_binary_string(f.read(2048)):
                yield None, 'was read (binary data)...'
                return
            f.close()
        except IOError:
            yield None, 'read error!'
            return

        f = open(parsable, 'r', errors='surrogateescape') if six.PY3 else open(parsable, 'r') # open the file once again with right mode
        f.seek(0)
        counter, detected = 0, False

        while not detected:

            if counter > 700: break # criterion: parser must detect its working format until here

            fingerprint = f.readline()
            if not fingerprint:
                break
            for name, Parser in self.Parsers.items():
                if Parser.fingerprints(fingerprint):
                    for calc, error in self._parse(parsable, name):
                        detected = True
                        # check if we parsed something reasonable
                        if not error and calc:

                            if not len(calc.structures) or not len(calc.structures[-1]):
                                error = 'Valid structure is not present!'

                            if calc.info['finished'] == 0x1:
                                calc.warning( 'This calculation is not correctly finished!' )

                            if not calc.info['H']:
                                error = 'XC potential is not present!'

                        yield calc, error

                    if detected:
                        break
            counter += 1
        f.close()

        # unsupported data occured
        if not detected:
            yield None, 'was read...'

Response: High - level parsing for the tilde object.


Instruction:
Create a Python 3 function to
classify the current structure using the hierarchy API and returns the tilde_obj and the error message

Response:
def classify(self, calc, symprec=None):
        '''
        Reasons on normalization, invokes hierarchy API and prepares calc for saving
        NB: this is the PUBLIC method
        @returns tilde_obj, error
        '''
        error = None
        symbols = calc.structures[-1].get_chemical_symbols()
        calc.info['formula'] = self.formula(symbols)
        calc.info['cellpar'] = cell_to_cellpar(calc.structures[-1].cell).tolist()
        if calc.info['input']:
            try:
                calc.info['input'] = str(calc.info['input'], errors='ignore')
            except:
                pass

        # applying filter: todo
        if (calc.info['finished'] == 0x1 and self.settings['skip_unfinished']) or \
           (not calc.info['energy'] and self.settings['skip_notenergy']):
            return None, 'data do not satisfy the active filter'

        # naive elements extraction
        fragments = re.findall(r'([A-Z][a-z]?)(\d*[?:.\d+]*)?', calc.info['formula'])
        for fragment in fragments:
            if fragment[0] == 'X':
                continue
            calc.info['elements'].append(fragment[0])
            calc.info['contents'].append(int(fragment[1])) if fragment[1] else calc.info['contents'].append(1)

        # extend hierarchy with modules
        for C_obj in self.Classifiers:
            try:
                calc = C_obj['classify'](calc)
            except:
                exc_type, exc_value, exc_tb = sys.exc_info()
                error = "Fatal error during classification:\n %s" % "".join(traceback.format_exception( exc_type, exc_value, exc_tb ))
                return None, error

        # chemical ratios
        if not len(calc.info['standard']):
            if len(calc.info['elements']) == 1: calc.info['expanded'] = 1
            if not calc.info['expanded']:
                calc.info['expanded'] = reduce(gcd, calc.info['contents'])
            for n, i in enumerate([x//calc.info['expanded'] for x in calc.info['contents']]):
                if i == 1:
                    calc.info['standard'] += calc.info['elements'][n]
                else:
                    calc.info['standard'] += calc.info['elements'][n] + str(i)
        if not calc.info['expanded']:
            del calc.info['expanded']

        calc.info['nelem'] = len(calc.info['elements'])
        if calc.info['nelem'] > 13:
            calc.info['nelem'] = 13
        calc.info['natom'] = len(symbols)

        # periodicity
        if calc.info['periodicity'] == 0:
            calc.info['periodicity'] = 0x4
        elif calc.info['periodicity'] == -1:
            calc.info['periodicity'] = 0x5

        # general calculation type reasoning
        if (calc.structures[-1].get_initial_charges() != 0).sum():
            calc.info['calctypes'].append(0x4) # numpy count_nonzero implementation
        if (calc.structures[-1].get_initial_magnetic_moments() != 0).sum():
            calc.info['calctypes'].append(0x5)
        if calc.phonons['modes']:
            calc.info['calctypes'].append(0x6)
        if calc.phonons['ph_k_degeneracy']:
            calc.info['calctypes'].append(0x7)
        if calc.phonons['dielectric_tensor']:
            calc.info['calctypes'].append(0x8) # CRYSTAL-only!
        if len(calc.tresholds) > 1:
            calc.info['calctypes'].append(0x3)
            calc.info['optgeom'] = True
        if calc.electrons['dos'] or calc.electrons['bands']:
            calc.info['calctypes'].append(0x2)
        if calc.info['energy']:
            calc.info['calctypes'].append(0x1)
        calc.info['spin'] = 0x2 if calc.info['spin'] else 0x1

        # TODO: standardize
        if 'vac' in calc.info:
            if 'X' in symbols:
                calc.info['techs'].append('vacancy defect: ghost')
            else:
                calc.info['techs'].append('vacancy defect: void space')

        calc.info['lata'] = round(calc.info['cellpar'][0], 3)
        calc.info['latb'] = round(calc.info['cellpar'][1], 3)
        calc.info['latc'] = round(calc.info['cellpar'][2], 3)
        calc.info['latalpha'] = round(calc.info['cellpar'][3], 2)
        calc.info['latbeta'] = round(calc.info['cellpar'][4], 2)
        calc.info['latgamma'] = round(calc.info['cellpar'][5], 2)

        # invoke symmetry finder
        found = SymmetryHandler(calc, symprec)
        if found.error:
            return None, found.error

        calc.info['sg'] = found.i
        calc.info['ng'] = found.n
        calc.info['symmetry'] = found.symmetry
        calc.info['spg'] = "%s — %s" % (found.n, found.i)
        calc.info['pg'] = found.pg
        calc.info['dg'] = found.dg

        # phonons
        if calc.phonons['dfp_magnitude']: calc.info['dfp_magnitude'] = round(calc.phonons['dfp_magnitude'], 3)
        if calc.phonons['dfp_disps']: calc.info['dfp_disps'] = len(calc.phonons['dfp_disps'])
        if calc.phonons['modes']:
            calc.info['n_ph_k'] = len(calc.phonons['ph_k_degeneracy']) if calc.phonons['ph_k_degeneracy'] else 1

        #calc.info['rgkmax'] = calc.electrons['rgkmax'] # LAPW

        # electronic properties reasoning by bands
        if calc.electrons['bands']:
            if calc.electrons['bands'].is_conductor():
                calc.info['etype'] = 0x2
                calc.info['bandgap'] = 0.0
                calc.info['bandgaptype'] = 0x1
            else:
                try:
                    gap, is_direct = calc.electrons['bands'].get_bandgap()
                except ElectronStructureError as e:
                    calc.electrons['bands'] = None
                    calc.warning(e.value)
                else:
                    calc.info['etype'] = 0x1
                    calc.info['bandgap'] = round(gap, 2)
                    calc.info['bandgaptype'] = 0x2 if is_direct else 0x3

        # electronic properties reasoning by DOS
        if calc.electrons['dos']:
            try: gap = round(calc.electrons['dos'].get_bandgap(), 2)
            except ElectronStructureError as e:
                calc.electrons['dos'] = None
                calc.warning(e.value)
            else:
                if calc.electrons['bands']: # check coincidence
                    if abs(calc.info['bandgap'] - gap) > 0.2:
                        calc.warning('Bans gaps in DOS and bands data differ considerably! The latter will be considered.')
                else:
                    calc.info['bandgap'] = gap
                    if gap:
                        calc.info['etype'] = 0x1
                    else:
                        calc.info['etype'] = 0x2
                        calc.info['bandgaptype'] = 0x1

        # TODO: beware to add something new to an existing item!
        # TODO2: unknown or absent?
        for entity in self.hierarchy:
            if entity['creates_topic'] and not entity['optional'] and not calc.info.get(entity['source']):
                if entity['enumerated']:
                    calc.info[ entity['source'] ] = [0x0] if entity['multiple'] else 0x0
                else:
                    calc.info[ entity['source'] ] = ['none'] if entity['multiple'] else 'none'

        calc.benchmark() # this call must be at the very end of parsing

        return calc, error


Instruction:
Write a Python 3 function that can
invoke module(s) API NB: this is the PUBLIC method @returns apps_dict

Response:
def postprocess(self, calc, with_module=None, dry_run=None):
        '''
        Invokes module(s) API
        NB: this is the PUBLIC method
        @returns apps_dict
        '''
        for appname, appclass in self.Apps.items():
            if with_module and with_module != appname: continue

            run_permitted = False

            # scope-conditions
            if appclass['apptarget']:
                for key in appclass['apptarget']:
                    negative = False
                    if str(appclass['apptarget'][key]).startswith('!'):
                        negative = True
                        scope_prop = appclass['apptarget'][key][1:]
                    else:
                        scope_prop = appclass['apptarget'][key]

                    if key in calc.info:
                        # non-strict comparison ("CRYSTAL" matches "CRYSTAL09 v2.0")
                        if (str(scope_prop) in str(calc.info[key]) or scope_prop == calc.info[key]) != negative: # true if only one, but not both
                            run_permitted = True
                        else:
                            run_permitted = False
                            break

            else: run_permitted = True

            # module code running
            if run_permitted:
                calc.apps[appname] = {'error': None, 'data': None}
                if dry_run:
                    continue
                try:
                    AppInstance = appclass['appmodule'](calc)
                except:
                    exc_type, exc_value, exc_tb = sys.exc_info()
                    errmsg = "Fatal error in %s module:\n %s" % ( appname, " ".join(traceback.format_exception( exc_type, exc_value, exc_tb )) )
                    calc.apps[appname]['error'] = errmsg
                    calc.warning( errmsg )
                else:
                    try:
                        calc.apps[appname]['data'] = getattr(AppInstance, appclass['appdata'])
                    except AttributeError:
                        errmsg = 'No appdata-defined property found for %s module!' % appname
                        calc.apps[appname]['error'] = errmsg
                        calc.warning( errmsg )
        return calc