def _add(self, other): """Return the operator self + other. Args: other (BaseOperator): an operator object. Returns: ScalarOp: if other is an ScalarOp. BaseOperator: if other is not an ScalarOp. Raises: QiskitError: if other has incompatible dimensions. """ if not isinstance(other, BaseOperator): other = Operator(other) self._validate_add_dims(other) # First we check the special case where coeff=0. In this case # we simply return the other operator reshaped so that its # subsystem dimensions are equal to the current operator for the # case where total dimensions agree but subsystem dimensions differ. if self.coeff == 0: return other.reshape(self._input_dims, self._output_dims) # Next if we are adding two ScalarOps we return a ScalarOp if isinstance(other, ScalarOp): coeff1 = 1 if self.coeff is None else self.coeff coeff2 = 1 if other.coeff is None else other.coeff return ScalarOp(self._input_dims, coeff=coeff1 + coeff2) # Finally if we are adding another BaseOperator subclass # we use that subclasses `_add` method and reshape the # final dimensions. return other._add(self).reshape(self._input_dims, self._output_dims)
def test_add(self): """Test add method.""" mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) op1 = Operator(mat1) op2 = Operator(mat2) self.assertEqual(op1._add(op2), Operator(mat1 + mat2)) self.assertEqual(op1 + op2, Operator(mat1 + mat2)) self.assertEqual(op1 - op2, Operator(mat1 - mat2))