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 mouse_drag(self, event): ''' ''' if event.inaxes == self.ax and event.button == 1: # Index of nearest point i = np.nanargmin(((event.xdata - self.x) / self.nx) ** 2) j = np.nanargmin(((event.ydata - self.y) / self.ny) ** 2) if (i == self.last_i) and (j == self.last_j): return else: self.last_i = i self.last_j = j # Toggle pixel if self.aperture[j,i]: self.aperture[j,i] = 0 else: self.aperture[j,i] = 1 # Update the contour self.update()
Example 2
def mouse_click(self, event): ''' ''' if event.mouseevent.inaxes == self.ax: # Index of nearest point i = np.nanargmin(((event.mouseevent.xdata - self.x) / self.nx) ** 2) j = np.nanargmin(((event.mouseevent.ydata - self.y) / self.ny) ** 2) self.last_i = i self.last_j = j # Toggle pixel if self.aperture[j,i]: self.aperture[j,i] = 0 else: self.aperture[j,i] = 1 # Update the contour self.update()
Example 3
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list ``arx``. Based on the smallest corresponding value in ``arf``, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. ``xarchive`` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum try: minidx = np.nanargmin(arf) except ValueError: return if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
Example 4
def test_nanargmin(self): tgt = np.argmin(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmin(mat), tgt)
Example 5
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
Example 6
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
Example 7
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
Example 8
def test_nanargmin(self): tgt = np.argmin(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmin(mat), tgt)
Example 9
def figure_mouse_pick(self, event): """ Trigger for when the mouse is used to select an item in the figure. :param event: The matplotlib event. """ ycol = "abundance" xcol = { self.ax_excitation_twin: "expot", self.ax_line_strength_twin: "reduced_equivalent_width" }[event.inaxes] xscale = np.ptp(event.inaxes.get_xlim()) yscale = np.ptp(event.inaxes.get_ylim()) try: distance = np.sqrt( ((self._state_transitions[ycol] - event.ydata)/yscale)**2 \ + ((self._state_transitions[xcol] - event.xdata)/xscale)**2) except AttributeError: # Stellar parameters have not been measured yet return None index = np.nanargmin(distance) # Because the state transitions are linked to the parent source model of # the table view, we will have to get the proxy index. proxy_index = self.table_view.model().mapFromSource( self.proxy_spectral_models.sourceModel().createIndex(index, 0)).row() self.table_view.selectRow(proxy_index) return None
Example 10
def find_min(x, bin_width = 10): xm = binned_average(x, bin_width=bin_width); imin = np.nanargmin(xm); return int((imin + 0.5) * bin_width);
Example 11
def find_min(x, bin_width = 10): xm = binned_average(x, bin_width=bin_width); imin = np.nanargmin(xm); return int((imin + 0.5) * bin_width);
Example 12
def find_min(x, bin_width = 10): xm = binned_average(x, bin_width=bin_width); imin = np.nanargmin(xm); return int((imin + 0.5) * bin_width);
Example 13
def find_min(x, bin_width = 10): xm = binned_average(x, bin_width=bin_width); imin = np.nanargmin(xm); return int((imin + 0.5) * bin_width);
Example 14
def find_min(x, bin_width = 10): xm = binned_average(x, bin_width=bin_width); imin = np.nanargmin(xm); return int((imin + 0.5) * bin_width);
Example 15
def Variogram(self): """ :return: """ self.run() # find the best Variogram idx = np.nanargmin(self.e) return self.V[idx]
Example 16
def _select_best_measure_index(curr_measures, args): idx = None try: if args.measure == 'aicc': # The best score for AICc is the minimum. idx = np.nanargmin(curr_measures) elif args.measure in ['hmm-distance', 'wasserstein', 'mahalanobis']: # The best score for the l-d measure is the maximum. idx = np.nanargmax(curr_measures) except: idx = random.choice(range(len(curr_measures))) assert idx is not None return idx
Example 17
def initial_count(classify, test_set_x, data, valid): (valid_st2,valid_st5,valid_st8) = valid (ns_test_set_x_st2,ns_test_set_x_st5,ns_test_set_x_st8) = data # classify st_2 it is always valid (st2_count, st2_res, st2_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st2, 0, 0, 81) #100 - 19 etc. # check if st5 is valid. if not return st2 count if (valid_st5 == 1): (st5_count, st5_res, st5_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st5, 0, 0, 21) else: st8_entropy = numpy.inf if (valid_st8 == 1): (st8_count, st8_res, st8_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st8, 0, 0, 6) else: st8_entropy = numpy.inf winner = numpy.nanargmin(numpy.array([st2_entropy, st5_entropy, st8_entropy])) if (winner == 0): # winner is stride 2 return (st2_count, (st2_res*2/2,st2_res*2/5, st2_res*2/8)) if (winner == 1): # winner is stride 5 return (st5_count, (st5_res*5/2,st5_res*5/5, st5_res*5/8)) if (winner == 2): # winner is stride 8 return (st8_count, (st8_res*8/2,st8_res*8/5, st8_res*8/8))
Example 18
def get_next_count(classify, test_set_x, data, valid, global_count, curr_residue, start_frame): (valid_st2,valid_st5,valid_st8) = valid (ns_test_set_x_st2,ns_test_set_x_st5,ns_test_set_x_st8) = data (curr_residue_st2, curr_residue_st5, curr_residue_st8) = curr_residue # classify st_2 it is always valid (st2_count, st2_res, st2_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st2, curr_residue_st2, (start_frame/2-19), (start_frame/2-19)+20) # check if st5 is valid. if not return st2 count if (valid_st5 == 1): (st5_count, st5_res, st5_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st5, curr_residue_st5, (start_frame/5-19), (start_frame/5-19)+8) else: st5_entropy = numpy.inf if (valid_st8 == 1): (st8_count, st8_res, st8_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st8, curr_residue_st8, (start_frame/8-19), (start_frame/8-19)+5) else: st8_entropy = numpy.inf winner = numpy.nanargmin(numpy.array([st2_entropy, st5_entropy, st8_entropy])) if (winner == 0): # winner is stride 2 return (global_count + st2_count, (st2_res*2/2,st2_res*2/5, st2_res*2/8)) if (winner == 1): # winner is stride 5 return (global_count + st5_count, (st5_res*5/2,st5_res*5/5, st5_res*5/8)) if (winner == 2): # winner is stride 8 return (global_count + st8_count, (st8_res*8/2,st8_res*8/5, st8_res*8/8))
Example 19
def get_remain_count(classify, test_set_x, data, valid, global_count, curr_residue, start_frame): (valid_st2,valid_st5,valid_st8) = valid (ns_test_set_x_st2,ns_test_set_x_st5,ns_test_set_x_st8) = data (curr_residue_st2, curr_residue_st5, curr_residue_st8) = curr_residue # classify st_2 it is always valid (st2_count, st2_res, st2_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st2, curr_residue_st2, (start_frame/2-19), ns_test_set_x_st2.shape[0]) # check if st5 is valid. if not return st2 count if (valid_st5 == 1): (st5_count, st5_res, st5_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st5, curr_residue_st5, (start_frame/5-19), ns_test_set_x_st5.shape[0]) else: st5_entropy = numpy.inf if (valid_st8 == 1): (st8_count, st8_res, st8_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st8, curr_residue_st8, (start_frame/8-19), ns_test_set_x_st8.shape[0]) else: st8_entropy = numpy.inf winner = numpy.nanargmin(numpy.array([st2_entropy, st5_entropy, st8_entropy])) if (winner == 0): # winner is stride 2 return (global_count + st2_count) if (winner == 1): # winner is stride 5 return (global_count + st5_count) if (winner == 2): # winner is stride 8 return (global_count + st8_count)
Example 20
def count_entire_movie(classify, test_set_x, data, valid, global_count, curr_residue, start_frame): (valid_st2,valid_st5,valid_st8) = valid (ns_test_set_x_st2,ns_test_set_x_st5,ns_test_set_x_st8) = data (curr_residue_st2, curr_residue_st5, curr_residue_st8) = curr_residue # classify st_2 it is always valid (st2_count, st2_res, st2_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st2, curr_residue_st2, 0, ns_test_set_x_st2.shape[0]) # check if st5 is valid. if not return st2 count if (valid_st5 == 1): (st5_count, st5_res, st5_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st5, curr_residue_st5, 0, ns_test_set_x_st5.shape[0]) else: st5_entropy = numpy.inf if (valid_st8 == 1): (st8_count, st8_res, st8_entropy) = count_in_interval(classify, test_set_x, ns_test_set_x_st8, curr_residue_st8, 0, ns_test_set_x_st8.shape[0]) else: st8_entropy = numpy.inf winner = numpy.nanargmin(numpy.array([st2_entropy, st5_entropy, st8_entropy])) if (winner == 0): # winner is stride 2 return (global_count + st2_count) if (winner == 1): # winner is stride 5 return (global_count + st5_count) if (winner == 2): # winner is stride 8 return (global_count + st8_count)
Example 21
def test_nanargmin(self): tgt = np.argmin(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmin(mat), tgt)
Example 22
def __find_nearest_nodes(self, num, signal, mahar=True): #if mahar: return self.__find_nearest_nodes_by_mahar(num, signal) n = self.nodes.shape[0] indexes = [0.0] * num sq_dists = [0.0] * num D = util.calc_distance(self.nodes, np.asarray([signal] * n)) for i in range(num): indexes[i] = np.nanargmin(D) sq_dists[i] = D[indexes[i]] D[indexes[i]] = float('nan') return indexes, sq_dists
Example 23
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
Example 24
def test_nanargmin(self): tgt = np.argmin(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmin(mat), tgt)
Example 25
def test_nanargmin(self): tgt = np.argmin(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmin(mat), tgt)
Example 26
def plot(self, ax=None, write_tau=True): """ Returns ------- fig : matplotlib.figure.Figure Figure instance containing the plot. """ check_is_fitted(self, 'neg_log_likelihood_') if ax is None: fig = plt.figure() ax = fig.gca() else: fig = ax.figure blue, green, red, purple, yellow, cyan = SEABORN_PALETTES['deep'] i_best = np.nanargmin(self.neg_log_likelihood_) ax.plot(self.delays_ms_, self.neg_log_likelihood_, color=purple) ax.plot(self.delays_ms_[i_best], self.neg_log_likelihood_[i_best], 'D', color=red) ax.set_xlabel('Delay (ms)') ax.set_ylabel('Neg. log likelihood / T') ax.grid('on') if write_tau: ax.text(0.5, 0.80, r'$\mathrm{Estimated}$', horizontalalignment='center', transform=ax.transAxes) ax.text(0.5, 0.66, r'$\tau_0 = %.0f \;\mathrm{ms}$' % (self.delays_ms_[i_best], ), horizontalalignment='center', transform=ax.transAxes) return fig
Example 27
def test_delay_shape(): est = fast_delay() assert_equal(est.neg_log_likelihood_.shape, est.delays_ms_.shape) assert_greater(est.neg_log_likelihood_.shape[0], 1) i_best = np.nanargmin(est.neg_log_likelihood_) assert_equal(est.best_delay_ms_, est.delays_ms_[i_best])
Example 28
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
Example 29
def optimize_threshold_with_f1(f1c, thresholds, criterion='max'): #f1c[np.isnan(f1c)] = 0 if criterion == 'max': ti = np.nanargmax(f1c) else: ti = np.nanargmin(np.abs(thresholds-0.5*f1c)) #assert(np.all(thresholds>=0)) #idx = (thresholds>=f1c*0.5-mp) & (thresholds<=f1c*0.5+mp) #assert(np.any(idx)) #ti = np.where(idx)[0][f1c[idx].argmax()] return thresholds[ti], ti
Example 30
def _(artist, event): offsets = artist.get_offsets() ds = np.hypot( *(artist.axes.transData.transform(offsets) - [event.x, event.y]).T) argmin = np.nanargmin(ds) if ds[argmin] < artist.get_pickradius(): target = with_attrs(offsets[argmin], index=argmin) return Selection(artist, target, ds[argmin], None, None) else: return None
Example 31
def compute_integral(self, x_s, y_s): if len(x_s) == 0: return np.zeros((y_s.shape[0],)) * np.nan closer = np.nanargmin(abs(x_s - self.limits[0])) return y_s[:, closer]
Example 32
def compute_draw_info(self, x, ys): bs = self.compute_baseline(x, ys) im = np.array([np.nanargmin(abs(x - self.limits[0]))]) dx = [self.limits[0], self.limits[0]] dys = np.hstack((bs[:, im], ys[:, im])) return [("curve", (dx, dys, INTEGRATE_DRAW_EDGE_PENARGS)), # line to value ("dot", (x[im], ys[:, im]))]
Example 33
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
Example 34
def test_nanargmin(self): tgt = np.argmin(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmin(mat), tgt)
Example 35
def nanmedoid(a, axis=1, indexonly=False): """ Compute the medoid along the specified axis, omitting observations containing NaNs. Returns the medoid of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : int Axis along which the medoid is computed. The default is to compute the median along the last axis of the array. indexonly : bool, optional If this is set to True, only the index of the medoid is returned. Returns ------- medoid : ndarray or int """ if axis == 1: diff = a.T[:, None, :] - a.T ssum = np.einsum('ijk,ijk->ij', diff, diff) dist = np.nansum(np.sqrt(ssum), axis=1) mask = np.isnan(a).any(axis=0) dist[mask] = np.nan idx = np.nanargmin(dist) if indexonly: return idx else: return a[:, idx] if axis == 0: diff = a[:, None, :] - a ssum = np.einsum('ijk,ijk->ij', diff, diff) dist = np.nansum(np.sqrt(ssum), axis=1) mask = np.isnan(a).any(axis=1) dist[mask] = np.nan idx = np.nanargmin(dist) if indexonly: return idx else: return a[idx, :] raise IndexError("axis {} out of bounds".format(axis))
Example 36
def nanargmin(a, axis=None): """ Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmin, nanargmax Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmin(a) 0 >>> np.nanargmin(a) 2 >>> np.nanargmin(a, axis=0) array([1, 1]) >>> np.nanargmin(a, axis=1) array([1, 0]) """ a, mask = _replace_nan(a, np.inf) res = np.argmin(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 37
def nanargmax(a, axis=None): """ Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) """ a, mask = _replace_nan(a, -np.inf) res = np.argmax(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 38
def nanargmin(a, axis=None): """ Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmin, nanargmax Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmin(a) 0 >>> np.nanargmin(a) 2 >>> np.nanargmin(a, axis=0) array([1, 1]) >>> np.nanargmin(a, axis=1) array([1, 0]) """ a, mask = _replace_nan(a, np.inf) res = np.argmin(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 39
def nanargmax(a, axis=None): """ Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) """ a, mask = _replace_nan(a, -np.inf) res = np.argmax(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 40
def nicecolorbar(self, axcb=None, reflevel=None, label=None, vmax=None, vmin=None, data=None, loc='head right', fontsize=8, ticks = None): if not axcb: axcb = matplotlib.pyplot.gca() divider = make_axes_locatable(axcb) # this code is from # http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axes-grid1 cax = divider.append_axes("right", size="2%", pad=0.15) levels = numpy.asarray([0.001,0.0025,0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,25,50,100,250,500,1000]) if vmax!= None and vmin != None: level = levels[numpy.nanargmin(abs((vmax - vmin)/5 - levels))] ticks = numpy.arange(vmin, vmax, level) elif vmax : level = levels[numpy.nanargmin(abs((vmax - numpy.nanmin(data))/5 - levels))] ticks = numpy.arange(numpy.nanmin(data), vmax, level) elif data is not None: level = None #levels[numpy.nanargmin(abs((numpy.nanmax(data) - numpy.nanmin(data))/5 - levels))] ticks = None #numpy.arange(numpy.nanmin(data), numpy.nanmax(data), level) #ticks -= numpy.nanmin(abs(ticks)) cb = matplotlib.pyplot.colorbar(self, cax=cax, label=label, orientation='vertical', extend='both', spacing='uniform', ticks=ticks) if vmax!= None and vmin != None: #print(ticks,vmin,vmax) cb.set_clim(vmin, vmax) cb.ax.yaxis.set_ticks_position('right') cb.ax.yaxis.set_label_position('right') cb.ax.set_yticklabels(cb.ax.get_yticklabels(), rotation='vertical',fontsize=fontsize) #if reflevel: # cb.ax.axhline((reflevel-min(cb.get_clim()))/numpy.diff(cb.get_clim()),zorder=999,color='k',linewidth=2) return cb
Example 41
def nanargmin(a, axis=None): """ Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmin, nanargmax Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmin(a) 0 >>> np.nanargmin(a) 2 >>> np.nanargmin(a, axis=0) array([1, 1]) >>> np.nanargmin(a, axis=1) array([1, 0]) """ a, mask = _replace_nan(a, np.inf) res = np.argmin(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 42
def nanargmax(a, axis=None): """ Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) """ a, mask = _replace_nan(a, -np.inf) res = np.argmax(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 43
def nanargmin(a, axis=None): """ Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmin, nanargmax Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmin(a) 0 >>> np.nanargmin(a) 2 >>> np.nanargmin(a, axis=0) array([1, 1]) >>> np.nanargmin(a, axis=1) array([1, 0]) """ a, mask = _replace_nan(a, np.inf) res = np.argmin(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 44
def nanargmax(a, axis=None): """ Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) """ a, mask = _replace_nan(a, -np.inf) res = np.argmax(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 45
def nanargmin(a, axis=None): """ Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmin, nanargmax Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmin(a) 0 >>> np.nanargmin(a) 2 >>> np.nanargmin(a, axis=0) array([1, 1]) >>> np.nanargmin(a, axis=1) array([1, 0]) """ a, mask = _replace_nan(a, np.inf) res = np.argmin(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 46
def nanargmax(a, axis=None): """ Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) """ a, mask = _replace_nan(a, -np.inf) res = np.argmax(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res
Example 47
def get_ray_lengths(self,x=None,y=None,PositionTol = 3,Coords='Display'): # Work out ray lengths for all raytraced pixels RayLength = np.sqrt(np.sum( (self.ray_end_coords - self.ray_start_coords) **2,axis=-1)) # If no x and y given, return them all if x is None and y is None: if self.fullchip: if Coords.lower() == 'display': return RayLength else: return self.transform.display_to_original_image(RayLength,binning=self.binning) else: return RayLength else: if self.x is None or self.y is None: raise Exception('This ray data does not have x and y pixel indices!') # Otherwise, return the ones at given x and y pixel coords. if np.shape(x) != np.shape(y): raise ValueError('x and y arrays must be the same shape!') else: if Coords.lower() == 'original': x,y = self.transform.original_to_display_coords(x,y) orig_shape = np.shape(x) x = np.reshape(x,np.size(x),order='F') y = np.reshape(y,np.size(y),order='F') RL = np.zeros(np.shape(x)) RayLength = RayLength.flatten() xflat = self.x.flatten() yflat = self.y.flatten() for pointno in range(x.size): if np.isnan(x[pointno]) or np.isnan(y[pointno]): RL[pointno] = np.nan continue deltaX = xflat - x[pointno] deltaY = yflat - y[pointno] deltaR = np.sqrt(deltaX**2 + deltaY**2) if np.nanmin(deltaR) <= PositionTol: RL[pointno] = RayLength[np.nanargmin(deltaR)] else: raise Exception('No ray-traced pixel within PositionTol of requested pixel!') return np.reshape(RL,orig_shape,order='F') # Return unit vectors of sight-line direction for each pixel.
Example 48
def _compute_projection_pick(artist, path, xy): """Project *xy* on *path* to obtain a `Selection` for *artist*. *path* is first transformed to screen coordinates using the artist transform, and the target of the returned `Selection` is transformed back to data coordinates using the artist *axes* inverse transform. The `Selection` `index` is returned as a float. This function returns ``None`` for degenerate inputs. The caller is responsible for converting the index to the proper class if needed. """ transform = artist.get_transform().frozen() tpath = (path.cleaned(transform) if transform.is_affine # `cleaned` only handles affine transforms. else transform.transform_path(path).cleaned()) # `cleaned` should return a path where the first element is `MOVETO`, the # following are `LINETO` or `CLOSEPOLY`, and the last one is `STOP`, i.e. # codes = path.codes # assert (codes[0], codes[-1]) == (path.MOVETO, path.STOP) # assert np.in1d(codes[1:-1], [path.LINETO, path.CLOSEPOLY]).all() vertices = tpath.vertices[:-1] codes = tpath.codes[:-1] vertices[codes == tpath.CLOSEPOLY] = vertices[0] # Unit vectors for each segment. us = vertices[1:] - vertices[:-1] ls = np.hypot(*us.T) with np.errstate(invalid="ignore"): # Results in 0/0 for repeated consecutive points. us /= ls[:, None] # Vectors from each vertex to the event (overwritten below). vs = xy - vertices[:-1] # Clipped dot products -- `einsum` cannot be done in place, `clip` can. dot = np.clip(np.einsum("ij,ij->i", vs, us), 0, ls, out=vs[:, 0]) # Projections. projs = vertices[:-1] + dot[:, None] * us ds = np.hypot(*(xy - projs).T, out=vs[:, 1]) try: argmin = np.nanargmin(ds) dmin = ds[argmin] except (ValueError, IndexError): # See above re: exceptions caught. return else: target = AttrArray( artist.axes.transData.inverted().transform_point(projs[argmin])) target.index = ( (argmin + dot[argmin] / ls[argmin]) / (path._interpolation_steps / tpath._interpolation_steps)) return Selection(artist, target, dmin, None, None)
Example 49
def _(artist, event): # No need to call `line.contains` because we're going to redo # the work anyways (and it was broken for step plots up to # matplotlib/matplotlib#6645). # Always work in screen coordinates, as this is how we need to compute # distances. Note that the artist transform may be different from the axes # transform (e.g., for axvline). xy = event.x, event.y data_xy = artist.get_xydata() sels = [] # If markers are visible, find the closest vertex. if artist.get_marker() not in ["None", "none", " ", "", None]: ds = np.hypot(*(xy - artist.get_transform().transform(data_xy)).T) try: argmin = np.nanargmin(ds) dmin = ds[argmin] except (ValueError, IndexError): # numpy 1.7.0's `nanargmin([nan])` returns nan, so # `ds[argmin]` raises IndexError. In later versions of numpy, # `nanargmin([nan])` raises ValueError (the release notes for 1.8.0 # are incorrect on this topic). pass else: # More precise than transforming back. target = with_attrs(artist.get_xydata()[argmin], index=argmin) sels.append(Selection(artist, target, dmin, None, None)) # If lines are visible, find the closest projection. if (artist.get_linestyle() not in ["None", "none", " ", "", None] and len(artist.get_xydata()) > 1): sel = _compute_projection_pick(artist, artist.get_path(), xy) if sel is not None: sel.target.index = { "_draw_lines": lambda _, index: index, "_draw_steps_pre": Index.pre_index, "_draw_steps_mid": Index.mid_index, "_draw_steps_post": Index.post_index}[ Line2D.drawStyles[artist.get_drawstyle()]]( len(data_xy), sel.target.index) sels.append(sel) sel = min(sels, key=lambda sel: sel.dist, default=None) return sel if sel and sel.dist < artist.get_pickradius() else None
Example 50
def mouseMoved(self, evt): pos = evt[0] if self.plot.sceneBoundingRect().contains(pos): mousePoint = self.plot.vb.mapSceneToView(pos) posx, posy = mousePoint.x(), mousePoint.y() labels = [] for a, vs in sorted(self.reports.items()): for v in vs: if isinstance(v, tuple) and len(v) == 2: if v[0] == "x": labels.append(("%0." + str(self.important_decimals[0]) + "f") % v[1]) continue labels.append(str(v)) labels = " ".join(labels) self.crosshair_hidden = bool(labels) if self.location and not labels: fs = "%0." + str(self.important_decimals[0]) + "f %0." + str(self.important_decimals[1]) + "f" labels = fs % (posx, posy) self.label.setText(labels, color=(0, 0, 0)) if self.curves and len(self.curves[0][0]): # need non-zero x axis! cache = {} bd = None if self.markclosest and self.plot.vb.action != ZOOMING: xpixel, ypixel = self.plot.vb.viewPixelSize() distances = distancetocurves(self.curves[0], posx, posy, xpixel, ypixel, r=self.MOUSE_RADIUS, cache=cache) try: mindi = np.nanargmin(distances) if distances[mindi] < self.MOUSE_RADIUS: bd = mindi except ValueError: # if all distances are NaN pass if self.highlighted != bd: QToolTip.hideText() if self.highlighted is not None and bd is None: self.highlighted = None self.highlighted_curve.hide() if bd is not None: self.highlighted = bd x = self.curves[0][0] y = self.curves[0][1][self.highlighted] self.highlighted_curve.setData(x=x, y=y) self.highlighted_curve.show() self.vLine.setPos(posx) self.hLine.setPos(posy) self.viewhelpers_show() else: self.viewhelpers_hide()