def is_circle(points, scale, verbose=True):
'''
Given a set of points, quickly determine if they represent
a circle or not.
'''
# make sure input is a numpy array
points = np.asanyarray(points)
scale = float(scale)
# can only be a circle if the first and last point are the
# same (AKA is a closed path)
if np.linalg.norm(points[0] - points[-1]) > tol.merge:
return None
box = points.ptp(axis=0)
# the bounding box size of the points
# check aspect ratio as an early exit if the path is not a circle
aspect = np.divide(*box)
if np.abs(aspect - 1.0) > tol.aspect_frac:
return None
# fit a circle with tolerance checks
CR = fit_circle_check(points, scale=scale)
if CR is None:
return None
# return the circle as three control points
control = angles_to_threepoint([0,np.pi*.5], *CR)
return control
python类ptp()的实例源码
def test_ptp(self):
a = [3, 4, 5, 10, -3, -5, 6.0]
assert_equal(np.ptp(a, axis=0), 15.0)
def print_confidence_interval(ci, tabs=''):
"""Pretty print confidence interval information"""
ci = list(ci)
ci += [np.ptp(ci)]
print(tabs + 'Value: {1:.04f}'.format(*ci))
print(tabs + '95% Confidence Interval: ({0:.04f}, {2:.04f})'.format(*ci))
print(tabs + '\tCI Width: {3:.05f}'.format(*ci))
def test_ptp(self):
a = [3, 4, 5, 10, -3, -5, 6.0]
assert_equal(np.ptp(a, axis=0), 15.0)
def ptp(a, axis=None, out=None):
"""
Range of values (maximum - minimum) along an axis.
The name of the function comes from the acronym for 'peak to peak'.
Parameters
----------
a : array_like
Input values.
axis : int, optional
Axis along which to find the peaks. By default, flatten the
array.
out : array_like
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output,
but the type of the output values will be cast if necessary.
Returns
-------
ptp : ndarray
A new array holding the result, unless `out` was
specified, in which case a reference to `out` is returned.
Examples
--------
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.ptp(x, axis=0)
array([2, 2])
>>> np.ptp(x, axis=1)
array([1, 1])
"""
return _wrapfunc(a, 'ptp', axis=axis, out=out)
def test_scalar(self):
"""
Should return 0 for all scalar
"""
x = scalar('x')
p = ptp(x)
f = theano.function([x], p)
y = numpy.asarray(rand() * 2000 - 1000, dtype=config.floatX)
result = f(y)
numpyResult = numpy.ptp(y)
self.assertTrue(numpy.array_equal(result, numpyResult))
def test_vector(self):
x = vector('x')
p = ptp(x, 0)
f = theano.function([x], p)
y = rand_ranged(-1000, 1000, [100])
result = f(y)
numpyResult = numpy.ptp(y, 0)
self.assertTrue(numpy.array_equal(result, numpyResult))
def test_matrix_first_axis(self):
x = matrix('x')
p = ptp(x, 1)
f = theano.function([x], p)
y = rand_ranged(-1000, 1000, [100, 100])
result = f(y)
numpyResult = numpy.ptp(y, 1)
self.assertTrue(numpy.array_equal(result, numpyResult))
def test_matrix_second_axis(self):
x = matrix('x')
p = ptp(x, 0)
f = theano.function([x], p)
y = rand_ranged(-1000, 1000, [100, 100])
result = f(y)
numpyResult = numpy.ptp(y, 0)
self.assertTrue(numpy.array_equal(result, numpyResult))
def test_matrix_neg_axis(self):
x = matrix('x')
p = ptp(x, -1)
f = theano.function([x], p)
y = rand_ranged(-1000, 1000, [100, 100])
result = f(y)
numpyResult = numpy.ptp(y, -1)
self.assertTrue(numpy.array_equal(result, numpyResult))
def test_interface(self):
x = matrix('x')
p = x.ptp(1)
f = theano.function([x], p)
y = rand_ranged(-1000, 1000, [100, 100])
result = f(y)
numpyResult = numpy.ptp(y, 1)
self.assertTrue(numpy.array_equal(result, numpyResult))
def has_constant(x):
"""
Parameters
----------
x: ndarray
Array to be checked for a constant (n,k)
Returns
-------
const : bool
Flag indicating whether x contains a constant or has column span with
a constant
loc : int
Column location of constant
"""
if np.any(np.all(x == 1, axis=0)):
loc = np.argwhere(np.all(x == 1, axis=0))
return True, int(loc)
if np.any((np.ptp(x, axis=0) == 0) & ~np.all(x == 0, axis=0)):
loc = np.any((np.ptp(x, axis=0) == 0) & ~np.all(x == 0, axis=0))
loc = np.argwhere(loc)
return True, int(loc)
n = x.shape[0]
aug_rank = matrix_rank(np.c_[np.ones((n, 1)), x])
rank = matrix_rank(x)
has_const = bool(aug_rank == rank)
loc = None
if has_const:
out = np.linalg.lstsq(x, np.ones((n, 1)))
beta = out[0].ravel()
loc = np.argmax(np.abs(beta) * x.var(0))
return has_const, loc
def test_ids(panel):
data = PanelData(panel)
eids = data.entity_ids
assert eids.shape == (77, 1)
assert len(np.unique(eids)) == 11
for i in range(0, len(eids), 7):
assert np.ptp(eids[i:i + 7]) == 0
assert np.all((eids[i + 8:] - eids[i]) != 0)
tids = data.time_ids
assert tids.shape == (77, 1)
assert len(np.unique(tids)) == 7
for i in range(0, 11):
assert np.ptp(tids[i::7]) == 0
def test_neighbors_accuracy_with_n_candidates():
# Checks whether accuracy increases as `n_candidates` increases.
n_candidates_values = np.array([.1, 50, 500])
n_samples = 100
n_features = 10
n_iter = 10
n_points = 5
rng = np.random.RandomState(42)
accuracies = np.zeros(n_candidates_values.shape[0], dtype=float)
X = rng.rand(n_samples, n_features)
for i, n_candidates in enumerate(n_candidates_values):
lshf = LSHForest(n_candidates=n_candidates)
ignore_warnings(lshf.fit)(X)
for j in range(n_iter):
query = X[rng.randint(0, n_samples)].reshape(1, -1)
neighbors = lshf.kneighbors(query, n_neighbors=n_points,
return_distance=False)
distances = pairwise_distances(query, X, metric='cosine')
ranks = np.argsort(distances)[0, :n_points]
intersection = np.intersect1d(ranks, neighbors).shape[0]
ratio = intersection / float(n_points)
accuracies[i] = accuracies[i] + ratio
accuracies[i] = accuracies[i] / float(n_iter)
# Sorted accuracies should be equal to original accuracies
assert_true(np.all(np.diff(accuracies) >= 0),
msg="Accuracies are not non-decreasing.")
# Highest accuracy should be strictly greater than the lowest
assert_true(np.ptp(accuracies) > 0,
msg="Highest accuracy is not strictly greater than lowest.")
def test_neighbors_accuracy_with_n_estimators():
# Checks whether accuracy increases as `n_estimators` increases.
n_estimators = np.array([1, 10, 100])
n_samples = 100
n_features = 10
n_iter = 10
n_points = 5
rng = np.random.RandomState(42)
accuracies = np.zeros(n_estimators.shape[0], dtype=float)
X = rng.rand(n_samples, n_features)
for i, t in enumerate(n_estimators):
lshf = LSHForest(n_candidates=500, n_estimators=t)
ignore_warnings(lshf.fit)(X)
for j in range(n_iter):
query = X[rng.randint(0, n_samples)].reshape(1, -1)
neighbors = lshf.kneighbors(query, n_neighbors=n_points,
return_distance=False)
distances = pairwise_distances(query, X, metric='cosine')
ranks = np.argsort(distances)[0, :n_points]
intersection = np.intersect1d(ranks, neighbors).shape[0]
ratio = intersection / float(n_points)
accuracies[i] = accuracies[i] + ratio
accuracies[i] = accuracies[i] / float(n_iter)
# Sorted accuracies should be equal to original accuracies
assert_true(np.all(np.diff(accuracies) >= 0),
msg="Accuracies are not non-decreasing.")
# Highest accuracy should be strictly greater than the lowest
assert_true(np.ptp(accuracies) > 0,
msg="Highest accuracy is not strictly greater than lowest.")
def test_ptp(self):
a = [3, 4, 5, 10, -3, -5, 6.0]
assert_equal(np.ptp(a, axis=0), 15.0)
def ptp(a, axis=None, out=None):
"""
Range of values (maximum - minimum) along an axis.
The name of the function comes from the acronym for 'peak to peak'.
Parameters
----------
a : array_like
Input values.
axis : int, optional
Axis along which to find the peaks. By default, flatten the
array.
out : array_like
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output,
but the type of the output values will be cast if necessary.
Returns
-------
ptp : ndarray
A new array holding the result, unless `out` was
specified, in which case a reference to `out` is returned.
Examples
--------
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.ptp(x, axis=0)
array([2, 2])
>>> np.ptp(x, axis=1)
array([1, 1])
"""
try:
ptp = a.ptp
except AttributeError:
return _wrapit(a, 'ptp', axis, out)
return ptp(axis, out)
def ptp(a, axis=None, out=None):
"""
Range of values (maximum - minimum) along an axis.
The name of the function comes from the acronym for 'peak to peak'.
Parameters
----------
a : array_like
Input values.
axis : int, optional
Axis along which to find the peaks. By default, flatten the
array.
out : array_like
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output,
but the type of the output values will be cast if necessary.
Returns
-------
ptp : ndarray
A new array holding the result, unless `out` was
specified, in which case a reference to `out` is returned.
Examples
--------
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.ptp(x, axis=0)
array([2, 2])
>>> np.ptp(x, axis=1)
array([1, 1])
"""
try:
ptp = a.ptp
except AttributeError:
return _wrapit(a, 'ptp', axis, out)
return ptp(axis, out)
def _plot_histogram(params):
"""Function for plotting histogram of peak-to-peak values."""
import matplotlib.pyplot as plt
epochs = params['epochs']
p2p = np.ptp(epochs.get_data(), axis=2)
types = list()
data = list()
if 'eeg' in params['types']:
eegs = np.array([p2p.T[i] for i,
x in enumerate(params['types']) if x == 'eeg'])
data.append(eegs.ravel())
types.append('eeg')
if 'mag' in params['types']:
mags = np.array([p2p.T[i] for i,
x in enumerate(params['types']) if x == 'mag'])
data.append(mags.ravel())
types.append('mag')
if 'grad' in params['types']:
grads = np.array([p2p.T[i] for i,
x in enumerate(params['types']) if x == 'grad'])
data.append(grads.ravel())
types.append('grad')
params['histogram'] = plt.figure()
scalings = _handle_default('scalings')
units = _handle_default('units')
titles = _handle_default('titles')
colors = _handle_default('color')
for idx in range(len(types)):
ax = plt.subplot(len(types), 1, idx + 1)
plt.xlabel(units[types[idx]])
plt.ylabel('count')
color = colors[types[idx]]
rej = None
if epochs.reject is not None and types[idx] in epochs.reject.keys():
rej = epochs.reject[types[idx]] * scalings[types[idx]]
rng = [0., rej * 1.1]
else:
rng = None
plt.hist(data[idx] * scalings[types[idx]], bins=100, color=color,
range=rng)
if rej is not None:
ax.plot((rej, rej), (0, ax.get_ylim()[1]), color='r')
plt.title(titles[types[idx]])
params['histogram'].suptitle('Peak-to-peak histogram', y=0.99)
params['histogram'].subplots_adjust(hspace=0.6)
try:
params['histogram'].show(warn=False)
except Exception:
pass
if params['fig_proj'] is not None:
params['fig_proj'].canvas.draw()
def relim_axes(axes, percent=20):
"""
Generate new axes for a matplotlib axes based on the collections present.
:param axes:
The matplotlib axes.
:param percent: [optional]
The percent of the data to extend past the minimum and maximum data
points.
:returns:
A two-length tuple containing the lower and upper limits in the x- and
y-axis, respectively.
"""
data = np.vstack([item.get_offsets() for item in axes.collections \
if isinstance(item, PathCollection)])
if data.size == 0:
return (None, None)
data = data.reshape(-1, 2)
x, y = data[:,0], data[:, 1]
# Only use finite values.
finite = np.isfinite(x*y)
x, y = x[finite], y[finite]
if x.size > 1:
xlim = [
np.min(x) - np.ptp(x) * percent/100.,
np.max(x) + np.ptp(x) * percent/100.,
]
elif x.size == 0:
xlim = None
else:
xlim = (x[0] - 1, x[0] + 1)
if y.size > 1:
ylim = [
np.min(y) - np.ptp(y) * percent/100.,
np.max(y) + np.ptp(y) * percent/100.
]
elif y.size == 0:
ylim = None
else:
ylim = (y[0] - 1, y[0] + 1)
axes.set_xlim(xlim)
axes.set_ylim(ylim)
return (xlim, ylim)