How to use the openfermion.ops.InteractionOperator function in openfermion

To help you get started, we’ve selected a few openfermion examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github quantumlib / OpenFermion / src / openfermion / utils / _testing_utils.py View on Github external
coefficient = two_body_coefficients[p, q, r, s]

            # Mixed spin.
            new_two_body_coefficients[2 * p, 2 * q + 1, 2 * r + 1, 2 * s] = (
                coefficient)
            new_two_body_coefficients[2 * p + 1, 2 * q, 2 * r, 2 * s + 1] = (
                coefficient)

            # Same spin.
            new_two_body_coefficients[2 * p, 2 * q, 2 * r, 2 * s] = coefficient
            new_two_body_coefficients[2 * p + 1, 2 * q + 1,
                                      2 * r + 1, 2 * s + 1] = coefficient
        two_body_coefficients = new_two_body_coefficients

    # Create the InteractionOperator.
    interaction_operator = InteractionOperator(
        constant, one_body_coefficients, two_body_coefficients)

    return interaction_operator
github quantumlib / OpenFermion / src / openfermion / utils / _operator_utils.py View on Github external
((p, q), (p, r)), ((p, r), (p, q)),
                ((p, q), (q, r)), ((q, r), (p, q)),
                ((p, r), (q, r)), ((q, r), (p, r))])
        quartic_index_pairs = (index_pair
            for p, q, r, s in itertools.combinations(range(n_modes)[::-1], 4)
            for index_pair in [
                ((p, q), (r, s)), ((r, s), (p, q)),
                ((p, r), (q, s)), ((q, s), (p, r)),
                ((p, s), (q, r)), ((q, r), (p, s))])
        index_pairs = itertools.chain(
            quadratic_index_pairs, cubic_index_pairs, quartic_index_pairs)
        for pq, rs in index_pairs:
            two_body_tensor[pq + rs] = sum(
                s * ss * operator.two_body_tensor[pq[::s] + rs[::ss]]
                for s, ss in itertools.product([-1, 1], repeat=2))
        return InteractionOperator(constant, one_body_tensor, two_body_tensor)

    else:
        raise TypeError('Can only normal order FermionOperator, '
                        'BosonOperator, QuadOperator, or InteractionOperator.')

    for term, coefficient in operator.terms.items():
        ordered_operator += order_fn(term, coefficient, **kwargs)

    return ordered_operator
github quantumlib / OpenFermion / src / openfermion / hamiltonians / _molecular_data.py View on Github external
# Same spin
                        two_body_coefficients[2 * p, 2 * q,
                                              2 * r, 2 * s] = (
                            two_body_integrals[p, q, r, s] / 2.)
                        two_body_coefficients[2 * p + 1, 2 * q + 1,
                                              2 * r + 1, 2 * s + 1] = (
                            two_body_integrals[p, q, r, s] / 2.)

        # Truncate.
        one_body_coefficients[
            numpy.absolute(one_body_coefficients) < EQ_TOLERANCE] = 0.
        two_body_coefficients[
            numpy.absolute(two_body_coefficients) < EQ_TOLERANCE] = 0.

        # Cast to InteractionOperator class and return.
        molecular_hamiltonian = InteractionOperator(
            constant, one_body_coefficients, two_body_coefficients)

        return molecular_hamiltonian
github quantumlib / OpenFermion / src / openfermion / transforms / _conversion.py View on Github external
elif len(term) == 4:
            # Handle two-body terms.
            if [operator[1] for operator in term] == [1, 1, 0, 0]:
                p, q, r, s = [operator[0] for operator in term]
                two_body[p, q, r, s] = coefficient
            else:
                raise InteractionOperatorError('FermionOperator does not map '
                                               'to InteractionOperator.')

        else:
            # Handle non-molecular Hamiltonian.
            raise InteractionOperatorError('FermionOperator does not map '
                                           'to InteractionOperator.')

    # Form InteractionOperator and return.
    interaction_operator = InteractionOperator(constant, one_body, two_body)
    return interaction_operator
