Python numpy.float_() Examples

The following are 30 code examples of numpy.float_(). 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 also want to check out all available functions/classes of the module , or try the search function .
Example #1
 Source File: numpy_fenics.py    From torch-fenics with GNU General Public License v3.0 7 votes
```def fenics_to_numpy(fenics_var):
"""Convert FEniCS variable to numpy array"""
return fenics_var.values()

np_array = fenics_var.vector().get_local()
n_sub = fenics_var.function_space().num_sub_spaces()
# Reshape if function is multi-component
if n_sub != 0:
np_array = np.reshape(np_array, (len(np_array) // n_sub, n_sub))
return np_array

if isinstance(fenics_var, fenics.GenericVector):
return fenics_var.get_local()

return np.array(float(fenics_var), dtype=np.float_)

raise ValueError('Cannot convert ' + str(type(fenics_var))) ```
Example #2
```def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
"""
Returns true if all components of a and b are equal to given tolerances.

If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal.  The relative error rtol should
be positive and << 1.0 The absolute error atol comes into play for
those elements of b that are very small or zero; it says how small a
must be also.

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
return d.ravel() ```
Example #3
```def test_nan(self):
# nans should be passed through, not converted to infs
ps = [None, 1, -1, 2, -2, 'fro']
p_pos = [None, 1, 2, 'fro']

A = np.ones((2, 2))
A[0,1] = np.nan
for p in ps:
c = linalg.cond(A, p)
assert_(isinstance(c, np.float_))
assert_(np.isnan(c))

A = np.ones((3, 2, 2))
A[1,0,1] = np.nan
for p in ps:
c = linalg.cond(A, p)
assert_(np.isnan(c[1]))
if p in p_pos:
assert_(c[0] > 1e15)
assert_(c[2] > 1e15)
else:
assert_(not np.isnan(c[0]))
assert_(not np.isnan(c[2])) ```
Example #4
```def test_fromValue(self, datetime_series):

nans = Series(np.NaN, index=datetime_series.index)
assert nans.dtype == np.float_
assert len(nans) == len(datetime_series)

strings = Series('foo', index=datetime_series.index)
assert strings.dtype == np.object_
assert len(strings) == len(datetime_series)

d = datetime.now()
dates = Series(d, index=datetime_series.index)
assert dates.dtype == 'M8[ns]'
assert len(dates) == len(datetime_series)

# GH12336
# Test construction of categorical series from value
categorical = Series(0, index=datetime_series.index, dtype="category")
expected = Series(0, index=datetime_series.index).astype("category")
assert categorical.dtype == 'category'
assert len(categorical) == len(datetime_series)
tm.assert_series_equal(categorical, expected) ```
Example #5
```def testFrexp(self):
t1 = ones((3, 4, 5), chunk_size=2)
t2 = empty((3, 4, 5), dtype=np.float_, chunk_size=2)
op_type = type(t1.op)

o1, o2 = frexp(t1)

self.assertIs(o1.op, o2.op)
self.assertNotEqual(o1.dtype, o2.dtype)

o1, o2 = frexp(t1, t1)

self.assertIs(o1, t1)
self.assertIsNot(o1.inputs[0], t1)
self.assertIsInstance(o1.inputs[0].op, op_type)
self.assertIsNot(o2.inputs[0], t1)

o1, o2 = frexp(t1, t2, where=t1 > 0)

op_type = type(t2.op)
self.assertIs(o1, t2)
self.assertIsNot(o1.inputs[0], t1)
self.assertIsInstance(o1.inputs[0].op, op_type)
self.assertIsNot(o2.inputs[0], t1) ```
Example #6
```def testArrayProtocol(self):
arr = mt.ones((10, 20))

result = np.asarray(arr)
np.testing.assert_array_equal(result, np.ones((10, 20)))

arr2 = mt.ones((10, 20))

result = np.asarray(arr2, mt.bool_)
np.testing.assert_array_equal(result, np.ones((10, 20), dtype=np.bool_))

arr3 = mt.ones((10, 20)).sum()

result = np.asarray(arr3)
np.testing.assert_array_equal(result, np.asarray(200))

arr4 = mt.ones((10, 20)).sum()

result = np.asarray(arr4, dtype=np.float_)
np.testing.assert_array_equal(result, np.asarray(200, dtype=np.float_)) ```
Example #7
```def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
"""
Returns true if all components of a and b are equal to given tolerances.

If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal.  The relative error rtol should
be positive and << 1.0 The absolute error atol comes into play for
those elements of b that are very small or zero; it says how small a
must be also.

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
return d.ravel() ```
Example #8
```def almost(a, b, decimal=6, fill_value=True):
"""
Returns True if a and b are equal up to decimal places.

If fill_value is True, masked values considered equal. Otherwise,

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
return d.ravel() ```
Example #9
```def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
"""
Returns true if all components of a and b are equal to given tolerances.

If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal.  The relative error rtol should
be positive and << 1.0 The absolute error atol comes into play for
those elements of b that are very small or zero; it says how small a
must be also.

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
return d.ravel() ```
Example #10
```def almost(a, b, decimal=6, fill_value=True):
"""
Returns True if a and b are equal up to decimal places.

If fill_value is True, masked values considered equal. Otherwise,

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
return d.ravel() ```
Example #11
```def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
"""
Returns true if all components of a and b are equal to given tolerances.

If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal.  The relative error rtol should
be positive and << 1.0 The absolute error atol comes into play for
those elements of b that are very small or zero; it says how small a
must be also.

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
return d.ravel() ```
Example #12
```def almost(a, b, decimal=6, fill_value=True):
"""
Returns True if a and b are equal up to decimal places.

If fill_value is True, masked values considered equal. Otherwise,

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
return d.ravel() ```
Example #13
```def test_empty_tuple_index(self):
# Empty tuple index creates a view
a = np.array([1, 2, 3])
assert_equal(a[()], a)
assert_(a[()].base is a)
a = np.array(0)
assert_(isinstance(a[()], np.int_))

# Regression, it needs to fall through integer and fancy indexing
# cases, so need the with statement to ignore the non-integer error.
with warnings.catch_warnings():
warnings.filterwarnings('ignore', '', DeprecationWarning)
a = np.array([1.])
assert_(isinstance(a[0.], np.float_))

a = np.array([np.array(1)], dtype=object)
assert_(isinstance(a[0.], np.ndarray)) ```
Example #14
```def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
"""
Returns true if all components of a and b are equal to given tolerances.

If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal.  The relative error rtol should
be positive and << 1.0 The absolute error atol comes into play for
those elements of b that are very small or zero; it says how small a
must be also.

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
return d.ravel() ```
Example #15
```def almost(a, b, decimal=6, fill_value=True):
"""
Returns True if a and b are equal up to decimal places.

If fill_value is True, masked values considered equal. Otherwise,

"""
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
return d.ravel() ```
Example #16
```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 #17
 Source File: solution_classes.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes
```def __init__(self,  obj):

