Python numpy.nanmax() Examples
The following are 30
code examples of numpy.nanmax().
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
numpy
, or try the search function
.
Example #1
Source File: genesis4_plot.py From ocelot with GNU General Public License v3.0 | 6 votes |
def subfig_evo_rad_pow_sz(ax_power_evo, out, legend, norm=1, **kwargs): if out.nSlices > 1: z = out.z s = out.s power = out.rad_power if norm == 1: max_power = np.nanmax(power, 1)[:, np.newaxis] max_power[max_power == 0] = 1 # avoid division by zero power = power / max_power # power[isnan(power)]=0 ax_power_evo.pcolormesh(z, s * 1e6, power.T) ax_power_evo.set_xlabel('z [m]') ax_power_evo.set_ylabel('s [$\mu$m]') ax_power_evo.axis('tight') ax_power_evo.grid(True) else: pass
Example #2
Source File: test_sw.py From pysat with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_calc_f107a_daily_missing(self): """ Test the calc_f107a routine with some daily data missing""" self.testInst.data = pds.DataFrame({'f107': np.linspace(70, 200, 160)}, index=[pysat.datetime(2009, 1, 1) + pds.DateOffset(days=2*i+1) for i in range(160)]) sw_f107.calc_f107a(self.testInst, f107_name='f107', f107a_name='f107a') # Assert that new data and metadata exist assert 'f107a' in self.testInst.data.columns assert 'f107a' in self.testInst.meta.keys() # Assert the finite values have realistic means assert(np.nanmin(self.testInst['f107a']) > np.nanmin(self.testInst['f107'])) assert(np.nanmax(self.testInst['f107a']) < np.nanmax(self.testInst['f107'])) # Assert the expected number of fill values assert(len(self.testInst['f107a'][np.isnan(self.testInst['f107a'])]) == 40)
Example #3
Source File: grid.py From python-control with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __call__(self, transform_xy, x1, y1, x2, y2): x_, y_ = np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny) x, y = np.meshgrid(x_, y_) lon, lat = transform_xy(np.ravel(x), np.ravel(y)) with np.errstate(invalid='ignore'): if self.lon_cycle is not None: lon0 = np.nanmin(lon) # Changed from 180 to 360 to be able to span only # 90-270 (left hand side) lon -= 360. * ((lon - lon0) > 360.) if self.lat_cycle is not None: lat0 = np.nanmin(lat) # Changed from 180 to 360 to be able to span only # 90-270 (left hand side) lat -= 360. * ((lat - lat0) > 360.) lon_min, lon_max = np.nanmin(lon), np.nanmax(lon) lat_min, lat_max = np.nanmin(lat), np.nanmax(lat) lon_min, lon_max, lat_min, lat_max = \ self._adjust_extremes(lon_min, lon_max, lat_min, lat_max) return lon_min, lon_max, lat_min, lat_max
Example #4
Source File: rafpc.py From fylearn with MIT License | 6 votes |
def fuzzify_mean(A): # output for fuzzified values R = np.zeros((A.shape[0], A.shape[1] * 3)) cmin, cmax, cmean = np.nanmin(A, 0), np.nanmax(A, 0), np.nanmean(A, 0) left = np.array([cmin - (cmax - cmin), cmin, cmax]).T middle = np.array([cmin, cmean, cmax]).T right = np.array([cmin, cmax, cmax + (cmax - cmin)]).T mus = [] for i in range(A.shape[1]): f_l = fl.TriangularSet(*left[i]) f_m = fl.TriangularSet(*middle[i]) f_r = fl.TriangularSet(*right[i]) R[:,(i*3)] = f_l(A[:,i]) R[:,(i*3)+1] = f_m(A[:,i]) R[:,(i*3)+2] = f_r(A[:,i]) mus.extend([(i, f_l), (i, f_m), (i, f_r)]) return 3, R, mus
Example #5
Source File: test_frame.py From recruit with Apache License 2.0 | 6 votes |
def test_unsorted_index_lims(self): df = DataFrame({'y': [0., 1., 2., 3.]}, index=[1., 0., 3., 2.]) ax = df.plot() xmin, xmax = ax.get_xlim() lines = ax.get_lines() assert xmin <= np.nanmin(lines[0].get_data()[0]) assert xmax >= np.nanmax(lines[0].get_data()[0]) df = DataFrame({'y': [0., 1., np.nan, 3., 4., 5., 6.]}, index=[1., 0., 3., 2., np.nan, 3., 2.]) ax = df.plot() xmin, xmax = ax.get_xlim() lines = ax.get_lines() assert xmin <= np.nanmin(lines[0].get_data()[0]) assert xmax >= np.nanmax(lines[0].get_data()[0]) df = DataFrame({'y': [0., 1., 2., 3.], 'z': [91., 90., 93., 92.]}) ax = df.plot(x='z', y='y') xmin, xmax = ax.get_xlim() lines = ax.get_lines() assert xmin <= np.nanmin(lines[0].get_data()[0]) assert xmax >= np.nanmax(lines[0].get_data()[0])
Example #6
Source File: rafpc.py From fylearn with MIT License | 6 votes |
def fuzzify_partitions(p): def fuzzify_p(A): R = np.zeros((A.shape[0], A.shape[1] * p)) cmin, cmax = np.nanmin(A, 0), np.nanmax(A, 0) psize = (cmax - cmin) / (p - 1) mus = [] # iterate features for i in range(A.shape[1]): # iterate partitions mu_i = [] offset = cmin[i] for j in range(p): f = fl.TriangularSet(offset - psize[i], offset, offset + psize[i]) R[:, (i * p) + j] = f(A[:, i]) mu_i.append(f) offset += psize[i] mus.append(mu_i) return p, R, mus return fuzzify_p
Example #7
Source File: dataset_keypoints.py From deep-functional-dictionaries with MIT License | 6 votes |
def convert_to_one_hot_matrix(self, dense_matrix, value_set=None): if value_set is None: n = np.nanmax(dense_matrix) + 1 value_set = np.arange(n) n_data = dense_matrix.shape[0] n_points = dense_matrix.shape[1] n_values = value_set.size one_hot_matrix = np.zeros((n_data, n_points, n_values), dtype=bool) for i in range(n_data): for j in range(n_points): # NOTE: # Ignore negative values. if dense_matrix[i,j] < 0: continue k = np.where(value_set == dense_matrix[i,j])[0] one_hot_matrix[i,j,k] = True return one_hot_matrix
Example #8
Source File: bam_cov.py From basenji with Apache License 2.0 | 6 votes |
def scatter_lims(vals1, vals2=None, buffer=.05): if vals2 is not None: vals = np.concatenate((vals1, vals2)) else: vals = vals1 vmin = np.nanmin(vals) vmax = np.nanmax(vals) buf = .05 * (vmax - vmin) if vmin == 0: vmin -= buf / 2 else: vmin -= buf vmax += buf return vmin, vmax ################################################################################ # __main__ ################################################################################
Example #9
Source File: basenji_sat_plot2.py From basenji with Apache License 2.0 | 6 votes |
def plot_seqlogo(ax, seq_align, sat_score_ti, pseudo_pct=0.05): """ Plot a sequence logo for the loss/gain scores. Args: ax (Axis): matplotlib axis to plot to. seq_align (L array): Sequence nucleotides, with gaps. sat_score_ti (L_sm array): Minimum mutation delta across satmut length. pseudo_pct (float): % of the max to add as a pseudocount. """ sat_score_cp = sat_score_ti.copy() satmut_len = len(sat_score_ti) # add pseudocounts sat_score_cp += pseudo_pct * np.nanmax(sat_score_cp) # expand sat_score_4l = expand_4l(sat_score_cp, seq_align) plots.seqlogo(sat_score_4l, ax)
Example #10
Source File: basenji_sat_plot.py From basenji with Apache License 2.0 | 6 votes |
def plot_heat(ax, sat_delta_ti, min_limit): """ Plot satmut deltas. Args: ax (Axis): matplotlib axis to plot to. sat_delta_ti (4 x L_sm array): Single target delta matrix for saturated mutagenesis region, min_limit (float): Minimum heatmap limit. """ vlim = max(min_limit, np.nanmax(np.abs(sat_delta_ti))) sns.heatmap( sat_delta_ti, linewidths=0, cmap='RdBu_r', vmin=-vlim, vmax=vlim, xticklabels=False, ax=ax) ax.yaxis.set_ticklabels('ACGT', rotation='horizontal') # , size=10)
Example #11
Source File: LSDMap_Subplots.py From LSDMappingTools with MIT License | 6 votes |
def findmaxval_multirasters(FileList): """ Loops through a list or array of rasters (np arrays) and finds the maximum single value in the set of arrays. """ overall_max_val = 0 for i in range (len(FileList)): raster_as_array = LSDMap_IO.ReadRasterArrayBlocks(FileList[i]) this_max_val = np.nanmax(raster_as_array) if this_max_val > overall_max_val: overall_max_val = this_max_val print(overall_max_val) return overall_max_val
Example #12
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def apply_cmap(zs, cmap, vmin=None, vmax=None, unit=None, logrescale=False): ''' apply_cmap(z, cmap) applies the given cmap to the values in z; if vmin and/or vmax are passed, they are used to scale z. Note that this function can automatically rescale data into log-space if the colormap is a neuropythy log-space colormap such as log_eccentricity. To enable this behaviour use the optional argument logrescale=True. ''' zs = pimms.mag(zs) if unit is None else pimms.mag(zs, unit) zs = np.asarray(zs, dtype='float') if pimms.is_str(cmap): cmap = matplotlib.cm.get_cmap(cmap) if logrescale: if vmin is None: vmin = np.log(np.nanmin(zs)) if vmax is None: vmax = np.log(np.nanmax(zs)) mn = np.exp(vmin) u = zdivide(nanlog(zs + mn) - vmin, vmax - vmin, null=np.nan) else: if vmin is None: vmin = np.nanmin(zs) if vmax is None: vmax = np.nanmax(zs) u = zdivide(zs - vmin, vmax - vmin, null=np.nan) u[np.isnan(u)] = -np.inf return cmap(u)
Example #13
Source File: genesis4_plot.py From ocelot with GNU General Public License v3.0 | 6 votes |
def subfig_evo_rad_spec_sz(ax_spectrum_evo, out, legend, norm=1): if out.nSlices > 1: z = out.z l, spectrum = out.calc_spec() # spectrum = out.spec if norm == 1: max_spectrum = np.nanmax(spectrum, 1)[:, np.newaxis] max_spectrum[max_spectrum == 0] = 1 # avoid division by zero spectrum = spectrum / max_spectrum # spectrum[isnan(spectrum)]=0 ax_spectrum_evo.pcolormesh(z, l, spectrum.T) ax_spectrum_evo.set_xlabel('z [m]') ax_spectrum_evo.set_ylabel('[eV]') ax_spectrum_evo.axis('tight') ax_spectrum_evo.grid(True) else: pass
Example #14
Source File: netcdfhelper.py From geojsoncontour with MIT License | 6 votes |
def netcdf_to_geojson(ncfile, var, fourth_dim=None): realpath = os.path.realpath(ncfile) name, ext = os.path.splitext(realpath) X, Y, Z, levels, unit = setup(ncfile, var) figure = plt.figure() ax = figure.add_subplot(111) for t in range(len(Z.time)): third = Z.isel(time=t) position = 0 if len(third.dims) == 3: position = len(getattr(third, third.dims[0]))-1 third = third[position, ] # local min max levels = np.linspace(start=np.nanmin(third), stop=np.nanmax(third), num=20) contourf = ax.contourf(X, Y, third, levels=levels, cmap=plt.cm.viridis) geojsoncontour.contourf_to_geojson( contourf=contourf, geojson_filepath='{}_{}_t{}_{}.geojson'.format(name, var, t, position), ndigits=3, min_angle_deg=None, unit=unit )
Example #15
Source File: test_frame.py From vnpy_crypto with MIT License | 6 votes |
def test_unsorted_index_lims(self): df = DataFrame({'y': [0., 1., 2., 3.]}, index=[1., 0., 3., 2.]) ax = df.plot() xmin, xmax = ax.get_xlim() lines = ax.get_lines() assert xmin <= np.nanmin(lines[0].get_data()[0]) assert xmax >= np.nanmax(lines[0].get_data()[0]) df = DataFrame({'y': [0., 1., np.nan, 3., 4., 5., 6.]}, index=[1., 0., 3., 2., np.nan, 3., 2.]) ax = df.plot() xmin, xmax = ax.get_xlim() lines = ax.get_lines() assert xmin <= np.nanmin(lines[0].get_data()[0]) assert xmax >= np.nanmax(lines[0].get_data()[0]) df = DataFrame({'y': [0., 1., 2., 3.], 'z': [91., 90., 93., 92.]}) ax = df.plot(x='z', y='y') xmin, xmax = ax.get_xlim() lines = ax.get_lines() assert xmin <= np.nanmin(lines[0].get_data()[0]) assert xmax >= np.nanmax(lines[0].get_data()[0])
Example #16
Source File: outlierdenstream.py From outlierdenstream with MIT License | 6 votes |
def updateRealTimeLSandSS(self, sample): """ Updates the `Weighted Linear Sum` (WLS), the `Weighted Squared Sum` (WSS), the `center` and the `radius` of the micro-cluster when a new sample is merged. :param sample: the `sample` to merge into the micro-cluster. """ sample = np.array(sample.value) self.LS = np.multiply(self.LS, self.reductionFactor) self.SS = np.multiply(self.SS, self.reductionFactor) self.LS = self.LS + sample self.SS = self.SS + np.power(sample, 2) self.center = np.divide(self.LS, float(self.weight)) LSd = np.power(self.center, 2) SSd = np.divide(self.SS, float(self.weight)) maxRad = np.nanmax(np.sqrt(SSd.astype(float)-LSd.astype(float))) # maxRad = np.nanmax(np.lib.scimath.sqrt(SSd-LSd)) self.radius = maxRad
Example #17
Source File: ImageView.py From tf-pose with Apache License 2.0 | 6 votes |
def quickMinMax(self, data): """ Estimate the min/max values of *data* by subsampling. Returns [(min, max), ...] with one item per channel """ while data.size > 1e6: ax = np.argmax(data.shape) sl = [slice(None)] * data.ndim sl[ax] = slice(None, None, 2) data = data[sl] cax = self.axes['c'] if cax is None: return [(float(nanmin(data)), float(nanmax(data)))] else: return [(float(nanmin(data.take(i, axis=cax))), float(nanmax(data.take(i, axis=cax)))) for i in range(data.shape[-1])]
Example #18
Source File: som.py From pyERA with MIT License | 6 votes |
def return_normalized_distance_matrix(self, input_vector): """Return the min-max normalized euclidean-distance matrix between the input vector and the SOM weights. A value of 0.0 means that the input/weights are equal. @param input_vector the vector to use for the comparison. """ output_matrix = np.zeros((self._matrix_size, self._matrix_size)) it = np.nditer(output_matrix, flags=['multi_index']) while not it.finished: #print "%d <%s>" % (it[0], it.multi_index), dist = self.return_euclidean_distance(input_vector, self._weights_matrix[it.multi_index[0], it.multi_index[1], :]) output_matrix[it.multi_index[0], it.multi_index[1]] = dist it.iternext() #min-max normalization max_value = np.nanmax(output_matrix) min_value = np.nanmin(output_matrix) output_matrix = (output_matrix - min_value) / (max_value - min_value) return output_matrix
Example #19
Source File: som.py From pyERA with MIT License | 6 votes |
def return_similarity_matrix(self, input_vector): """Return a similarity matrix where a value is 1.0 if the distance input/weight is zero. @param input_vector the vector to use for the comparison. """ output_matrix = np.zeros((self._matrix_size, self._matrix_size)) it = np.nditer(output_matrix, flags=['multi_index']) while not it.finished: #print "%d <%s>" % (it[0], it.multi_index), dist = self.return_euclidean_distance(input_vector, self._weights_matrix[it.multi_index[0], it.multi_index[1], :]) output_matrix[it.multi_index[0], it.multi_index[1]] = dist it.iternext() #min-max normalization max_value = np.nanmax(output_matrix) min_value = np.nanmin(output_matrix) output_matrix = (output_matrix - min_value) / (max_value - min_value) output_matrix = 1.0 - output_matrix return output_matrix
Example #20
Source File: plots.py From basenji with Apache License 2.0 | 6 votes |
def scatter_lims(vals1, vals2=None, buffer=.05): if vals2 is not None: vals = np.concatenate((vals1, vals2)) else: vals = vals1 vmin = np.nanmin(vals) vmax = np.nanmax(vals) buf = .05 * (vmax - vmin) if vmin == 0: vmin -= buf / 2 else: vmin -= buf vmax += buf return vmin, vmax ################################################################################ # nucleotides # Thanks to Anshul Kundaje, Avanti Shrikumar # https://github.com/kundajelab/deeplift/tree/master/deeplift/visualization
Example #21
Source File: _tools.py From vnpy_crypto with MIT License | 5 votes |
def _get_xlim(lines): left, right = np.inf, -np.inf for l in lines: x = l.get_xdata(orig=False) left = min(np.nanmin(x), left) right = max(np.nanmax(x), right) return left, right
Example #22
Source File: circular.py From pingouin with GNU General Public License v3.0 | 5 votes |
def _checkangles(angles, axis=None): """Internal function to check that angles are in radians. """ msg = ("Angles are not in unit of radians. Please use the " "`pingouin.convert_angles` function to map your angles to " "the [-pi, pi] range.") ptp_rad = np.nanmax(angles, axis=axis) - np.nanmin(angles, axis=axis) ptp_mask = ptp_rad <= 2 * np.pi if not ptp_mask.all(): raise ValueError(msg)
Example #23
Source File: test_series.py From vnpy_crypto with MIT License | 5 votes |
def test_unsorted_index_xlim(self): ser = Series([0., 1., np.nan, 3., 4., 5., 6.], index=[1., 0., 3., 2., np.nan, 3., 2.]) _, ax = self.plt.subplots() ax = ser.plot(ax=ax) xmin, xmax = ax.get_xlim() lines = ax.get_lines() assert xmin <= np.nanmin(lines[0].get_data(orig=False)[0]) assert xmax >= np.nanmax(lines[0].get_data(orig=False)[0])
Example #24
Source File: test_nanfunctions.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def test_nanmax(self): tgt = np.max(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanmax(mat), tgt)
Example #25
Source File: data.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def partial_fit(self, X, y=None): """Online computation of max absolute value of X for later scaling. All of X is processed as a single batch. This is intended for cases when `fit` is not feasible due to very large number of `n_samples` or because X is read from a continuous stream. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. y Ignored """ X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite='allow-nan') if sparse.issparse(X): mins, maxs = min_max_axis(X, axis=0, ignore_nan=True) max_abs = np.maximum(np.abs(mins), np.abs(maxs)) else: max_abs = np.nanmax(np.abs(X), axis=0) # First pass if not hasattr(self, 'n_samples_seen_'): self.n_samples_seen_ = X.shape[0] # Next passes else: max_abs = np.maximum(self.max_abs_, max_abs) self.n_samples_seen_ += X.shape[0] self.max_abs_ = max_abs self.scale_ = _handle_zeros_in_scale(max_abs) return self
Example #26
Source File: simpletable.py From TheCannon with MIT License | 5 votes |
def max(s, v): return np.nanmax(v)
Example #27
Source File: test_result.py From ibeis with Apache License 2.0 | 5 votes |
def print_percent_identification_success(testres): """ Prints names identified (at rank 1) / names queried. This combines results over multiple queries of a particular name using max OLD, MAYBE DEPRIATE Example: >>> # DISABLE_DOCTEST >>> from ibeis.expt.test_result import * # NOQA """ ibs = testres.ibs qaids = testres.get_test_qaids() unique_nids, groupxs = ut.group_indices(ibs.get_annot_nids(qaids)) qx2_gt_raw_score = testres.get_infoprop_mat('qx2_gt_raw_score', qaids=qaids) qx2_gf_raw_score = testres.get_infoprop_mat('qx2_gf_raw_score', qaids=qaids) nx2_gt_raw_score = np.array([ np.nanmax(scores, axis=0) for scores in vt.apply_grouping(qx2_gt_raw_score, groupxs)]) nx2_gf_raw_score = np.array([ np.nanmax(scores, axis=0) for scores in vt.apply_grouping(qx2_gf_raw_score, groupxs)]) cfgx2_success = (nx2_gt_raw_score > nx2_gf_raw_score).T print('Identification success (names identified / names queried)') for cfgx, success in enumerate(cfgx2_success): pipelbl = testres.cfgx2_lbl[cfgx] percent = 100 * success.sum() / len(success) print('%2d) success = %r/%r = %.2f%% -- %s' % ( cfgx, success.sum(), len(success), percent, pipelbl))
Example #28
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def scale_for_cmap(cmap, x, vmin=Ellipsis, vmax=Ellipsis, unit=Ellipsis): ''' scale_for_cmap(cmap, x) yields the values in x rescaled to be appropriate for the given colormap cmap. The cmap must be the name of a colormap or a colormap object. For a given cmap argument, if the object is a colormap itself, it is treated as cmap.name. If the cmap names a colormap known to neuropythy, neuropythy will rescale the values in x according to a heuristic. ''' import matplotlib as mpl if isinstance(cmap, mpl.colors.Colormap): cmap = cmap.name (name, cm) = (None, None) if cmap not in colormaps: for (k,v) in six.iteritems(colormaps): if cmap in k: (name, cm) = (k, v) break else: (name, cm) = (cmap, colormaps[cmap]) if cm is not None: cm = cm if len(cm) == 3 else (cm + (None,)) (cm, (mn,mx), uu) = cm if vmin is Ellipsis: vmin = mn if vmax is Ellipsis: vmax = mx if unit is Ellipsis: unit = uu if vmin is Ellipsis: vmin = None if vmax is Ellipsis: vmax = None if unit is Ellipsis: unit = None x = pimms.mag(x) if unit is None else pimms.mag(x, unit) if name is not None and name.startswith('log_'): emn = np.exp(vmin) x = np.log(x + emn) vmin = np.nanmin(x) if vmin is None else vmin vmax = np.nanmax(x) if vmax is None else vmax return zdivide(x - vmin, vmax - vmin, null=np.nan)
Example #29
Source File: angle_helper.py From matplotlib-4-abaqus with MIT License | 5 votes |
def __call__(self, transform_xy, x1, y1, x2, y2): """ get extreme values. x1, y1, x2, y2 in image coordinates (0-based) nx, ny : number of divisions in each axis """ x_, y_ = np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny) x, y = np.meshgrid(x_, y_) lon, lat = transform_xy(np.ravel(x), np.ravel(y)) # iron out jumps, but algorithm should be improved. # Tis is just naive way of doing and my fail for some cases. if self.lon_cycle is not None: lon0 = np.nanmin(lon) lon -= 360. * ((lon - lon0) > 180.) if self.lat_cycle is not None: lat0 = np.nanmin(lat) lat -= 360. * ((lat - lat0) > 180.) lon_min, lon_max = np.nanmin(lon), np.nanmax(lon) lat_min, lat_max = np.nanmin(lat), np.nanmax(lat) lon_min, lon_max, lat_min, lat_max = \ self._adjust_extremes(lon_min, lon_max, lat_min, lat_max) return lon_min, lon_max, lat_min, lat_max
Example #30
Source File: windowed_minmax_scaler.py From scikit-multiflow with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_max(self, column_index): max_val = 1. if not self.window.is_empty(): max_val = np.nanmax(np.array(self.window.get_queue())[:, column_index]) return max_val