Python numpy.rint() Examples
The following are 30
code examples of numpy.rint().
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: scene.py From kite with GNU General Public License v3.0 | 8 votes |
def get_elevation(self, interpolation='nearest_neighbor'): assert interpolation in ('nearest_neighbor', 'bivariate') if self._elevation.get(interpolation, None) is None: self._log.debug('Getting elevation...') # region = llLon, urLon, llLat, urLon coords = self.frame.coordinates lons = coords[:, 0] lats = coords[:, 1] region = (lons.min(), lons.max(), lats.min(), lats.max()) if not srtmgl3.covers(region): raise AssertionError( 'Region is outside of SRTMGL3 topo dataset') tile = srtmgl3.get(region) if not tile: raise AssertionError('Cannot get SRTMGL3 topo dataset') if interpolation == 'nearest_neighbor': iy = num.rint((lats - tile.ymin) / tile.dy).astype(num.intp) ix = num.rint((lons - tile.xmin) / tile.dx).astype(num.intp) elevation = tile.data[(iy, ix)] elif interpolation == 'bivariate': interp = interpolate.RectBivariateSpline( tile.y(), tile.x(), tile.data) elevation = interp(lats, lons, grid=False) elevation = elevation.reshape(self.rows, self.cols) self._elevation[interpolation] = elevation return self._elevation[interpolation]
Example #2
Source File: dataset.py From neural-combinatorial-optimization-rl-tensorflow with MIT License | 7 votes |
def visualize_2D_trip(self,trip,tw_open,tw_close): plt.figure(figsize=(30,30)) rcParams.update({'font.size': 22}) # Plot cities colors = ['red'] # Depot is first city for i in range(len(tw_open)-1): colors.append('blue') plt.scatter(trip[:,0], trip[:,1], color=colors, s=200) # Plot tour tour=np.array(list(range(len(trip))) + [0]) X = trip[tour, 0] Y = trip[tour, 1] plt.plot(X, Y,"--", markersize=100) # Annotate cities with TW tw_open = np.rint(tw_open) tw_close = np.rint(tw_close) time_window = np.concatenate((tw_open,tw_close),axis=1) for tw, (x, y) in zip(time_window,(zip(X,Y))): plt.annotate(tw,xy=(x, y)) plt.xlim(0,60) plt.ylim(0,60) plt.show() # Heatmap of permutations (x=cities; y=steps)
Example #3
Source File: kaldi_data.py From EEND with MIT License | 6 votes |
def extract_segments(wavs, segments=None): """ This function returns generator of segmented audio as (utterance id, numpy.float32 array) TODO?: sampling rate is not converted. """ if segments is not None: # segments should be sorted by rec-id for seg in segments: wav = wavs[seg['rec']] data, samplerate = load_wav(wav) st_sample = np.rint(seg['st'] * samplerate).astype(int) et_sample = np.rint(seg['et'] * samplerate).astype(int) yield seg['utt'], data[st_sample:et_sample] else: # segments file not found, # wav.scp is used as segmented audio list for rec in wavs: data, samplerate = load_wav(wavs[rec]) yield rec, data
Example #4
Source File: data_io.py From pase with MIT License | 6 votes |
def read_segments_as_bool_vec(segments_file): """ [ bool_vec ] = read_segments_as_bool_vec(segments_file) using kaldi 'segments' file for 1 wav, format : '<utt> <rec> <t-beg> <t-end>' - t-beg, t-end is in seconds, - assumed 100 frames/second, """ segs = np.loadtxt(segments_file, dtype='object,object,f,f', ndmin=1) # Sanity checks, assert(len(segs) > 0) # empty segmentation is an error, assert(len(np.unique([rec[1] for rec in segs ])) == 1) # segments with only 1 wav-file, # Convert time to frame-indexes, start = np.rint([100 * rec[2] for rec in segs]).astype(int) end = np.rint([100 * rec[3] for rec in segs]).astype(int) # Taken from 'read_lab_to_bool_vec', htk.py, frms = np.repeat(np.r_[np.tile([False,True], len(end)), False], np.r_[np.c_[start - np.r_[0, end[:-1]], end-start].flat, 0]) assert np.sum(end-start) == np.sum(frms) return frms
Example #5
Source File: utils.py From redshells with MIT License | 6 votes |
def optimize_model(task, param_name, test_size: float, binary=False) -> None: x, y = task.create_train_data() def objective(trial): train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=test_size) param = redshells.factory.get_optuna_param(param_name, trial) model = task.create_model() model.set_params(**param) model.fit(train_x, train_y) predictions = model.predict(test_x) if binary: predictions = np.rint(predictions) return 1.0 - sklearn.metrics.accuracy_score(test_y, predictions) study = optuna.create_study() study.optimize(objective, n_trials=100) task.dump(dict(best_params=study.best_params, best_value=study.best_value))
Example #6
Source File: generic.py From pyiron with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_k_mesh_by_cell(self, kpoints_per_reciprocal_angstrom, cell=None): """ get k-mesh density according to the box size. Args: kpoints_per_reciprocal_angstrom: (float) number of k-points per reciprocal angstrom (i.e. per 2*pi*box_length) cell: (list/ndarray) 3x3 cell. If not set, the current cell is used. """ if cell is None: if self.structure is None: raise AssertionError('structure not set') cell = self.structure.cell latlens = np.linalg.norm(cell, axis=-1) kmesh = np.rint( 2 * np.pi / latlens * kpoints_per_reciprocal_angstrom) if kmesh.min() <= 0: raise AssertionError("kpoint per angstrom too low") return [int(k) for k in kmesh]
Example #7
Source File: waveclussortingextractor.py From spikeextractors with MIT License | 6 votes |
def __init__(self, file_path: PathType): super().__init__(file_path) cluster_classes = self._getfield("cluster_class") classes = cluster_classes[:, 0] spike_times = cluster_classes[:, 1] par = self._getfield("par") sample_rate = par[0, 0][np.where(np.array(par.dtype.names) == 'sr')[0][0]][0][0] self.set_sampling_frequency(sample_rate) self._unit_ids = np.unique(classes[classes > 0]).astype('int') self._spike_trains = {} for uid in self._unit_ids: mask = (classes == uid) self._spike_trains[uid] = np.rint(spike_times[mask]*(sample_rate/1000)) self._unsorted_train = np.rint(spike_times[classes == 0] * (sample_rate / 1000))
Example #8
Source File: train_confusion.py From glc with Apache License 2.0 | 6 votes |
def get_C_hat_transpose(): probs = [] net.eval() for batch_idx, (data, target) in enumerate(train_gold_deterministic_loader): # we subtract 10 because we added 10 to gold so we could identify which example is gold in train_phase2 data, target = torch.autograd.Variable(data.cuda(), volatile=True),\ torch.autograd.Variable((target - num_classes).cuda(), volatile=True) # forward output = net(data) pred = F.softmax(output) probs.extend(list(pred.data.cpu().numpy())) probs = np.array(probs, dtype=np.float32) preds = np.argmax(probs, axis=1) C_hat = np.zeros([num_classes, num_classes]) for i in range(len(train_data_gold.train_labels)): C_hat[int(np.rint(train_data_gold.train_labels[i] - num_classes)), preds[i]] += 1 C_hat /= (np.sum(C_hat, axis=1, keepdims=True) + 1e-7) C_hat = C_hat * 0.99 + np.full_like(C_hat, 1/num_classes) * 0.01 # smoothing return C_hat.T.astype(np.float32)
Example #9
Source File: Functions.py From Jalali-Lab-Implementation-of-RAISR with GNU General Public License v3.0 | 6 votes |
def BGR2YCbCr(im): mat = np.array([[24.966, 128.553, 65.481],[112, -74.203, -37.797], [-18.214, -93.786, 112]]) mat = mat.T offset = np.array([[[16, 128, 128]]]) if im.dtype == 'uint8': mat = mat/255 out = np.dot(im,mat) + offset out = np.clip(out, 0, 255) out = np.rint(out).astype('uint8') elif im.dtype == 'float': mat = mat/255 offset = offset/255 out = np.dot(im, mat) + offset out = np.clip(out, 0, 1) else: assert False return out
Example #10
Source File: kaldi_io.py From Attentive-Filtering-Network with MIT License | 6 votes |
def read_segments_as_bool_vec(segments_file): """ [ bool_vec ] = read_segments_as_bool_vec(segments_file) using kaldi 'segments' file for 1 wav, format : '<utt> <rec> <t-beg> <t-end>' - t-beg, t-end is in seconds, - assumed 100 frames/second, """ segs = np.loadtxt(segments_file, dtype='object,object,f,f', ndmin=1) # Sanity checks, assert(len(segs) > 0) # empty segmentation is an error, assert(len(np.unique([rec[1] for rec in segs ])) == 1) # segments with only 1 wav-file, # Convert time to frame-indexes, start = np.rint([100 * rec[2] for rec in segs]).astype(int) end = np.rint([100 * rec[3] for rec in segs]).astype(int) # Taken from 'read_lab_to_bool_vec', htk.py, frms = np.repeat(np.r_[np.tile([False,True], len(end)), False], np.r_[np.c_[start - np.r_[0, end[:-1]], end-start].flat, 0]) assert np.sum(end-start) == np.sum(frms) return frms
Example #11
Source File: hrv_utils.py From NeuroKit with MIT License | 6 votes |
def _hrv_get_rri(peaks=None, sampling_rate=1000, interpolate=False, **kwargs): rri = np.diff(peaks) / sampling_rate * 1000 if interpolate is False: return rri else: # Minimum sampling rate for interpolation if sampling_rate < 10: sampling_rate = 10 # Compute length of interpolated heart period signal at requested sampling rate. desired_length = int(np.rint(peaks[-1] / sampling_rate * sampling_rate)) rri = signal_interpolate( peaks[1:], # Skip first peak since it has no corresponding element in heart_period rri, x_new=np.arange(desired_length), **kwargs ) return rri, sampling_rate
Example #12
Source File: Functions.py From Jalali-Lab-Implementation-of-RAISR with GNU General Public License v3.0 | 6 votes |
def YCbCr2BGR(im): mat = np.array([[24.966, 128.553, 65.481],[112, -74.203, -37.797], [-18.214, -93.786, 112]]) mat = mat.T mat = np.linalg.inv(mat) offset = np.array([[[16, 128, 128]]]) if im.dtype == 'uint8': mat = mat * 255 out = np.dot((im - offset),mat) out = np.clip(out, 0, 255) out = np.rint(out).astype('uint8') elif im.dtype == 'float': mat = mat * 255 offset = offset/255 out = np.dot((im - offset),mat) out = np.clip(out, 0, 1) else: assert False return out
Example #13
Source File: mesh_affine_equ.py From pyscf with Apache License 2.0 | 6 votes |
def __init__(self, **kw): """ Constructor of affine, equidistant 3d mesh class ucell : unit cell vectors (in coordinate space) Ecut : Energy cutoff to parametrize the discretization """ from scipy.fftpack import next_fast_len self.ucell = kw['ucell'] if 'ucell' in kw else 30.0*np.eye(3) # Not even unit cells vectors are required by default self.Ecut = Ecut = kw['Ecut'] if 'Ecut' in kw else 50.0 # 50.0 Hartree by default luc = np.sqrt(np.einsum('ix,ix->i', self.ucell, self.ucell)) self.shape = nn = np.array([next_fast_len( int(np.rint(l * np.sqrt(Ecut)/2))) for l in luc], dtype=int) self.size = np.prod(self.shape) gc = self.ucell/(nn) # This is probable the best for finite systems, for PBC use nn, not (nn-1) self.dv = np.abs(np.dot(gc[0], np.cross(gc[1], gc[2] ))) rr = [np.array([gc[i]*j for j in range(nn[i])]) for i in range(3)] self.rr = rr self.origin = kw['origin'] if 'origin' in kw else np.zeros(3)
Example #14
Source File: test_numpy_extractors.py From spikeextractors with MIT License | 6 votes |
def setUp(self): M = 4 N = 10000 seed= 0 sampling_frequency = 30000 X = np.random.RandomState(seed=seed).normal(0, 1, (M, N)) geom = np.random.RandomState(seed=seed).normal(0, 1, (M, 2)) self._X = X self._geom = geom self._sampling_frequency = sampling_frequency self.RX = se.NumpyRecordingExtractor(timeseries=X, sampling_frequency=sampling_frequency, geom=geom) self.SX = se.NumpySortingExtractor() L = 200 self._train1 = np.rint(np.random.RandomState(seed=seed).uniform(0, N, L)).astype(int) self.SX.add_unit(unit_id=1, times=self._train1) self.SX.add_unit(unit_id=2, times=np.random.RandomState(seed=seed).uniform(0, N, L)) self.SX.add_unit(unit_id=3, times=np.random.RandomState(seed=seed).uniform(0, N, L))
Example #15
Source File: kpts_helper.py From pyscf with Apache License 2.0 | 6 votes |
def get_kconserv(cell, kpts): r'''Get the momentum conservation array for a set of k-points. Given k-point indices (k, l, m) the array kconserv[k,l,m] returns the index n that satifies momentum conservation, (k(k) - k(l) + k(m) - k(n)) \dot a = 2n\pi This is used for symmetry e.g. integrals of the form [\phi*[k](1) \phi[l](1) | \phi*[m](2) \phi[n](2)] are zero unless n satisfies the above. ''' nkpts = kpts.shape[0] a = cell.lattice_vectors() / (2*np.pi) kconserv = np.zeros((nkpts,nkpts,nkpts), dtype=int) kvKLM = kpts[:,None,None,:] - kpts[:,None,:] + kpts for N, kvN in enumerate(kpts): kvKLMN = np.einsum('wx,klmx->wklm', a, kvKLM - kvN) # check whether (1/(2pi) k_{KLMN} dot a) is an integer kvKLMN_int = np.rint(kvKLMN) mask = np.einsum('wklm->klm', abs(kvKLMN - kvKLMN_int)) < 1e-9 kconserv[mask] = N return kconserv
Example #16
Source File: utils.py From yolo_v2 with Apache License 2.0 | 6 votes |
def visualize_voxel_spectral(points, vis_size=128): """Function to visualize voxel (spectral).""" points = np.rint(points) points = np.swapaxes(points, 0, 2) fig = p.figure(figsize=(1, 1), dpi=vis_size) verts, faces = measure.marching_cubes_classic(points, 0, spacing=(0.1, 0.1, 0.1)) ax = fig.add_subplot(111, projection='3d') ax.plot_trisurf( verts[:, 0], verts[:, 1], faces, verts[:, 2], cmap='Spectral_r', lw=0.1) ax.set_axis_off() fig.tight_layout(pad=0) fig.canvas.draw() data = np.fromstring( fig.canvas.tostring_rgb(), dtype=np.uint8, sep='').reshape( vis_size, vis_size, 3) p.close('all') return data
Example #17
Source File: integer_from_float_operator.py From pymoo with Apache License 2.0 | 6 votes |
def apply_float_operation(problem, fun): # save the original bounds of the problem _xl, _xu = problem.xl, problem.xu # copy the arrays of the problem and cast them to float xl, xu = problem.xl.astype(np.float), problem.xu.astype(np.float) # modify the bounds to match the new crossover specifications and set the problem problem.xl = xl - (0.5 - 1e-16) problem.xu = xu + (0.5 - 1e-16) # perform the crossover off = fun() # now round to nearest integer for all offsprings off = np.rint(off).astype(np.int) # reset the original bounds of the problem and design space values problem.xl = _xl problem.xu = _xu return off
Example #18
Source File: som.py From pyERA with MIT License | 6 votes |
def __init__(self, matrix_size, input_size, low=0, high=1, round_values=False): """Init function. @param matrix_size It defines the matrix size @param input_size it defines the vector input size. @param low boundary for the random initialization @param high boundary for the random initialization @param round_values it is possible to initialize the weights to the closest integer value. """ self._matrix_size = matrix_size self._input_size = input_size self._weights_matrix = np.random.uniform(low=low, high=high, size=(matrix_size, matrix_size, input_size)) if (round_values == True): self._weights_matrix = np.rint(self._weights_matrix)
Example #19
Source File: dataset_tool.py From disentangling_conditional_gans with MIT License | 6 votes |
def add_image(self, img): if self.print_progress and self.cur_images % self.progress_interval == 0: print('%d / %d\r' % (self.cur_images, self.expected_images), end='', flush=True) sys.stdout.flush() if self.shape is None: self.shape = img.shape self.resolution_log2 = int(np.log2(self.shape[1])) assert self.shape[0] in [1, 3] assert self.shape[1] == self.shape[2] assert self.shape[1] == 2**self.resolution_log2 tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE) for lod in range(self.resolution_log2 - 1): tfr_file = self.tfr_prefix + '-r%02d.tfrecords' % (self.resolution_log2 - lod) self.tfr_writers.append(tf.python_io.TFRecordWriter(tfr_file, tfr_opt)) assert img.shape == self.shape for lod, tfr_writer in enumerate(self.tfr_writers): if lod: img = img.astype(np.float32) img = (img[:, 0::2, 0::2] + img[:, 0::2, 1::2] + img[:, 1::2, 0::2] + img[:, 1::2, 1::2]) * 0.25 quant = np.rint(img).clip(0, 255).astype(np.uint8) ex = tf.train.Example(features=tf.train.Features(feature={ 'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=quant.shape)), 'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[quant.tostring()]))})) tfr_writer.write(ex.SerializeToString()) self.cur_images += 1
Example #20
Source File: _workflow.py From oggm with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _get_centerline_lonlat(gdir): """Quick n dirty solution to write the centerlines as a shapefile""" cls = gdir.read_pickle('centerlines') olist = [] for j, cl in enumerate(cls[::-1]): mm = 1 if j == 0 else 0 gs = dict() gs['RGIID'] = gdir.rgi_id gs['LE_SEGMENT'] = np.rint(np.max(cl.dis_on_line) * gdir.grid.dx) gs['MAIN'] = mm tra_func = partial(gdir.grid.ij_to_crs, crs=wgs84) gs['geometry'] = shp_trafo(tra_func, cl.line) olist.append(gs) return olist
Example #21
Source File: test_prepro.py From oggm with BSD 3-Clause "New" or "Revised" License | 6 votes |
def read_svgcoords(svg_file): """Get the vertices coordinates out of a SVG file""" from xml.dom import minidom doc = minidom.parse(svg_file) coords = [path.getAttribute('d') for path in doc.getElementsByTagName('path')] doc.unlink() _, _, coords = coords[0].partition('C') x = [] y = [] for c in coords.split(' '): if c == '': continue c = c.split(',') x.append(np.float(c[0])) y.append(np.float(c[1])) x.append(x[0]) y.append(y[0]) return np.rint(np.asarray((x, y)).T).astype(np.int64)
Example #22
Source File: test_cholesky.py From chainer with MIT License | 5 votes |
def random_matrix(self, shape, dtype, scale, sym=False): m, n = shape[-2:] dtype = numpy.dtype(dtype) assert dtype.kind in 'iufc' low_s, high_s = scale bias = None if dtype.kind in 'iu': err = numpy.sqrt(m * n) / 2. low_s += err high_s -= err if dtype.kind in 'u': assert sym, ( 'generating nonsymmetric matrix with uint cells is not' ' supported') # (singular value of numpy.ones((m, n))) <= \sqrt{mn} high_s = bias = high_s / (1 + numpy.sqrt(m * n)) assert low_s <= high_s a = numpy.random.standard_normal(shape) u, s, vh = numpy.linalg.svd(a) new_s = numpy.random.uniform(low_s, high_s, s.shape) if sym: assert m == n new_a = numpy.einsum('...ij,...j,...kj', u, new_s, u) else: new_a = numpy.einsum('...ij,...j,...jk', u, new_s, vh) if bias is not None: new_a += bias if dtype.kind in 'iu': new_a = numpy.rint(new_a) return new_a.astype(dtype)
Example #23
Source File: utils.py From yolo_v2 with Apache License 2.0 | 5 votes |
def visualize_voxel_scatter(points, vis_size=128): """Function to visualize voxel (scatter).""" points = np.rint(points) points = np.swapaxes(points, 0, 2) fig = p.figure(figsize=(1, 1), dpi=vis_size) ax = fig.add_subplot(111, projection='3d') x = [] y = [] z = [] (x_dimension, y_dimension, z_dimension) = points.shape for i in range(x_dimension): for j in range(y_dimension): for k in range(z_dimension): if points[i, j, k]: x.append(i) y.append(j) z.append(k) ax.scatter3D(x, y, z) ax.set_axis_off() fig.tight_layout(pad=0) fig.canvas.draw() data = np.fromstring( fig.canvas.tostring_rgb(), dtype=np.uint8, sep='').reshape( vis_size, vis_size, 3) p.close('all') return data
Example #24
Source File: theil_sen.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def _check_subparams(self, n_samples, n_features): n_subsamples = self.n_subsamples if self.fit_intercept: n_dim = n_features + 1 else: n_dim = n_features if n_subsamples is not None: if n_subsamples > n_samples: raise ValueError("Invalid parameter since n_subsamples > " "n_samples ({0} > {1}).".format(n_subsamples, n_samples)) if n_samples >= n_features: if n_dim > n_subsamples: plus_1 = "+1" if self.fit_intercept else "" raise ValueError("Invalid parameter since n_features{0} " "> n_subsamples ({1} > {2})." "".format(plus_1, n_dim, n_samples)) else: # if n_samples < n_features if n_subsamples != n_samples: raise ValueError("Invalid parameter since n_subsamples != " "n_samples ({0} != {1}) while n_samples " "< n_features.".format(n_subsamples, n_samples)) else: n_subsamples = min(n_dim, n_samples) if self.max_subpopulation <= 0: raise ValueError("Subpopulation must be strictly positive " "({0} <= 0).".format(self.max_subpopulation)) all_combinations = max(1, np.rint(binom(n_samples, n_subsamples))) n_subpopulation = int(min(self.max_subpopulation, all_combinations)) return n_subsamples, n_subpopulation
Example #25
Source File: atomistic.py From pyiron with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_displacements(structure, positions, cells, varying_cell=False): """ Output for 3-d displacements between successive snapshots, with minimum image convention. For the total displacements from the initial configuration, use total_displacements This algorithm collapses if: - the ID's are not consistent (i.e. you can also not change the number of atoms) - there are atoms which move by more than half a box length in any direction within two snapshots (due to periodic boundary conditions) Args: structure (pyiron.atomistics.structure.atoms.Atoms): The initial structure positions (numpy.ndarray/list): List of positions in cartesian coordinates (N_steps x N_atoms x 3) cells (numpy.ndarray/list): List of cells (N_steps x 3 x 3) varying_cell (bool): True if the cell shape varies during the trajectory (raises a warning) Returns: numpy.ndarray: Displacements (N_steps x N_atoms x 3) """ if not varying_cell: displacement = np.tensordot(positions, np.linalg.inv(cells[-1]), axes=([2, 0])) displacement -= np.append(structure.get_scaled_positions(), displacement).reshape(len(positions) + 1, len(structure), 3)[:-1] displacement -= np.rint(displacement) displacement = np.tensordot(displacement, cells[-1], axes=([2, 0])) else: warnings.warn("You are computing displacements in a simulation with periodic boundary conditions \n" "and a varying cell shape.") displacement = np.array( [np.tensordot(pos, np.linalg.inv(cell), axes=([1, 1])) for pos, cell in zip(positions, cells)]) displacement -= np.append(structure.get_scaled_positions(), displacement).reshape(len(positions) + 1, len(structure), 3)[:-1] displacement -= np.rint(displacement) displacement = np.einsum('nki,nji->nkj', displacement, cells) return displacement
Example #26
Source File: test_umath.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def test_rint_big_int(): # np.rint bug for large integer values on Windows 32-bit and MKL # https://github.com/numpy/numpy/issues/6685 val = 4607998452777363968 # This is exactly representable in floating point assert_equal(val, int(float(val))) # Rint should not change the value assert_equal(val, np.rint(val))
Example #27
Source File: numpyextractors.py From spikeextractors with MIT License | 5 votes |
def get_unit_spike_train(self, unit_id, start_frame=None, end_frame=None): start_frame, end_frame = self._cast_start_end_frame(start_frame, end_frame) if start_frame is None: start_frame = 0 if end_frame is None: end_frame = np.Inf times = self._units[unit_id]['times'] inds = np.where((start_frame <= times) & (times < end_frame))[0] return np.rint(times[inds]).astype(int)
Example #28
Source File: mdaextractors.py From spikeextractors with MIT License | 5 votes |
def get_unit_spike_train(self, unit_id, start_frame=None, end_frame=None): start_frame, end_frame = self._cast_start_end_frame(start_frame, end_frame) if start_frame is None: start_frame = 0 if end_frame is None: end_frame = np.Inf inds = np.where((self._labels == unit_id) & (start_frame <= self._times) & (self._times < end_frame)) return np.rint(self._times[inds]).astype(int)
Example #29
Source File: mearecextractors.py From spikeextractors with MIT License | 5 votes |
def get_unit_spike_train(self, unit_id, start_frame=None, end_frame=None): start_frame, end_frame = self._cast_start_end_frame(start_frame, end_frame) if start_frame is None: start_frame = 0 if end_frame is None: end_frame = np.Inf if self._spike_trains is None: self._initialize() times = (self._spike_trains[self.get_unit_ids().index(unit_id)].times.rescale('s') * self._fs.rescale('Hz')).magnitude inds = np.where((start_frame <= times) & (times < end_frame)) return np.rint(times[inds]).astype(int)
Example #30
Source File: apls_utils.py From apls with Apache License 2.0 | 5 votes |
def get_pixel_dist_from_meters(im_test_file, len_meters): '''For the input image, we want a buffer or other distance in meters, this function determines the pixel distance by calculating the GSD''' gsd = get_gsd(im_test_file) pix_width = max(1, np.rint(len_meters/gsd)) return gsd, pix_width ###############################################################################