if isinstance(obj, SolutionPool):

self._P = obj.P
self._objvals = obj.objvals
self._solutions = obj.solutions

elif isinstance(obj, int):

assert obj >= 1
self._P = int(obj)
self._objvals = np.empty(0)
self._solutions = np.empty(shape = (0, self._P))

elif isinstance(obj, dict):

assert len(obj) == 2
objvals = np.copy(obj['objvals']).flatten().astype(dtype = np.float_)
solutions = np.copy(obj['solutions'])
n = objvals.size
if solutions.ndim == 2:
assert n in solutions.shape
if solutions.shape[1] == n and solutions.shape[0] != n:
solutions = np.transpose(solutions)
elif solutions.ndim == 1:
assert n == 1
solutions = np.reshape(solutions, (1, solutions.size))
else:
raise ValueError('solutions has more than 2 dimensions')

self._P = solutions.shape[1]
self._objvals = objvals
self._solutions = solutions

else:
raise ValueError('cannot initialize SolutionPool using %s object' % type(obj)) ```
Example #18
 Source File: solution_classes.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes
```def objvals(self, objvals):
if hasattr(objvals, "__len__"):
if len(objvals) > 0:
self._objvals = np.copy(list(objvals)).flatten().astype(dtype = np.float_)
elif len(objvals) == 0:
self._objvals = np.empty(0)
else:
self._objvals = float(objvals) ```
Example #19
 Source File: solution_classes.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes
```def add(self, new_objvals, new_solutions):
if isinstance(new_objvals, (np.ndarray, list)):
n = len(new_objvals)
self._objvals = np.append(self._objvals, np.array(new_objvals).astype(dtype = np.float_).flatten())
else:
n = 1
self._objvals = np.append(self._objvals, float(new_objvals))

