本文整理汇总了Python中numpy.isclose方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.isclose方法的具体用法?Python numpy.isclose怎么用?Python numpy.isclose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.isclose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: color_overlap
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def color_overlap(color1, *args):
'''
color_overlap(color1, color2...) yields the rgba value associated with overlaying color2 on top
of color1 followed by any additional colors (overlaid left to right). This respects alpha
values when calculating the results.
Note that colors may be lists of colors, in which case a matrix of RGBA values is yielded.
'''
args = list(args)
args.insert(0, color1)
rgba = np.asarray([0.5,0.5,0.5,0])
for c in args:
c = to_rgba(c)
a = c[...,3]
a0 = rgba[...,3]
if np.isclose(a0, 0).all(): rgba = np.ones(rgba.shape) * c
elif np.isclose(a, 0).all(): continue
else: rgba = times(a, c) + times(1-a, rgba)
return rgba
示例2: point_in_segment
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def point_in_segment(ac, b, atol=1e-8):
'''
point_in_segment((a,b), c) yields True if point x is in segment (a,b) and False otherwise. Note
that this differs from point_on_segment in that a point that if c is equal to a or b it is
considered 'on' but not 'in' the segment.
The option atol can be given and is used only to test for difference from 0; by default it is
1e-8.
'''
(a,c) = ac
abc = [np.asarray(u) for u in (a,b,c)]
if any(len(u.shape) > 1 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc]
else: (a,b,c) = abc
vab = b - a
vbc = c - b
vac = c - a
dab = np.sqrt(np.sum(vab**2, axis=0))
dbc = np.sqrt(np.sum(vbc**2, axis=0))
dac = np.sqrt(np.sum(vac**2, axis=0))
return (np.isclose(dab + dbc - dac, 0, atol=atol) &
~np.isclose(dac - dab, 0, atol=atol) &
~np.isclose(dac - dbc, 0, atol=atol))
示例3: _retinotopic_field_sign_triangles
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def _retinotopic_field_sign_triangles(m, retinotopy):
t = m.tess if isinstance(m, geo.Mesh) or isinstance(m, geo.Topology) else m
# get the polar angle and eccen data as a complex number in degrees
if pimms.is_str(retinotopy):
(x,y) = as_retinotopy(retinotopy_data(m, retinotopy), 'geographical')
elif retinotopy is Ellipsis:
(x,y) = as_retinotopy(retinotopy_data(m, 'any'), 'geographical')
else:
(x,y) = as_retinotopy(retinotopy, 'geographical')
# Okay, now we want to make some coordinates...
coords = np.asarray([x, y])
us = coords[:, t.indexed_faces[1]] - coords[:, t.indexed_faces[0]]
vs = coords[:, t.indexed_faces[2]] - coords[:, t.indexed_faces[0]]
(us,vs) = [np.concatenate((xs, np.full((1, t.face_count), 0.0))) for xs in [us,vs]]
xs = np.cross(us, vs, axis=0)[2]
xs[np.isclose(xs, 0)] = 0
return np.sign(xs)
示例4: calc_anchors
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def calc_anchors(preregistration_map, model, model_hemi,
scale=1, sigma=Ellipsis, radius_weight=0, field_sign_weight=0,
invert_rh_field_sign=False):
'''
calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:
@ invert_rh_field_sign May be set to True (default is False) to indicate that the right
hemisphere's field signs will be incorrect relative to the model; this generally should be
used whenever invert_rh_angle is also set to True.
'''
wgts = preregistration_map.prop('weight')
rads = preregistration_map.prop('radius')
if np.isclose(radius_weight, 0): radius_weight = 0
ancs = retinotopy_anchors(preregistration_map, model,
polar_angle='polar_angle',
eccentricity='eccentricity',
radius='radius',
weight=wgts, weight_min=0, # taken care of already
radius_weight=radius_weight, field_sign_weight=field_sign_weight,
scale=scale,
invert_field_sign=(model_hemi == 'rh' and invert_rh_field_sign),
**({} if sigma is Ellipsis else {'sigma':sigma}))
return ancs
示例5: parameters
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def parameters(params):
'''
mdl.parameters is a persistent map of the parameters for the given SchiraModel object mdl.
'''
if not pimms.is_pmap(params): params = pyr.pmap(params)
# do the translations that we need...
scale = params['scale']
if pimms.is_number(scale):
params = params.set('scale', (scale, scale))
elif not is_tuple(scale):
params = params.set('scale', tuple(scale))
shear = params['shear']
if pimms.is_number(shear) and np.isclose(shear, 0):
params = params.set('shear', ((1, 0), (0, 1)))
elif shear[0][0] != 1 or shear[1][1] != 1:
raise RuntimeError('shear matrix diagonal elements must be 1!')
elif not is_tuple(shear) or not all(is_tuple(s) for s in shear):
params.set('shear', tuple([tuple(s) for s in shear]))
center = params['center']
if pimms.is_number(center) and np.isclose(center, 0):
params = params.set('center', (0.0, 0.0))
return pimms.persist(params, depth=None)
示例6: splrep
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def splrep(coordinates, t, order, weights, smoothing, periodic):
from scipy import interpolate
(x,y) = coordinates
# we need to skip anything where t[i] and t[i+1] are too close
wh = np.where(np.isclose(np.diff(t), 0))[0]
if len(wh) > 0:
(t,x,y) = [np.array(u) for u in (t,x,y)]
ii = np.arange(len(t))
for i in reversed(wh):
ii[i+1:-1] = ii[i+2:]
for u in (t,x,y):
u[i] = np.mean(u[i:i+2])
ii = ii[:-len(wh)]
(t,x,y) = [u[ii] for u in (t,x,y)]
xtck = interpolate.splrep(t, x, k=order, s=smoothing, w=weights, per=periodic)
ytck = interpolate.splrep(t, y, k=order, s=smoothing, w=weights, per=periodic)
return tuple([tuple([pimms.imm_array(u) for u in tck])
for tck in (xtck,ytck)])
示例7: test_circuit_generation_and_accuracy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def test_circuit_generation_and_accuracy():
for dim in range(2, 10):
qubits = cirq.LineQubit.range(dim)
u_generator = numpy.random.random(
(dim, dim)) + 1j * numpy.random.random((dim, dim))
u_generator = u_generator - numpy.conj(u_generator).T
assert numpy.allclose(-1 * u_generator, numpy.conj(u_generator).T)
unitary = scipy.linalg.expm(u_generator)
circuit = cirq.Circuit()
circuit.append(optimal_givens_decomposition(qubits, unitary))
fermion_generator = QubitOperator(()) * 0.0
for i, j in product(range(dim), repeat=2):
fermion_generator += jordan_wigner(
FermionOperator(((i, 1), (j, 0)), u_generator[i, j]))
true_unitary = scipy.linalg.expm(
get_sparse_operator(fermion_generator).toarray())
assert numpy.allclose(true_unitary.conj().T.dot(true_unitary),
numpy.eye(2 ** dim, dtype=complex))
test_unitary = cirq.unitary(circuit)
assert numpy.isclose(
abs(numpy.trace(true_unitary.conj().T.dot(test_unitary))), 2 ** dim)
示例8: get_matrix_of_eigs
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def get_matrix_of_eigs(w: np.ndarray) -> np.ndarray:
"""
Transform the eigenvalues for getting the gradient
.. math:
f(w) \rightarrow \frac{e^{i (\lambda_{i} - \lambda_{j})}{i (\lambda_{i} - \lambda_{j})}
:param w: eigenvalues of C-matrix
:return: new array of transformed eigenvalues
"""
transform_eigs = np.zeros((w.shape[0], w.shape[0]),
dtype=np.complex128)
for i, j in product(range(w.shape[0]), repeat=2):
if np.isclose(abs(w[i] - w[j]), 0):
transform_eigs[i, j] = 1
else:
transform_eigs[i, j] = (np.exp(1j * (w[i] - w[j])) - 1) / (
1j * (w[i] - w[j]))
return transform_eigs
示例9: test_get_matrix_of_eigs
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def test_get_matrix_of_eigs():
"""
Generate the matrix of [exp(i (li - lj)) - 1] / (i(li - lj)
:return:
"""
lam_vals = np.random.randn(4) + 1j * np.random.randn(4)
mat_eigs = np.zeros((lam_vals.shape[0],
lam_vals.shape[0]),
dtype=np.complex128)
for i, j in product(range(lam_vals.shape[0]), repeat=2):
if np.isclose(abs(lam_vals[i] - lam_vals[j]), 0):
mat_eigs[i, j] = 1
else:
mat_eigs[i, j] = (np.exp(1j * (lam_vals[i] - lam_vals[j])) - 1) / (
1j * (lam_vals[i] - lam_vals[j]))
test_mat_eigs = get_matrix_of_eigs(lam_vals)
assert np.allclose(test_mat_eigs, mat_eigs)
示例10: test_rhf_func_gen
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def test_rhf_func_gen():
rhf_objective, molecule, parameters, _, _ = make_h6_1_3()
ansatz, energy, _ = rhf_func_generator(rhf_objective)
assert np.isclose(molecule.hf_energy, energy(parameters))
ansatz, energy, _, opdm_func = rhf_func_generator(
rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True)
assert np.isclose(molecule.hf_energy, energy(parameters))
test_opdm = opdm_func(parameters)
u = ansatz(parameters)
initial_opdm = np.diag([1] * 3 + [0] * 3)
final_odpm = u @ initial_opdm @ u.T
assert np.allclose(test_opdm, final_odpm)
result = rhf_minimization(rhf_objective, initial_guess=parameters)
assert np.allclose(result.x, parameters)
示例11: params
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def params(self) -> Iterable[sympy.Symbol]:
"""The parameters of the ansatz."""
for i in range(self.iterations):
for p in range(len(self.qubits)):
if (self.include_all_z or not
numpy.isclose(self.hamiltonian.one_body[p, p], 0)):
yield LetterWithSubscripts('U', p, i)
for p, q in itertools.combinations(range(len(self.qubits)), 2):
if (self.include_all_xxyy or not
numpy.isclose(self.hamiltonian.one_body[p, q].real, 0)):
yield LetterWithSubscripts('T', p, q, i)
if (self.include_all_yxxy or not
numpy.isclose(self.hamiltonian.one_body[p, q].imag, 0)):
yield LetterWithSubscripts('W', p, q, i)
if (self.include_all_cz or not
numpy.isclose(self.hamiltonian.two_body[p, q], 0)):
yield LetterWithSubscripts('V', p, q, i)
示例12: _build_normalising_constant
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def _build_normalising_constant(self, re_eval=False):
balanced_tree = True
first_constant_value = None
normalising_constant = {}
for _base_leaf in self._domain_values:
constant_value = 0.0
for _target_leaf in self._domain_values:
constant_value += self._get_prob(_base_leaf, _target_leaf)
normalising_constant[_base_leaf] = constant_value
if first_constant_value is None:
first_constant_value = constant_value
elif not np.isclose(constant_value, first_constant_value):
balanced_tree = False
# If the tree is balanced, we can eliminate the doubling factor
if balanced_tree and not re_eval:
self._balanced_tree = True
return self._build_normalising_constant(True)
return normalising_constant
示例13: set_bounds
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def set_bounds(self, lower, upper):
"""Sets the lower and upper bounds of the mechanism.
For the folded geometric mechanism, `lower` and `upper` must be integer or half-integer -valued. Must have
`lower` <= `upper`.
Parameters
----------
lower : int or float
The lower bound of the mechanism.
upper : int or float
The upper bound of the mechanism.
Returns
-------
self : class
"""
if not np.isclose(2 * lower, np.round(2 * lower)) or not np.isclose(2 * upper, np.round(2 * upper)):
raise ValueError("Bounds must be integer or half-integer floats")
return super().set_bounds(lower, upper)
示例14: set_dimension
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def set_dimension(self, vector_dim):
"""Sets the dimension `vector_dim` of the domain of the mechanism.
This dimension relates to the size of the input vector of the function being considered by the mechanism. This
corresponds to the size of the random vector produced by the mechanism.
Parameters
----------
vector_dim : int
Function input dimension.
Returns
-------
self : class
"""
if not isinstance(vector_dim, Real) or not np.isclose(vector_dim, int(vector_dim)):
raise TypeError("d must be integer-valued")
if not vector_dim >= 1:
raise ValueError("d must be strictly positive")
self._vector_dim = int(vector_dim)
return self
示例15: _print_detection_eval_metrics
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isclose [as 别名]
def _print_detection_eval_metrics(self, coco_eval):
IoU_lo_thresh = 0.5
IoU_hi_thresh = 0.95
def _get_thr_ind(coco_eval, thr):
ind = np.where((coco_eval.params.iouThrs > thr - 1e-5) &
(coco_eval.params.iouThrs < thr + 1e-5))[0][0]
iou_thr = coco_eval.params.iouThrs[ind]
assert np.isclose(iou_thr, thr)
return ind
ind_lo = _get_thr_ind(coco_eval, IoU_lo_thresh)
ind_hi = _get_thr_ind(coco_eval, IoU_hi_thresh)
# precision has dims (iou, recall, cls, area range, max dets)
# area range index 0: all area ranges
# max dets index 2: 100 per image
precision = \
coco_eval.eval['precision'][ind_lo:(ind_hi + 1), :, :, 0, 2]
ap_default = np.mean(precision[precision > -1])
print(('~~~~ Mean and per-category AP @ IoU=[{:.2f},{:.2f}] '
'~~~~').format(IoU_lo_thresh, IoU_hi_thresh))
print('{:.1f}'.format(100 * ap_default))
for cls_ind, cls in enumerate(self.classes):
if cls == '__background__':
continue
# minus 1 because of __background__
precision = coco_eval.eval['precision'][ind_lo:(ind_hi + 1), :, cls_ind - 1, 0, 2]
ap = np.mean(precision[precision > -1])
print('{:.1f}'.format(100 * ap))
print('~~~~ Summary metrics ~~~~')
coco_eval.summarize()
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:34,代码来源:coco.py