# Python numpy.conjugate() Examples

The following are 30 code examples for showing how to use numpy.conjugate(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module , or try the search function .

Example 1
```def __init__(self, j):
self._j = j
self._c2r = np.zeros( (2*j+1, 2*j+1), dtype=np.complex128)
self._c2r[j,j]=1.0
for m in range(1,j+1):
self._c2r[m+j, m+j] = sgn[m] * np.sqrt(0.5)
self._c2r[m+j,-m+j] = np.sqrt(0.5)
self._c2r[-m+j,-m+j]= 1j*np.sqrt(0.5)
self._c2r[-m+j, m+j]= -sgn[m] * 1j * np.sqrt(0.5)

self._hc_c2r = np.conj(self._c2r).transpose()
self._conj_c2r = np.conjugate(self._c2r) # what is the difference ? conj and conjugate
self._tr_c2r = np.transpose(self._c2r)

#print(abs(self._hc_c2r.conj().transpose()-self._c2r).sum())

#
#
# ```
Example 2
```def infidelity_diff(self, constant_value):
"""
Returns a ReportableQty that is the (element-wise in the vector case)
difference between `constant_value` and this one given by:

`1.0 - Re(conjugate(constant_value) * self )`
"""
# let diff(x) = 1.0 - Re(const.C * x) = 1.0 - (const.re * x.re + const.im * x.im)
# so d(diff)/dx.re = -const.re, d(diff)/dx.im = -const.im
# diff(x + dx) = diff(x) + d(diff)/dx * dx
# diff(x + dx) - diff(x) =  - (const.re * dx.re + const.im * dx.im)
v = 1.0 - _np.real(_np.conjugate(constant_value) * self.value)
if self.has_eb():
eb = abs(_np.real(constant_value) * _np.real(self.errbar)
+ _np.imag(constant_value) * _np.real(self.errbar))
return ReportableQty(v, eb, self.nonMarkovianEBs)
else:
return ReportableQty(v) ```
Example 3
```def is_hermitian(mx, TOL=1e-9):
"""
Test whether mx is a hermitian matrix.

Parameters
----------
mx : numpy array
Matrix to test.

TOL : float, optional
Tolerance on absolute magitude of elements.

Returns
-------
bool
True if mx is hermitian, otherwise False.
"""
(m, n) = mx.shape
for i in range(m):
if abs(mx[i, i].imag) > TOL: return False
for j in range(i + 1, n):
if abs(mx[i, j] - mx[j, i].conjugate()) > TOL: return False
return True ```
Example 4
```def to_unitary(scaled_unitary):
"""
Compute the scaling factor required to turn a scalar multiple of a unitary matrix
to a unitary matrix.

Parameters
----------
scaled_unitary : ndarray
A scaled unitary matrix

Returns
-------
scale : float
unitary : ndarray
Such that `scale * unitary == scaled_unitary`.

"""
scaled_identity = _np.dot(scaled_unitary, _np.conjugate(scaled_unitary.T))
scale = _np.sqrt(scaled_identity[0, 0])
assert(_np.allclose(scaled_identity / (scale**2), _np.identity(scaled_identity.shape[0], 'd'))), \
"Given `scaled_unitary` does not appear to be a scaled unitary matrix!"
return scale, (scaled_unitary / scale) ```
Example 5
```def state_to_dmvec(psi):
"""
Compute the vectorized density matrix which acts as the state `psi`.

This is just the outer product map |psi> => |psi><psi| with the
output flattened, i.e. `dot(psi, conjugate(psi).T)`.

Parameters
----------
psi : numpy array
The state vector.

Returns
-------
numpy array
The vectorized density matrix.
"""
psi = psi.reshape((psi.size, 1))  # convert to (N,1) shape if necessary
dm = _np.dot(psi, _np.conjugate(psi.T))
return dm.flatten() ```
Example 6
```def unitary_to_process_mx(U):
"""
Compute the super-operator which acts on (row)-vectorized
density matrices from a unitary operator (matrix) U which
acts on state vectors.  This super-operator is given by
the tensor product of U and conjugate(U), i.e. kron(U,U.conj).

Parameters
----------
U : numpy array
The unitary matrix which acts on state vectors.

Returns
-------
numpy array
The super-operator process matrix.
"""
# U -> kron(U,Uc) since U rho U_dag -> kron(U,Uc)
#  since AXB --row-vectorize--> kron(A,B.T)*vec(X)
return _np.kron(U, _np.conjugate(U)) ```
Example 7
```def test_poly(self):
assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]),
[1, -3, -2, 6])

# From matlab docs
A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
assert_array_almost_equal(np.poly(A), [1, -6, -72, -27])

# Should produce real output for perfect conjugates
assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j])))
assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j,
1-2j, 1.+3.5j, 1-3.5j])))
assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j])))
assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j])))
assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j])))
assert_(np.isrealobj(np.poly([1j, -1j])))
assert_(np.isrealobj(np.poly([1, -1])))

assert_(np.iscomplexobj(np.poly([1j, -1.0000001j])))

np.random.seed(42)
a = np.random.randn(100) + 1j*np.random.randn(100)
assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a)))))) ```
Example 8
```def test_testArrayMethods(self):
a = array([1, 3, 2])
assert_(eq(a.any(), a._data.any()))
assert_(eq(a.all(), a._data.all()))
assert_(eq(a.argmax(), a._data.argmax()))
assert_(eq(a.argmin(), a._data.argmin()))
assert_(eq(a.choose(0, 1, 2, 3, 4),
a._data.choose(0, 1, 2, 3, 4)))
assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
assert_(eq(a.conj(), a._data.conj()))
assert_(eq(a.conjugate(), a._data.conjugate()))
m = array([[1, 2], [3, 4]])
assert_(eq(m.diagonal(), m._data.diagonal()))
assert_(eq(a.sum(), a._data.sum()))
assert_(eq(a.take([1, 2]), a._data.take([1, 2])))
assert_(eq(m.transpose(), m._data.transpose())) ```
Example 9
```def test_generic_methods(self):
a = array([1, 3, 2])
assert_equal(a.any(), a._data.any())
assert_equal(a.all(), a._data.all())
assert_equal(a.argmax(), a._data.argmax())
assert_equal(a.argmin(), a._data.argmin())
assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
assert_equal(a.conj(), a._data.conj())
assert_equal(a.conjugate(), a._data.conjugate())

m = array([[1, 2], [3, 4]])
assert_equal(m.diagonal(), m._data.diagonal())
assert_equal(a.sum(), a._data.sum())
assert_equal(a.take([1, 2]), a._data.take([1, 2]))
assert_equal(m.transpose(), m._data.transpose()) ```
Example 10
```def test_poly(self):
assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]),
[1, -3, -2, 6])

# From matlab docs
A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
assert_array_almost_equal(np.poly(A), [1, -6, -72, -27])

# Should produce real output for perfect conjugates
assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j])))
assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j,
1-2j, 1.+3.5j, 1-3.5j])))
assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j])))
assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j])))
assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j])))
assert_(np.isrealobj(np.poly([1j, -1j])))
assert_(np.isrealobj(np.poly([1, -1])))

assert_(np.iscomplexobj(np.poly([1j, -1.0000001j])))

np.random.seed(42)
a = np.random.randn(100) + 1j*np.random.randn(100)
assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a)))))) ```
Example 11
```def test_generic_methods(self):
a = array([1, 3, 2])
assert_equal(a.any(), a._data.any())
assert_equal(a.all(), a._data.all())
assert_equal(a.argmax(), a._data.argmax())
assert_equal(a.argmin(), a._data.argmin())
assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
assert_equal(a.conj(), a._data.conj())
assert_equal(a.conjugate(), a._data.conjugate())

m = array([[1, 2], [3, 4]])
assert_equal(m.diagonal(), m._data.diagonal())
assert_equal(a.sum(), a._data.sum())
assert_equal(a.take([1, 2]), a._data.take([1, 2]))
assert_equal(m.transpose(), m._data.transpose()) ```
Example 12
```def test_testArrayMethods(self):
a = array([1, 3, 2])
self.assertTrue(eq(a.any(), a._data.any()))
self.assertTrue(eq(a.all(), a._data.all()))
self.assertTrue(eq(a.argmax(), a._data.argmax()))
self.assertTrue(eq(a.argmin(), a._data.argmin()))
self.assertTrue(eq(a.choose(0, 1, 2, 3, 4),
a._data.choose(0, 1, 2, 3, 4)))
self.assertTrue(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
self.assertTrue(eq(a.conj(), a._data.conj()))
self.assertTrue(eq(a.conjugate(), a._data.conjugate()))
m = array([[1, 2], [3, 4]])
self.assertTrue(eq(m.diagonal(), m._data.diagonal()))
self.assertTrue(eq(a.sum(), a._data.sum()))
self.assertTrue(eq(a.take([1, 2]), a._data.take([1, 2])))
self.assertTrue(eq(m.transpose(), m._data.transpose())) ```
Example 13
```def test_generic_methods(self):
a = array([1, 3, 2])
assert_equal(a.any(), a._data.any())
assert_equal(a.all(), a._data.all())
assert_equal(a.argmax(), a._data.argmax())
assert_equal(a.argmin(), a._data.argmin())
assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
assert_equal(a.conj(), a._data.conj())
assert_equal(a.conjugate(), a._data.conjugate())

m = array([[1, 2], [3, 4]])
assert_equal(m.diagonal(), m._data.diagonal())
assert_equal(a.sum(), a._data.sum())
assert_equal(a.take([1, 2]), a._data.take([1, 2]))
assert_equal(m.transpose(), m._data.transpose()) ```
Example 14
```def test_poly(self):
assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]),
[1, -3, -2, 6])

# From matlab docs
A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
assert_array_almost_equal(np.poly(A), [1, -6, -72, -27])

# Should produce real output for perfect conjugates
assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j])))
assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j,
1-2j, 1.+3.5j, 1-3.5j])))
assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j])))
assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j])))
assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j])))
assert_(np.isrealobj(np.poly([1j, -1j])))
assert_(np.isrealobj(np.poly([1, -1])))

assert_(np.iscomplexobj(np.poly([1j, -1.0000001j])))

np.random.seed(42)
a = np.random.randn(100) + 1j*np.random.randn(100)
assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a)))))) ```
Example 15
```def test_testArrayMethods(self):
a = array([1, 3, 2])
assert_(eq(a.any(), a._data.any()))
assert_(eq(a.all(), a._data.all()))
assert_(eq(a.argmax(), a._data.argmax()))
assert_(eq(a.argmin(), a._data.argmin()))
assert_(eq(a.choose(0, 1, 2, 3, 4),
a._data.choose(0, 1, 2, 3, 4)))
assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
assert_(eq(a.conj(), a._data.conj()))
assert_(eq(a.conjugate(), a._data.conjugate()))
m = array([[1, 2], [3, 4]])
assert_(eq(m.diagonal(), m._data.diagonal()))
assert_(eq(a.sum(), a._data.sum()))
assert_(eq(a.take([1, 2]), a._data.take([1, 2])))
assert_(eq(m.transpose(), m._data.transpose())) ```
Example 16
```def test_generic_methods(self):
a = array([1, 3, 2])
assert_equal(a.any(), a._data.any())
assert_equal(a.all(), a._data.all())
assert_equal(a.argmax(), a._data.argmax())
assert_equal(a.argmin(), a._data.argmin())
assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
assert_equal(a.conj(), a._data.conj())
assert_equal(a.conjugate(), a._data.conjugate())

m = array([[1, 2], [3, 4]])
assert_equal(m.diagonal(), m._data.diagonal())
assert_equal(a.sum(), a._data.sum())
assert_equal(a.take([1, 2]), a._data.take([1, 2]))
assert_equal(m.transpose(), m._data.transpose()) ```
Example 17
```def qmat(self, modes=None):
""" Construct the covariance matrix for the Q function"""
if modes is None:
modes = list(range(self.nlen))

rows = np.reshape(modes, [-1, 1])
cols = np.reshape(modes, [1, -1])

sigmaq = np.concatenate(
(
np.concatenate(
(self.nmat[rows, cols], np.conjugate(self.mmat[rows, cols])), axis=1
),
np.concatenate(
(self.mmat[rows, cols], np.conjugate(self.nmat[rows, cols])), axis=1
),
),
axis=0,
) + np.identity(2 * len(modes))
return sigmaq ```
Example 18
```def test_squeezed_coherent(setup_backend, hbar, tol):
"""Test Wigner function for a squeezed coherent state
matches the analytic result"""
backend = setup_backend(1)
backend.prepare_coherent_state(np.abs(A), np.angle(A), 0)
backend.squeeze(R, PHI, 0)

state = backend.state()
W = state.wigner(0, XVEC, XVEC)
rot = rotm(PHI / 2)

# exact wigner function
alpha = A * np.cosh(R) - np.conjugate(A) * np.exp(1j * PHI) * np.sinh(R)
mu = np.array([alpha.real, alpha.imag]) * np.sqrt(2 * hbar)
cov = np.diag([np.exp(-2 * R), np.exp(2 * R)])
cov = np.dot(rot, np.dot(cov, rot.T)) * hbar / 2.0
Wexact = wigner(GRID, mu, cov)

assert np.allclose(W, Wexact, atol=0.01, rtol=0) ```
Example 19
```def spectralwhitening(stream):
"""
Apply spectral whitening to data.
Data is divided by its smoothed (Default: None) amplitude spectrum.
"""
stream2 = copy.deepcopy(stream)

for trace in arange(len(stream2)):
data = stream2[trace].data

n = len(data)
nfft = nextpow2(n)

spec = fft(data, nfft)
spec_ampl = sqrt(abs(multiply(spec, conjugate(spec))))

spec /= spec_ampl  # Do we need to do some smoothing here?
ret = real(ifft(spec, nfft)[:n])

stream2[trace].data = ret

return stream2 ```
Example 20
```def spectralwhitening_smooth(stream, N):
"""
Apply spectral whitening to data.
Data is divided by its smoothed (Default: None) amplitude spectrum.
"""
stream2 = copy.deepcopy(stream)

for trace in arange(len(stream2)):
data = stream2[trace].data

n = len(data)
nfft = nextpow2(n)

spec = fft(data, nfft)
spec_ampl = sqrt(abs(multiply(spec, conjugate(spec))))

spec_ampl = smooth(spec_ampl, N)

spec /= spec_ampl  # Do we need to do some smoothing here?
ret = real(ifft(spec, nfft)[:n])

stream2[trace].data = ret

return stream2 ```
Example 21
```def _gaussian_basis_change(qubits: Sequence[cirq.Qid],
transformation_matrix: numpy.ndarray,
initially_occupied_orbitals: Optional[Sequence[int]]
) -> cirq.OP_TREE:
n_qubits = len(qubits)

# Rearrange the transformation matrix because the OpenFermion routine
# expects it to describe annihilation operators rather than creation
# operators
left_block = transformation_matrix[:, :n_qubits]
right_block = transformation_matrix[:, n_qubits:]
transformation_matrix = numpy.block(
[numpy.conjugate(right_block), numpy.conjugate(left_block)])

decomposition, left_decomposition, _, left_diagonal = (
fermionic_gaussian_decomposition(transformation_matrix))

if (initially_occupied_orbitals is not None and
len(initially_occupied_orbitals) == 0):
# Starting with the vacuum state yields additional symmetry
circuit_description = list(reversed(decomposition))
else:
if initially_occupied_orbitals is None:
# The initial state is not a computational basis state so the
# phases left on the diagonal in the Givens decomposition matter
numpy.angle(left_diagonal[j])).on(qubits[j])
for j in range(n_qubits))
circuit_description = list(reversed(decomposition + left_decomposition))

yield _ops_from_givens_rotations_circuit_description(
qubits, circuit_description) ```
Example 22
```def rhf_func_generator(rhf_objective: RestrictedHartreeFockObjective,
initial_occ_vec: Optional[Union[None, np.ndarray]] = None,
get_opdm_func: Optional[bool] = False):
"""
Generate the energy, gradient, and unitary functions

:param rhf_objective: objective function object
:param initial_occ_vec: (optional) vector for occupation numbers of the alpha-opdm
:return: functions for unitary, energy, gradient (in that order)
"""
if initial_occ_vec is None:
initial_opdm = np.diag([1] * rhf_objective.nocc + [0] * rhf_objective.nvirt)
else:
initial_opdm = np.diag(initial_occ_vec)

def energy(params):
u = unitary(params)
final_opdm_aa = u @ initial_opdm @ np.conjugate(u).T
tenergy = rhf_objective.energy_from_opdm(final_opdm_aa)
return tenergy

u = unitary(params)
final_opdm_aa = u @ initial_opdm @ np.conjugate(u).T

def unitary(params):
kappa = rhf_params_to_matrix(params,
len(rhf_objective.occ) + len(rhf_objective.virt),
rhf_objective.occ, rhf_objective.virt)
return sp.linalg.expm(kappa)

def get_opdm(params):
u = unitary(params)
return u @ initial_opdm @ np.conjugate(u).T

if get_opdm_func:
Example 23
```def fidelity(state1, state2):
return abs(numpy.dot(state1, numpy.conjugate(state2)))**2 ```
Example 24
```def _rhoE_from_spamTuple(self, spamTuple):
assert(len(spamTuple) == 2)
if isinstance(spamTuple[0], _Label):
rholabel, elabel = spamTuple
# This calculator uses the convention that rho has shape (N,1)
rho = self.sos.get_prep(rholabel).todense()[:, None]
E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense()
[:, None]))  # convention: E has shape (1,N)
else:
# a "custom" spamLabel consisting of a pair of SPAMVec (or array)
#  objects: (prepVec, effectVec)
rho, Eraw = spamTuple
E = _np.conjugate(_np.transpose(Eraw))
return rho, E ```
Example 25
```def _rhoEs_from_spamTuples(self, rholabel, elabels):
#Note: no support for "custom" spamlabels...
# This calculator uses the convention that rho has shape (N,1)
rho = self.sos.get_prep(rholabel).todense()[:, None]
Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels]
Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1)))  # convention: Es has shape (len(elabels),N)
return rho, Es ```
Example 26
```def hermitian_to_real(self):
"""
Returns a ReportableQty that holds the real matrix
whose upper/lower triangle contains the real/imaginary parts
of the corresponding off-diagonal matrix elements of the
*Hermitian* matrix stored in this ReportableQty.

This is used for display purposes.  If this object doesn't
contain a Hermitian matrix, `ValueError` is raised.
"""
if _np.linalg.norm(self.value - _np.conjugate(self.value).T) > 1e-8:
raise ValueError("Contained value must be Hermitian!")

def _convert(A):
ret = _np.empty(A.shape, 'd')
for i in range(A.shape[0]):
ret[i, i] = A[i, i].real
for j in range(i + 1, A.shape[1]):
ret[i, j] = A[i, j].real
ret[j, i] = A[i, j].imag
return ret

v = _convert(self.value)
if self.has_eb():
eb = _convert(self.errbar)
return ReportableQty(v, eb, self.nonMarkovianEBs)
else:
return ReportableQty(v) ```
Example 27
```def adjoint_acton(self, state):
return DMStateRep(_np.dot(self.base.T, state.base))  # no conjugate b/c *real* data ```
Example 28
```def adjoint_acton(self, state):
return SVStateRep(_np.dot(_np.conjugate(self.base.T), state.base)) ```
Example 29
```def unitary_dagger(self):
return _np.conjugate(self.unitary.T) ```
Example 30
```def adjoint_acton(self, state):