new_solutions = np.reshape(new_solutions, (n, self._P))
self._solutions = np.append(self._solutions, new_solutions, axis = 0) ```
Example #20
 Source File: setup_functions.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes
```def setup_objective_functions(compute_loss, L0_reg_ind, C_0_nnz):

get_objval = lambda rho: compute_loss(rho) + np.sum(C_0_nnz * (rho[L0_reg_ind] != 0.0))
get_L0_norm = lambda rho: np.count_nonzero(rho[L0_reg_ind])
get_L0_penalty = lambda rho: np.sum(C_0_nnz * (rho[L0_reg_ind] != 0.0))
get_alpha = lambda rho: np.array(abs(rho[L0_reg_ind]) > 0.0, dtype = np.float_)
get_L0_penalty_from_alpha = lambda alpha: np.sum(C_0_nnz * alpha)

return (get_objval, get_L0_norm, get_L0_penalty, get_alpha, get_L0_penalty_from_alpha) ```
Example #21
```def __iter__(self):
lengths = np.array(
[(-l[0], -l[1], np.random.random()) for l in self.lengths],
dtype=[('l1', np.int_), ('l2', np.int_), ('rand', np.float_)]
)
indices = np.argsort(lengths, order=('l1', 'l2', 'rand'))
batches = [indices[i:i + self.batch_size]
for i in range(0, len(indices), self.batch_size)]
if self.shuffle:
np.random.shuffle(batches)
return iter([i for batch in batches for i in batch]) ```
Example #22
 Source File: numpy_fenics.py    From torch-fenics with GNU General Public License v3.0 5 votes
```def numpy_to_fenics(numpy_array, fenics_var_template):
"""Convert numpy array to FEniCS variable"""
if numpy_array.shape == (1,):
return type(fenics_var_template)(numpy_array[0])
else:
return type(fenics_var_template)(numpy_array)

np_n_sub = numpy_array.shape[-1]
np_size = np.prod(numpy_array.shape)

function_space = fenics_var_template.function_space()

u = type(fenics_var_template)(function_space)
fenics_size = u.vector().local_size()
fenics_n_sub = function_space.num_sub_spaces()

if (fenics_n_sub != 0 and np_n_sub != fenics_n_sub) or np_size != fenics_size:
err_msg = 'Cannot convert numpy array to Function:' \
' Wrong shape {} vs {}'.format(numpy_array.shape, u.vector().get_local().shape)
raise ValueError(err_msg)

if numpy_array.dtype != np.float_:
err_msg = 'The numpy array must be of type {}, ' \
'but got {}'.format(np.float_, numpy_array.dtype)
raise ValueError(err_msg)

u.vector().set_local(np.reshape(numpy_array, fenics_size))
u.vector().apply('insert')
return u

