Пример #1
0
    def test_simplify(self):
        """Test simplify"""
        with self.subTest("simplify integer"):
            fer_op = FermionicOp("N") + FermionicOp("E") + FermionicOp("N")
            simplified_op = fer_op.simplify()
            targ = FermionicOp([("N", 2), ("E", 1)])
            self.assertFermionEqual(simplified_op, targ)

        with self.subTest("simplify complex"):
            fer_op = FermionicOp(
                "+") + 1j * FermionicOp("-") + 1j * FermionicOp("+")
            simplified_op = fer_op.simplify()
            targ = FermionicOp([("+", 1 + 1j), ("-", 1j)])
            self.assertFermionEqual(simplified_op, targ)

        with self.subTest("simplify doesn't reorder"):
            fer_op = FermionicOp("+_1 -_0")
            simplified_op = fer_op.simplify()
            expected = [((("-", 0), ("+", 1)), -1)]
            self.assertEqual(simplified_op._data, expected)

        with self.subTest("simplify zero"):
            fer_op = FermionicOp("+") - FermionicOp("+")
            simplified_op = fer_op.simplify()
            targ = FermionicOp.zero(1)
            self.assertFermionEqual(simplified_op, targ)
    def to_second_q_op(self) -> FermionicOp:
        """Creates the operator representing the Hamiltonian defined by these electronic integrals.

        This method uses ``to_spin`` internally to map the electronic integrals into the spin
        orbital basis.

        Returns:
            The :class:`~qiskit_nature.second_q.operators.FermionicOp` given by these
            electronic integrals.
        """
        spin_matrix = self.to_spin()
        register_length = len(spin_matrix)

        if not np.any(spin_matrix):
            return FermionicOp.zero(register_length)

        spin_matrix_iter = spin_matrix.flat
        # NOTE: we need to access `.coords` before `.next()` is called for the first time!
        coords = spin_matrix_iter.coords
        op_data = []
        for coeff in spin_matrix_iter:
            if coeff:
                op_data.append((self._calc_coeffs_with_ops(coords), coeff))
            coords = spin_matrix_iter.coords

        return FermionicOp(op_data, register_length=register_length, display_format="sparse")