The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.
Example 1
def compute_group(cls, data, scales, **params):
n = len(data)
if n < 3:
return pd.DataFrame()
weight = data.get('weight')
if params['trim']:
range_y = data['y'].min(), data['y'].max()
else:
range_y = scales.y.dimension()
dens = compute_density(data['y'], weight, range_y, **params)
dens['y'] = dens['x']
dens['x'] = np.mean([data['x'].min(), data['x'].max()])
# Compute width if x has multiple values
if len(np.unique(data['x'])) > 1:
dens['width'] = np.ptp(data['x']) * 0.9
return dens
Example 2
def draw_group(data, panel_params, coord, ax, **params):
data = coord.transform(data, panel_params)
fill = to_rgba(data['fill'], data['alpha'])
color = to_rgba(data['color'], data['alpha'])
ranges = coord.range(panel_params)
# For perfect circles the width/height of the circle(ellipse)
# should factor in the dimensions of axes
bbox = ax.get_window_extent().transformed(
ax.figure.dpi_scale_trans.inverted())
ax_width, ax_height = bbox.width, bbox.height
factor = ((ax_width/ax_height) *
np.ptp(ranges.y)/np.ptp(ranges.x))
size = data.loc[0, 'binwidth'] * params['dotsize']
offsets = data['stackpos'] * params['stackratio']
if params['binaxis'] == 'x':
width, height = size, size*factor
xpos, ypos = data['x'], data['y'] + height*offsets
elif params['binaxis'] == 'y':
width, height = size/factor, size
xpos, ypos = data['x'] + width*offsets, data['y']
circles = []
for xy in zip(xpos, ypos):
patch = mpatches.Ellipse(xy, width=width, height=height)
circles.append(patch)
coll = mcoll.PatchCollection(circles,
edgecolors=color,
facecolors=fill)
ax.add_collection(coll)
Example 3
def fit(self, X, y=None):
"""Fit it.
Parameters
----------
X : array, shape (n_epochs, n_times)
The data for one channel.
y : None
Redundant. Necessary to be compatible with sklearn
API.
"""
deltas = np.ptp(X, axis=1)
self.deltas_ = deltas
keep = deltas <= self.thresh
# XXX: actually go over all the folds before setting the min
# in skopt. Otherwise, may confuse skopt.
if self.thresh < np.min(np.ptp(X, axis=1)):
assert np.sum(keep) == 0
keep = deltas <= np.min(np.ptp(X, axis=1))
self.mean_ = _slicemean(X, keep, axis=0)
return self
Example 4
def _vote_bad_epochs(self, epochs):
"""Each channel votes for an epoch as good or bad.
Parameters
----------
epochs : instance of mne.Epochs
The epochs object for which bad epochs must be found.
"""
n_epochs = len(epochs)
picks = _handle_picks(info=epochs.info, picks=self.picks)
drop_log = np.zeros((n_epochs, len(epochs.ch_names)))
bad_sensor_counts = np.zeros((len(epochs), ))
ch_names = [epochs.ch_names[p] for p in picks]
deltas = np.ptp(epochs.get_data()[:, picks], axis=-1).T
threshes = [self.threshes_[ch_name] for ch_name in ch_names]
for ch_idx, (delta, thresh) in enumerate(zip(deltas, threshes)):
bad_epochs_idx = np.where(delta > thresh)[0]
# TODO: combine for different ch types
bad_sensor_counts[bad_epochs_idx] += 1
drop_log[bad_epochs_idx, picks[ch_idx]] = 1
return drop_log, bad_sensor_counts
Example 5
def extend_limits(values, fraction=0.10, tolerance=1e-2):
""" Extend the values of a list by a fractional amount """
values = np.array(values)
finite_indices = np.isfinite(values)
if np.sum(finite_indices) == 0:
raise ValueError("no finite values provided")
lower_limit, upper_limit = np.min(values[finite_indices]), np.max(values[finite_indices])
ptp_value = np.ptp([lower_limit, upper_limit])
new_limits = lower_limit - fraction * ptp_value, ptp_value * fraction + upper_limit
if np.abs(new_limits[0] - new_limits[1]) < tolerance:
if np.abs(new_limits[0]) < tolerance:
# Arbitrary limits, since we"ve just been passed zeros
offset = 1
else:
offset = np.abs(new_limits[0]) * fraction
new_limits = new_limits[0] - offset, offset + new_limits[0]
return np.array(new_limits)
Example 6
def calculate_fractional_overlap(interest_range, comparison_range):
"""
Calculate how much of the range of interest overlaps with the comparison
range.
"""
if not (interest_range[-1] >= comparison_range[0] \
and comparison_range[-1] >= interest_range[0]):
return 0.0 # No overlap
elif (interest_range[0] >= comparison_range[0] \
and interest_range[-1] <= comparison_range[-1]):
return 1.0 # Total overlap
else:
# Some overlap. Which side?
if interest_range[0] < comparison_range[0]:
# Left hand side
width = interest_range[-1] - comparison_range[0]
else:
# Right hand side
width = comparison_range[-1] - interest_range[0]
return width/np.ptp(interest_range) # Fractional overlap
Example 7
def update_roi_xy_size(self):
""" Update the cursor size showing the optimizer scan area for the XY image.
"""
hpos = self.roi_xy.pos()[0]
vpos = self.roi_xy.pos()[1]
hsize = self.roi_xy.size()[0]
vsize = self.roi_xy.size()[1]
hcenter = hpos + 0.5 * hsize
vcenter = vpos + 0.5 * vsize
if self.adjust_cursor_roi:
newsize = self._optimizer_logic.refocus_XY_size
else:
viewrange = self.xy_image.getViewBox().viewRange()
newsize = np.sqrt(np.sum(np.ptp(viewrange, axis=1)**2)) / 20
self.roi_xy.setSize([newsize, newsize])
self.roi_xy.setPos([hcenter - newsize / 2, vcenter - newsize / 2])
Example 8
def update_roi_depth_size(self):
""" Update the cursor size showing the optimizer scan area for the X-depth image.
"""
hpos = self.roi_depth.pos()[0]
vpos = self.roi_depth.pos()[1]
hsize = self.roi_depth.size()[0]
vsize = self.roi_depth.size()[1]
hcenter = hpos + 0.5 * hsize
vcenter = vpos + 0.5 * vsize
if self.adjust_cursor_roi:
newsize_h = self._optimizer_logic.refocus_XY_size
newsize_v = self._optimizer_logic.refocus_Z_size
else:
viewrange = self.depth_image.getViewBox().viewRange()
newsize = np.sqrt(np.sum(np.ptp(viewrange, axis=1)**2)) / 20
newsize_h = newsize
newsize_v = newsize
self.roi_depth.setSize([newsize_h, newsize_v])
self.roi_depth.setPos([hcenter - newsize_h / 2, vcenter - newsize_v / 2])
Example 9
def plane_fit(points, tolerance=None):
'''
Given a set of points, find an origin and normal using least squares
Arguments
---------
points: (n,3)
tolerance: how non-planar the result can be without raising an error
Returns
---------
C: (3) point on the plane
N: (3) normal vector
'''
C = points[0]
x = points - C
M = np.dot(x.T, x)
N = np.linalg.svd(M)[0][:,-1]
if not (tolerance is None):
normal_range = np.ptp(np.dot(N, points.T))
if normal_range > tol.planar:
log.error('Points have peak to peak of %f', normal_range)
raise ValueError('Plane outside tolerance!')
return C, N
Example 10
def plot_epipolar_line(p1, p2, F, show_epipole=False)