err_msg = 'Cannot convert numpy array to {}'.format(fenics_var_template)
raise ValueError(err_msg) ```
Example #23
```def test_float(self):
vals = nan_to_num(1.0)
assert_all(vals == 1.0)
assert_equal(type(vals), np.float_) ```
Example #24
```def test_ptp(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
(n, m) = X.shape
assert_equal(mx.ptp(), mx.compressed().ptp())
rows = np.zeros(n, np.float_)
cols = np.zeros(m, np.float_)
for k in range(m):
cols[k] = mX[:, k].compressed().ptp()
for k in range(n):
rows[k] = mX[k].compressed().ptp()
assert_(eq(mX.ptp(0), cols))
assert_(eq(mX.ptp(1), rows)) ```
Example #25
```def test_testAverage2(self):
# More tests of average.
w1 = [0, 1, 1, 1, 1, 0]
w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
x = arange(6, dtype=np.float_)
assert_equal(average(x, axis=0), 2.5)
assert_equal(average(x, axis=0, weights=w1), 2.5)
y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
assert_equal(average(y, axis=1),
[average(x, axis=0), average(x, axis=0) * 2.0])
assert_equal(average(y, None, weights=w2), 20. / 6.)
assert_equal(average(y, axis=0, weights=w2),
[0., 1., 2., 3., 4., 10.])
assert_equal(average(y, axis=1),
[average(x, axis=0), average(x, axis=0) * 2.0])
m1 = zeros(6)
m2 = [0, 0, 1, 1, 0, 0]
m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
m4 = ones(6)
m5 = [0, 1, 1, 1, 1, 1]
assert_equal(average(z, None), 20. / 6.)
assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
assert_equal(average(z, axis=1), [2.5, 5.0])
assert_equal(average(z, axis=0, weights=w2),
[0., 1., 99., 99., 4.0, 10.0]) ```
Example #26
```def test_scalar_return_type(self):
# Full scalar indices should return scalars and object
# arrays should not call PyArray_Return on their items
class Zero(object):
# The most basic valid indexing
def __index__(self):
return 0

z = Zero()

class ArrayLike(object):
# Simple array, should behave like the array
def __array__(self):
return np.array(0)

a = np.zeros(())
assert_(isinstance(a[()], np.float_))
a = np.zeros(1)
assert_(isinstance(a[z], np.float_))
a = np.zeros((1, 1))
assert_(isinstance(a[z, np.array(0)], np.float_))
assert_(isinstance(a[z, ArrayLike()], np.float_))

# And object arrays do not call it too often:
b = np.array(0)
a = np.array(0, dtype=object)
a[()] = b
assert_(isinstance(a[()], np.ndarray))
a = np.array([b, None])
assert_(isinstance(a[z], np.ndarray))
a = np.array([[b, None]])
assert_(isinstance(a[z, np.array(0)], np.ndarray))
assert_(isinstance(a[z, ArrayLike()], np.ndarray)) ```
Example #27
```def test_non_integer_sequence_multiplication(self):
# NumPy scalar sequence multiply should not work with non-integers
def mult(a, b):
return a * b

assert_raises(TypeError, mult, [1], np.float_(3))
# following should be OK
mult([1], np.int_(3)) ```
Example #28
```def test_empty_fancy_raises(self, attr):
# pd.DatetimeIndex is excluded, because it overrides getitem and should
# be tested separately.
empty_farr = np.array([], dtype=np.float_)
index = getattr(self, attr)
empty_index = index.__class__([])

assert index[[]].identical(empty_index)
# np.ndarray only accepts ndarray of int & bool dtypes, so should Index
pytest.raises(IndexError, index.__getitem__, empty_farr) ```
Example #29
```def test_map_int(self):
left = Series({'a': 1., 'b': 2., 'c': 3., 'd': 4})
right = Series({1: 11, 2: 22, 3: 33})

assert left.dtype == np.float_
assert issubclass(right.dtype.type, np.integer)

merged = left.map(right)
assert merged.dtype == np.float_
assert isna(merged['d'])
assert not isna(merged['c']) ```
Example #30
```def test_reindex_int(test_data):