# Python numpy.complex_() Examples

The following are 30 code examples for showing how to use numpy.complex_(). 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 test_against_cmath(self):
import cmath

points = [-1-1j, -1+1j, +1-1j, +1+1j]
name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
atol = 4*np.finfo(np.complex).eps
for func in self.funcs:
fname = func.__name__.split('.')[-1]
cname = name_map.get(fname, fname)
try:
cfunc = getattr(cmath, cname)
except AttributeError:
continue
for p in points:
a = complex(func(np.complex_(p)))
b = cfunc(p)
assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b)) ```
Example 2
```def test_against_cmath(self):
import cmath

points = [-1-1j, -1+1j, +1-1j, +1+1j]
name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
atol = 4*np.finfo(complex).eps
for func in self.funcs:
fname = func.__name__.split('.')[-1]
cname = name_map.get(fname, fname)
try:
cfunc = getattr(cmath, cname)
except AttributeError:
continue
for p in points:
a = complex(func(np.complex_(p)))
b = cfunc(p)
assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b)) ```
Example 3
```def test_against_cmath(self):
import cmath, sys

points = [-1-1j, -1+1j, +1-1j, +1+1j]
name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
atol = 4*np.finfo(np.complex).eps
for func in self.funcs:
fname = func.__name__.split('.')[-1]
cname = name_map.get(fname, fname)
try:
cfunc = getattr(cmath, cname)
except AttributeError:
continue
for p in points:
a = complex(func(np.complex_(p)))
b = cfunc(p)
assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s"%(fname, p, a, b)) ```
Example 4
```def get_matrix_from_channel(channel, symbol):
"""
Extract the numeric parameter matrix.

Args:
channel (matrix): a 4x4 symbolic matrix.
symbol (list): a symbol xi

Returns:
matrix: a 4x4 numeric matrix.

Each entry of the 4x4 symbolic input channel matrix is assumed to
be a polynomial of the form a1x1 + ... + anxn + c. The corresponding
entry in the output numeric matrix is ai.
"""
from sympy import Poly
n = channel.rows
M = numpy.zeros((n, n), dtype=numpy.complex_)
for (i, j) in itertools.product(range(n), range(n)):
M[i, j] = numpy.complex(
Poly(channel[i, j], symbol).coeff_monomial(symbol))
return M ```
Example 5
```def get_const_matrix_from_channel(channel, symbols):
"""
Extract the numeric constant matrix.

Args:
channel (matrix): a 4x4 symbolic matrix.
symbols (list): The full list [x1, ..., xn] of symbols
used in the matrix.

Returns:
matrix: a 4x4 numeric matrix.

Each entry of the 4x4 symbolic input channel matrix is assumed to
be a polynomial of the form a1x1 + ... + anxn + c. The corresponding
entry in the output numeric matrix is c.
"""
from sympy import Poly
n = channel.rows
M = numpy.zeros((n, n), dtype=numpy.complex_)
for (i, j) in itertools.product(range(n), range(n)):
M[i, j] = numpy.complex(
Poly(channel[i, j], symbols).coeff_monomial(1))
return M ```
Example 6
```def _default(obj):
"""
Convert dates and numpy objects in a json serializable format.
"""
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
elif isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16,
np.int32, np.int64, np.uint8, np.uint16,
np.uint32, np.uint64)):
return int(obj)
elif isinstance(obj, np.bool_):
return bool(obj)
elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64,
np.complex_, np.complex64, np.complex128)):
return float(obj)

raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") ```
Example 7
```def test_numpy_scalar(self):
dtype = self.dtype
if dtype is numpy.bool_:
x = dtype(True)
elif issubclass(dtype, numpy.complex_):
x = dtype(3.2 - 2.4j)
elif issubclass(dtype, numpy.integer):
x = dtype(3)
elif issubclass(dtype, numpy.floating):
x = dtype(3.2)
else:
assert False

y = cuda.to_cpu(x)
assert isinstance(y, numpy.ndarray)
assert y.shape == ()
assert y.dtype == dtype
assert y == x ```
Example 8
```def test_numpy_scalar(self):
dtype = self.dtype
if dtype is numpy.bool_:
x = dtype(True)
elif issubclass(dtype, numpy.complex_):
x = dtype(3.2 - 2.4j)
elif issubclass(dtype, numpy.integer):
x = dtype(3)
elif issubclass(dtype, numpy.floating):
x = dtype(3.2)
else:
assert False

y = cuda.to_gpu(x)
assert isinstance(y, cuda.ndarray)
assert y.shape == ()
assert y.dtype == dtype
assert y == x ```
Example 9
```def convert_esys_to_ndarray(esys_qutip):
"""Takes a qutip eigenstates array, as obtained with .eigenstates(), and converts it into a pure numpy array.

Parameters
----------
esys_qutip: ndarray of qutip.Qobj
as obtained from qutip `.eigenstates()`

Returns
-------
ndarray
converted eigenstate data
"""
evals_count = len(esys_qutip)
dimension = esys_qutip[0].shape[0]
esys_ndarray = np.empty((evals_count, dimension), dtype=np.complex_)
for index, eigenstate in enumerate(esys_qutip):
esys_ndarray[index] = eigenstate.full()[:, 0]
return esys_ndarray ```
Example 10
```def _zeropi_operator_in_product_basis(self, zeropi_operator, zeropi_evecs=None):
"""Helper method that converts a zeropi operator into one in the product basis.

Returns
-------
scipy.sparse.csc_matrix
operator written in the product basis
"""
zeropi_dim = self.zeropi_cutoff
zeta_dim = self.zeta_cutoff

if zeropi_evecs is None:
_, zeropi_evecs = self._zeropi.eigensys(evals_count=zeropi_dim)

op_eigen_basis = sparse.dia_matrix((zeropi_dim, zeropi_dim),
dtype=np.complex_)  # is this guaranteed to be zero?

op_zeropi = spec_utils.get_matrixelement_table(zeropi_operator, zeropi_evecs)
for n in range(zeropi_dim):
for m in range(zeropi_dim):
op_eigen_basis += op_zeropi[n, m] * op.hubbard_sparse(n, m, zeropi_dim)

return sparse.kron(op_eigen_basis, sparse.identity(zeta_dim, format='csc', dtype=np.complex_), format='csc') ```
Example 11
```def sparse_kinetic_mat(self):
"""
Kinetic energy portion of the Hamiltonian.
TODO: update this method to use single-variable operator methods

Returns
-------
scipy.sparse.csc_matrix
matrix representing the kinetic energy operator
"""
pt_count = self.grid.pt_count
dim_theta = 2 * self.ncut + 1
identity_phi = sparse.identity(pt_count, format='csc', dtype=np.complex_)
identity_theta = sparse.identity(dim_theta, format='csc', dtype=np.complex_)

kinetic_matrix_phi = self.grid.second_derivative_matrix(prefactor=-2.0 * self.ECJ)

diag_elements = 2.0 * self.ECS * np.square(np.arange(-self.ncut + self.ng, self.ncut + 1 + self.ng))
kinetic_matrix_theta = sparse.dia_matrix((diag_elements, [0]), shape=(dim_theta, dim_theta)).tocsc()

kinetic_matrix = (sparse.kron(kinetic_matrix_phi, identity_theta, format='csc')
+ sparse.kron(identity_phi, kinetic_matrix_theta, format='csc'))

kinetic_matrix -= 2.0 * self.ECS * self.dCJ * self.i_d_dphi_operator() * self.n_theta_operator()
return kinetic_matrix ```
Example 12
```def __init__(self, EJ1, EJ2, EJ3, ECJ1, ECJ2, ECJ3, ECg1, ECg2, ng1, ng2, flux, ncut,
truncated_dim=None):
self.EJ1 = EJ1
self.EJ2 = EJ2
self.EJ3 = EJ3
self.ECJ1 = ECJ1
self.ECJ2 = ECJ2
self.ECJ3 = ECJ3
self.ECg1 = ECg1
self.ECg2 = ECg2
self.ng1 = ng1
self.ng2 = ng2
self.flux = flux
self.ncut = ncut
self.truncated_dim = truncated_dim
self._sys_type = type(self).__name__
self._evec_dtype = np.complex_
self._default_grid = discretization.Grid1d(-np.pi / 2, 3 * np.pi / 2, 100)    # for plotting in phi_j basis
self._image_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'qubit_pngs/fluxqubit.png') ```
Example 13
```def _standard_normal(shape, randstate=np.random, dtype=np.float_):
"""Generates a standard normal numpy array of given shape and dtype, i.e.
this function is equivalent to `randstate.randn(*shape)` for real dtype and
`randstate.randn(*shape) + 1.j * randstate.randn(shape)` for complex dtype.

:param tuple shape: Shape of array to be returned
:param randstate: An instance of :class:`numpy.random.RandomState` (default is
``np.random``))
:param dtype: ``np.float_`` (default) or `np.complex_`

Returns
-------

A: An array of given shape and dtype with standard normal entries

"""
if dtype == np.float_:
return randstate.randn(*shape)
elif dtype == np.complex_:
return randstate.randn(*shape) + 1.j * randstate.randn(*shape)
else:
raise ValueError('{} is not a valid dtype.'.format(dtype)) ```
Example 14
```def _random_vec(sites, ldim, randstate=None, dtype=np.complex_):
"""Returns a random complex vector (normalized to ||x||_2 = 1) of shape
(ldim,) * sites, i.e. a pure state with local dimension `ldim` living on
`sites` sites.

:param sites: Number of local sites
:param ldim: Local ldimension
:param randstate: numpy.random.RandomState instance or None
:returns: numpy.ndarray of shape (ldim,) * sites

>>> psi = _random_vec(5, 2); psi.shape
(2, 2, 2, 2, 2)
>>> np.abs(np.vdot(psi, psi) - 1) < 1e-6
True
"""
shape = (ldim, ) * sites
psi = _randfuncs[dtype](shape, randstate=randstate)
psi /= np.linalg.norm(psi)
return psi ```
Example 15
```def _random_op(sites, ldim, hermitian=False, normalized=False, randstate=None,
dtype=np.complex_):
"""Returns a random operator  of shape (ldim,ldim) * sites with local
dimension `ldim` living on `sites` sites in global form.

:param sites: Number of local sites
:param ldim: Local ldimension
:param hermitian: Return only the hermitian part (default False)
:param normalized: Normalize to Frobenius norm=1 (default False)
:param randstate: numpy.random.RandomState instance or None
:returns: numpy.ndarray of shape (ldim,ldim) * sites

>>> A = _random_op(3, 2); A.shape
(2, 2, 2, 2, 2, 2)
"""
op = _randfuncs[dtype]((ldim**sites,) * 2, randstate=randstate)
if hermitian:
op += np.transpose(op).conj()
if normalized:
op /= np.linalg.norm(op)
return op.reshape((ldim,) * 2 * sites) ```
Example 16
```def test_operations_typesafety(nr_sites, local_dim, rank, rgen):
# create a real MPA
mpo1 = factory.random_mpa(nr_sites, (local_dim, local_dim), rank,
randstate=rgen, dtype=np.float_)
mpo2 = factory.random_mpa(nr_sites, (local_dim, local_dim), rank,
randstate=rgen, dtype=np.complex_)

assert mpo1.dtype == np.float_
assert mpo2.dtype == np.complex_

assert (mpo1 + mpo1).dtype == np.float_
assert (mpo1 + mpo2).dtype == np.complex_
assert (mpo2 + mpo1).dtype == np.complex_

assert mp.sumup((mpo1, mpo1)).dtype == np.float_
assert mp.sumup((mpo1, mpo2)).dtype == np.complex_
assert mp.sumup((mpo2, mpo1)).dtype == np.complex_

assert (mpo1 - mpo1).dtype == np.float_
assert (mpo1 - mpo2).dtype == np.complex_
assert (mpo2 - mpo1).dtype == np.complex_

mpo1 += mpo2
assert mpo1.dtype == np.complex_ ```
Example 17
```def test_inject_many(local_dim, rank, rgen):
"""Calling mp.inject() repeatedly vs. calling it with sequence arguments"""
mpa = factory.random_mpa(3, local_dim, rank, rgen, normalized=True,
dtype=np.complex_)
inj_lt = [factory._zrandn(s, rgen) for s in [(2, 3), (1,), (2, 2), (3, 2)]]

mpa_inj1 = mp.inject(mpa, 1, None, [inj_lt[0]])
mpa_inj1 = mp.inject(mpa_inj1, 2, 1, inj_lt[0])
mpa_inj1 = mp.inject(mpa_inj1, 4, None, [inj_lt[2]])
mpa_inj2 = mp.inject(mpa, [1, 2], [2, None], [inj_lt[0], [inj_lt[2]]])
mpa_inj3 = mp.inject(mpa, [1, 2], [2, 1], [inj_lt[0], inj_lt[2]])
assert_mpa_almost_equal(mpa_inj1, mpa_inj2, True)
assert_mpa_almost_equal(mpa_inj1, mpa_inj3, True)

inj_lt = [inj_lt[:2], inj_lt[2:]]
mpa_inj1 = mp.inject(mpa, 1, None, inj_lt[0])
mpa_inj1 = mp.inject(mpa_inj1, 4, inject_ten=inj_lt[1])
mpa_inj2 = mp.inject(mpa, [1, 2], None, inj_lt)
assert_mpa_almost_equal(mpa_inj1, mpa_inj2, True) ```
Example 18
```def test_inject_vs_chain(nr_sites, local_dim, rank, rgen):
"""Compare mp.inject() with mp.chain()"""
if nr_sites == 1:
return
mpa = factory.random_mpa(nr_sites // 2, local_dim, rank, rgen,
dtype=np.complex_, normalized=True)
pten = [factory._zrandn((local_dim,) * 2) for _ in range(nr_sites // 2)]
pten_mpa = mp.MPArray.from_kron(pten)

outer1 = mp.chain((pten_mpa, mpa))
outer2 = mp.inject(mpa, 0, inject_ten=pten)
assert_mpa_almost_equal(outer1, outer2, True)

outer1 = mp.chain((mpa, pten_mpa))
outer2 = mp.inject(mpa, [len(mpa)], [None], inject_ten=[pten])
assert_mpa_almost_equal(outer1, outer2, True) ```
Example 19
```def test_mult_mpo_scalar_normalization(nr_sites, local_dim, rank, rgen):
if nr_sites < 2:
# Re-normalization has no effect for nr_sites == 1. There is
# nothing more to test than :func:`test_mult_mpo_scalar`.
return

mpo = factory.random_mpa(nr_sites, (local_dim, local_dim), rank,
dtype=np.complex_, randstate=rgen)
op = mpo.to_array_global()
scalar = rgen.randn() + 1.j * rgen.randn()

center = nr_sites // 2
mpo.canonicalize(left=center - 1, right=center)
mpo_times_two = scalar * mpo

assert_array_almost_equal(scalar * op, mpo_times_two.to_array_global())
assert_correct_normalization(mpo_times_two, center - 1, center)

mpo *= scalar
assert_array_almost_equal(scalar * op, mpo.to_array_global())
assert_correct_normalization(mpo, center - 1, center) ```
Example 20
```def test_mppovm_pmf_as_array_pmps(
nr_sites, local_dim, rank, startsite, width, rgen):
if hasattr(local_dim, '__len__'):
pdims = [d for d, _ in local_dim]
mppaulis = mp.chain(
povm.MPPovm.from_local_povm(povm.pauli_povm(d), 1)
for d in pdims[startsite:startsite + width]
)
else:
pdims = local_dim
local_dim = (local_dim, local_dim)
mppaulis = povm.MPPovm.from_local_povm(povm.pauli_povm(pdims), width)
mppaulis = mppaulis.embed(nr_sites, startsite, pdims)
pmps = factory.random_mpa(nr_sites, local_dim, rank,
dtype=np.complex_, randstate=rgen, normalized=True)
rho = mpsmpo.pmps_to_mpo(pmps)
expect_rho = mppaulis.pmf_as_array(rho, 'mpdo')

for impl in ['default', 'pmps-ltr', 'pmps-symm']:
expect_pmps = mppaulis.pmf_as_array(pmps, 'pmps', impl=impl)
assert_array_almost_equal(expect_rho, expect_pmps, err_msg=impl) ```
Example 21
```def test_complex_array():
datum1 = qcel.Datum("complex array", "", np.arange(3, dtype=np.complex_) + 1j)
ans = {
"label": "complex array",
"units": "",
"data": [complex(0, 1), complex(1, 1), complex(2, 1)],
"numeric": True,
}

dicary = datum1.dict()
assert compare_recursive(ans, dicary, 9) ```
Example 22
```def create_data(qubit_num, measurement_num, sample_num, file_name=None):
measurements = np.empty([sample_num, measurement_num], dtype=np.float_)
states = np.empty([sample_num, 2**qubit_num], dtype=np.complex_)
projectors = [random_state(qubit_num) for _ in range(measurement_num)]
for i in range(sample_num):
sample = random_state(qubit_num)
states[i] = sample
measurements[i] = np.array([projection(p, sample) for p in projectors])
result = (measurements, states, projectors)
if file_name is not None:
f = gzip.open(io.data_path + file_name + ".plk.gz", 'wb')
cPickle.dump(result, f, protocol=2)
f.close()
return result ```
Example 23
```def test_return_dtype(self):
assert_equal(select(self.conditions, self.choices, 1j).dtype,
np.complex_)
# But the conditions need to be stronger then the scalar default
# if it is scalar.
choices = [choice.astype(np.int8) for choice in self.choices]
assert_equal(select(self.conditions, choices).dtype, np.int8)

d = np.array([1, 2, 3, np.nan, 5, 7])
m = np.isnan(d)
assert_equal(select([m], [d]), [0, 0, 0, np.nan, 0, 0]) ```
Example 24
```def test_complex_good(self):
vals = nan_to_num(1+1j)
assert_all(vals == 1+1j)
assert_equal(type(vals), np.complex_) ```
Example 25
```def test_complex_bad(self):
with np.errstate(divide='ignore', invalid='ignore'):
v = 1 + 1j
v += np.array(0+1.j)/0.
vals = nan_to_num(v)
# !! This is actually (unexpectedly) zero
assert_all(np.isfinite(vals))
assert_equal(type(vals), np.complex_) ```
Example 26
```def test_complex_bad2(self):
with np.errstate(divide='ignore', invalid='ignore'):
v = 1 + 1j
v += np.array(-1+1.j)/0.
vals = nan_to_num(v)
assert_all(np.isfinite(vals))
assert_equal(type(vals), np.complex_)
# Fixme
#assert_all(vals.imag > 1e10)  and assert_all(np.isfinite(vals))
# !! This is actually (unexpectedly) positive
# !! inf.  Comment out for now, and see if it
# !! changes
#assert_all(vals.real < -1e10) and assert_all(np.isfinite(vals)) ```
Example 27
```def test_power_complex(self):
x = np.array([1+2j, 2+3j, 3+4j])
assert_equal(x**0, [1., 1., 1.])
assert_equal(x**1, x)
assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j])
assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3])
assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4])
assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)])
assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2])
assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197,
(-117-44j)/15625])
assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j),
ncu.sqrt(3+4j)])
norm = 1./((x**14)[0])
assert_almost_equal(x**14 * norm,
[i * norm for i in [-76443+16124j, 23161315+58317492j,
5583548873 + 2465133864j]])

# Ticket #836
def assert_complex_equal(x, y):
assert_array_equal(x.real, y.real)
assert_array_equal(x.imag, y.imag)

for z in [complex(0, np.inf), complex(1, np.inf)]:
z = np.array([z], dtype=np.complex_)
with np.errstate(invalid="ignore"):
assert_complex_equal(z**1, z)
assert_complex_equal(z**2, z*z)
assert_complex_equal(z**3, z*z*z) ```
Example 28
```def test_description(self, expected_support, obj):
for datatype in expected_support:
assert obj.description(datatype) is not None

from StringIO import StringIO
s = StringIO()
assert obj.description(s) is None
assert obj.description(str) is None
assert obj.description(numpy.complex_) is None

# lists, tuples, dicts refer to numpy.object types and
# return a 'text' description - working as intended or bug?
assert obj.description(dict) is not None
assert obj.description(list) is not None
assert obj.description(tuple) is not None ```
Example 29
```def _set_dtype(self, dtype, union=False):
if np.issubdtype(dtype, np.complexfloating) \
or np.issubdtype(self.dtype, np.complexfloating):
self.dtype = np.complex_
else:
if not union or self.dtype != np.complex_:
self.dtype = np.float_ ```
Example 30
```def _get_dtype(dtype):