github quantumlib / OpenFermion / src / openfermion / utils / _operator_utils.py View on Github external
conjugate_operator = QubitOperator()
        for term, coefficient in operator.terms.items():
            conjugate_operator.terms[term] = coefficient.conjugate()

    # Handle QuadOperator
    elif isinstance(operator, QuadOperator):
        conjugate_operator = QuadOperator()
        for term, coefficient in operator.terms.items():
            conjugate_term = reversed(term)
            # take into account that different indices commute
            conjugate_term = tuple(
                sorted(conjugate_term, key=lambda factor: factor[0]))
            conjugate_operator.terms[conjugate_term] = coefficient.conjugate()

    # Handle InteractionOperator
    elif isinstance(operator, InteractionOperator):
        conjugate_constant = operator.constant.conjugate()
        conjugate_one_body_tensor = hermitian_conjugated(
            operator.one_body_tensor)
        conjugate_two_body_tensor = hermitian_conjugated(
            operator.two_body_tensor)
        conjugate_operator = type(operator)(conjugate_constant,
            conjugate_one_body_tensor, conjugate_two_body_tensor)

    # Handle sparse matrix
    elif isinstance(operator, spmatrix):
        conjugate_operator = operator.getH()

    # Handle numpy array
    elif isinstance(operator, numpy.ndarray):
        conjugate_operator = operator.T.conj()
github quantumlib / OpenFermion / src / openfermion / transforms / _jordan_wigner.py View on Github external
Warning:
        The runtime of this method is exponential in the maximum locality
        of the original FermionOperator.

    Raises:
        TypeError: Operator must be a FermionOperator,
            DiagonalCoulombHamiltonian, or InteractionOperator.
    """
    if isinstance(operator, FermionOperator):
        return jordan_wigner_fermion_operator(operator)
    if isinstance(operator, MajoranaOperator):
        return jordan_wigner_majorana_operator(operator)
    if isinstance(operator, DiagonalCoulombHamiltonian):
        return jordan_wigner_diagonal_coulomb_hamiltonian(operator)
    if isinstance(operator, InteractionOperator):
        return jordan_wigner_interaction_op(operator)
    raise TypeError("Operator must be a FermionOperator, "
                    "MajoranaOperator, "
github quantumlib / OpenFermion / src / openfermion / utils / _operator_utils.py View on Github external
TypeError: Operator of invalid type.
    """
    file_path = get_file_path(file_name, data_directory)

    if os.path.isfile(file_path) and not allow_overwrite:
        raise OperatorUtilsError("Not saved, file already exists.")

    if isinstance(operator, FermionOperator):
        operator_type = "FermionOperator"
    elif isinstance(operator, BosonOperator):
        operator_type = "BosonOperator"
    elif isinstance(operator, QubitOperator):
        operator_type = "QubitOperator"
    elif isinstance(operator, QuadOperator):
        operator_type = "QuadOperator"
    elif isinstance(operator, (InteractionOperator, InteractionRDM)):
        raise NotImplementedError('Not yet implemented for '
                                  'InteractionOperator or InteractionRDM.')
    else:
        raise TypeError('Operator of invalid type.')

    if plain_text:
        with open(file_path, 'w') as f:
            f.write(operator_type + ":\n" + str(operator))
    else:
        tm = operator.terms
        with open(file_path, 'wb') as f:
            marshal.dump((operator_type,
                          dict(zip(tm.keys(), map(complex, tm.values())))), f)
github quantumlib / OpenFermion / src / openfermion / ops / _interaction_rdm.py View on Github external
Args:
            operator: A QubitOperator or InteractionOperator.

        Returns:
            float: Expectation value

        Raises:
            InteractionRDMError: Invalid operator provided.
        """
        if isinstance(operator, QubitOperator):
            expectation_op = self.get_qubit_expectations(operator)
            expectation = 0.0
            for qubit_term in operator.terms:
                expectation += (operator.terms[qubit_term] *
                                expectation_op.terms[qubit_term])
        elif isinstance(operator, InteractionOperator):
            expectation = operator.constant
            expectation += numpy.sum(self.one_body_tensor *
                                     operator.one_body_tensor)
            expectation += numpy.sum(self.two_body_tensor *
                                     operator.two_body_tensor)
        else:
            raise InteractionRDMError('Invalid operator type provided.')
        return expectation