Python numpy.uint() Examples
The following are 30 code examples for showing how to use numpy.uint(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example 1
Project: me-ica Author: ME-ICA File: test_scaling.py License: GNU Lesser General Public License v2.1 | 6 votes |
def test_scaling_in_abstract(): # Confirm that, for all ints and uints as input, and all possible outputs, # for any simple way of doing the calculation, the result is near enough for category0, category1 in (('int', 'int'), ('uint', 'int'), ): for in_type in np.sctypes[category0]: for out_type in np.sctypes[category1]: check_int_a2f(in_type, out_type) # Converting floats to integer for category0, category1 in (('float', 'int'), ('float', 'uint'), ('complex', 'int'), ('complex', 'uint'), ): for in_type in np.sctypes[category0]: for out_type in np.sctypes[category1]: check_int_a2f(in_type, out_type)
Example 2
Project: tf-pose Author: SrikanthVelpuri File: GLViewWidget.py License: Apache License 2.0 | 6 votes |
def itemsAt(self, region=None): """ Return a list of the items displayed in the region (x, y, w, h) relative to the widget. """ region = (region[0], self.height()-(region[1]+region[3]), region[2], region[3]) #buf = np.zeros(100000, dtype=np.uint) buf = glSelectBuffer(100000) try: glRenderMode(GL_SELECT) glInitNames() glPushName(0) self._itemNames = {} self.paintGL(region=region, useItemNames=True) finally: hits = glRenderMode(GL_RENDER) items = [(h.near, h.names[0]) for h in hits] items.sort(key=lambda i: i[0]) return [self._itemNames[i[1]] for i in items]
Example 3
Project: mars Author: mars-project File: histogram.py License: Apache License 2.0 | 6 votes |
def _unsigned_subtract(a, b): """ Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram """ # coerce to a single type signed_to_unsigned = { np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong } dt = np.result_type(a, b) try: dt = signed_to_unsigned[dt.type] except KeyError: # pragma: no cover return np.subtract(a, b, dtype=dt) else: # we know the inputs are integers, and we are deliberately casting # signed to unsigned return np.subtract(a, b, casting='unsafe', dtype=dt)
Example 4
Project: lambda-packs Author: ryfeus File: histograms.py License: MIT License | 6 votes |
def _unsigned_subtract(a, b): """ Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram """ # coerce to a single type signed_to_unsigned = { np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong } dt = np.result_type(a, b) try: dt = signed_to_unsigned[dt.type] except KeyError: return np.subtract(a, b, dtype=dt) else: # we know the inputs are integers, and we are deliberately casting # signed to unsigned return np.subtract(a, b, casting='unsafe', dtype=dt)
Example 5
Project: ngraph-python Author: NervanaSystems File: mnist_training.py License: Apache License 2.0 | 6 votes |
def savetxt(filename, ndarray): dir = os.path.dirname(filename) if not os.path.exists(dir): os.makedirs(dir) if not os.path.isfile(filename): with open(filename, 'w') as f: labels = list(map(' '.join, np.eye(10, dtype=np.uint).astype(str))) for row in ndarray: row_str = row.astype(str) label_str = labels[row[-1]] feature_str = ' '.join(row_str[:-1]) f.write('|labels {} |features {}\n'.format(label_str, feature_str)) else: print("File already exists", filename)
Example 6
Project: ai-gym Author: MattChanTK File: mnist_softmax_cntk.py License: MIT License | 6 votes |
def save_as_txt(filename, ndarray): dir = os.path.dirname(filename) if not os.path.exists(dir): os.makedirs(dir) if not os.path.isfile(filename): print("Saving to ", filename, end=" ") with open(filename, 'w') as f: labels = list(map(' '.join, np.eye(10, dtype=np.uint).astype(str))) for row in ndarray: row_str = row.astype(str) label_str = labels[row[-1]] feature_str = ' '.join(row_str[:-1]) f.write('|labels {} |features {}\n'.format(label_str, feature_str)) else: print("File already exists", filename)
Example 7
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: histograms.py License: MIT License | 6 votes |
def _unsigned_subtract(a, b): """ Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram """ # coerce to a single type signed_to_unsigned = { np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong } dt = np.result_type(a, b) try: dt = signed_to_unsigned[dt.type] except KeyError: return np.subtract(a, b, dtype=dt) else: # we know the inputs are integers, and we are deliberately casting # signed to unsigned return np.subtract(a, b, casting='unsafe', dtype=dt)
Example 8
Project: fastMRI Author: facebookresearch File: subsample.py License: MIT License | 6 votes |
def __call__(self, shape, seed, offset=None): fraction_low_freqs, acceleration = self.choose_acceleration(seed) num_cols = shape[-2] num_low_freqs = int(round(num_cols * fraction_low_freqs)) # Create the mask mask = np.zeros(num_cols, dtype=np.float32) pad = (num_cols - num_low_freqs + 1) // 2 mask[pad:pad + num_low_freqs] = True # Determine acceleration rate by adjusting for the number of low frequencies adjusted_accel = (acceleration * (num_low_freqs - num_cols)) / (num_low_freqs * acceleration - num_cols) if offset == None: offset = random.randrange(round(adjusted_accel)) accel_samples = np.arange(offset, num_cols - 1, adjusted_accel) accel_samples = np.around(accel_samples).astype(np.uint) mask[accel_samples] = True # Reshape the mask mask_shape = [1 for _ in shape] mask_shape[-2] = num_cols mask = torch.from_numpy(mask.reshape(*mask_shape).astype(np.float32)) return mask, num_low_freqs
Example 9
Project: Amulet-Core Author: Amulet-Team File: numpy_helpers.py License: MIT License | 6 votes |
def brute_sort_objects_no_hash(data) -> Tuple[numpy.ndarray, numpy.ndarray]: unique = [] inverse = numpy.zeros(dtype=numpy.uint, shape=len(data)) for i, d in enumerate(data): try: index = unique.index(d) except ValueError: index = len(unique) unique.append(d) inverse[i] = index unique_ = numpy.empty(len(unique), dtype=object) for index, obj in enumerate(unique): unique_[index] = obj return unique_, numpy.array(inverse)
Example 10
Project: sonata Author: AllenInstitute File: test_root.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_save_gids(thalamocortical): if os.path.exists('tmp/gid_table.h5'): os.remove('tmp/gid_table.h5') assert(thalamocortical.nodes.has_gids == False) thalamocortical.nodes.generate_gids(file_name='tmp/gid_table.h5') assert(os.path.exists('tmp/gid_table.h5')) gid_h5 = h5py.File('tmp/gid_table.h5', mode='r') assert('gid' in gid_h5) assert(len(gid_h5['gid']) == 9449) assert(np.issubdtype(gid_h5['gid'].dtype, np.uint)) assert('node_id' in gid_h5) assert(len(gid_h5['node_id']) == 9449) assert(np.issubdtype(gid_h5['node_id'].dtype, np.uint)) assert('population' in gid_h5) assert(len(gid_h5['population']) == 9449) print(gid_h5['population']) assert(np.issubdtype(gid_h5['population'].dtype, np.integer)) assert(set(np.unique(gid_h5['population'][...])) == set([0, 1])) assert(set(np.unique(gid_h5['population_names'][...])) == set(['v1', 'lgn']))
Example 11
Project: GraphicDesignPatternByPython Author: Relph1119 File: histograms.py License: MIT License | 6 votes |
def _unsigned_subtract(a, b): """ Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram """ # coerce to a single type signed_to_unsigned = { np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong } dt = np.result_type(a, b) try: dt = signed_to_unsigned[dt.type] except KeyError: return np.subtract(a, b, dtype=dt) else: # we know the inputs are integers, and we are deliberately casting # signed to unsigned return np.subtract(a, b, casting='unsafe', dtype=dt)
Example 12
Project: GraphicDesignPatternByPython Author: Relph1119 File: test_distance.py License: MIT License | 6 votes |
def test_pdist_dtype_equivalence(self): # Tests that the result is not affected by type up-casting eps = 1e-07 tests = [(eo['random-bool-data'], self.valid_upcasts['bool']), (eo['random-uint-data'], self.valid_upcasts['uint']), (eo['random-int-data'], self.valid_upcasts['int']), (eo['random-float32-data'], self.valid_upcasts['float32'])] for metric in _METRICS_NAMES: for test in tests: X1 = test[0][::5, ::2] try: y1 = pdist(X1, metric=metric) except Exception as e: e_cls = e.__class__ if verbose > 2: print(e_cls.__name__) print(e) for new_type in test[1]: X2 = new_type(X1) assert_raises(e_cls, pdist, X2, metric=metric) else: for new_type in test[1]: y2 = pdist(new_type(X1), metric=metric) _assert_within_tol(y1, y2, eps, verbose > 2)
Example 13
Project: deep_image_model Author: tobegit3hub File: dtypes_test.py License: Apache License 2.0 | 6 votes |
def testNumpyConversion(self): self.assertIs(tf.float32, tf.as_dtype(np.float32)) self.assertIs(tf.float64, tf.as_dtype(np.float64)) self.assertIs(tf.int32, tf.as_dtype(np.int32)) self.assertIs(tf.int64, tf.as_dtype(np.int64)) self.assertIs(tf.uint8, tf.as_dtype(np.uint8)) self.assertIs(tf.uint16, tf.as_dtype(np.uint16)) self.assertIs(tf.int16, tf.as_dtype(np.int16)) self.assertIs(tf.int8, tf.as_dtype(np.int8)) self.assertIs(tf.complex64, tf.as_dtype(np.complex64)) self.assertIs(tf.complex128, tf.as_dtype(np.complex128)) self.assertIs(tf.string, tf.as_dtype(np.object)) self.assertIs(tf.string, tf.as_dtype(np.array(["foo", "bar"]).dtype)) self.assertIs(tf.bool, tf.as_dtype(np.bool)) with self.assertRaises(TypeError): tf.as_dtype(np.dtype([("f1", np.uint), ("f2", np.int32)]))
Example 14
Project: predictive-maintenance-using-machine-learning Author: awslabs File: histograms.py License: Apache License 2.0 | 6 votes |
def _unsigned_subtract(a, b): """ Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram """ # coerce to a single type signed_to_unsigned = { np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong } dt = np.result_type(a, b) try: dt = signed_to_unsigned[dt.type] except KeyError: return np.subtract(a, b, dtype=dt) else: # we know the inputs are integers, and we are deliberately casting # signed to unsigned return np.subtract(a, b, casting='unsafe', dtype=dt)
Example 15
Project: qiskit-terra Author: Qiskit File: pauli.py License: Apache License 2.0 | 6 votes |
def to_spmatrix(self): r""" Convert Pauli to a sparse matrix representation (CSR format). Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$ Returns: scipy.sparse.csr_matrix: a sparse matrix with CSR format that represents the pauli. """ _x, _z = self._x, self._z n = 2**len(_x) twos_array = 1 << np.arange(len(_x)) xs = np.array(_x).dot(twos_array) zs = np.array(_z).dot(twos_array) rows = np.arange(n+1, dtype=np.uint) columns = rows ^ xs global_factor = (-1j)**np.dot(np.array(_x, dtype=np.uint), _z) data = global_factor*(-1)**np.mod(_count_set_bits(zs & rows), 2) return sparse.csr_matrix((data, columns, rows), shape=(n, n))
Example 16
Project: pySINDy Author: luckystarufo File: histograms.py License: MIT License | 6 votes |
def _unsigned_subtract(a, b): """ Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram """ # coerce to a single type signed_to_unsigned = { np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong } dt = np.result_type(a, b) try: dt = signed_to_unsigned[dt.type] except KeyError: return np.subtract(a, b, dtype=dt) else: # we know the inputs are integers, and we are deliberately casting # signed to unsigned return np.subtract(a, b, casting='unsafe', dtype=dt)
Example 17
Project: FashionAI_KeyPoint_Detection_Challenge_Keras Author: yuanyuanli85 File: data_process.py License: MIT License | 6 votes |
def rotate_image_with_invrmat(cvmat, rotateAngle): assert (cvmat.dtype == np.uint8) , " only support normalize np.uint in rotate_image_with_invrmat'" ##Make sure cvmat is square? height, width, channel = cvmat.shape center = ( width//2, height//2) rotateMatrix = cv2.getRotationMatrix2D(center, rotateAngle, 1.0) cos, sin = np.abs(rotateMatrix[0,0]), np.abs(rotateMatrix[0, 1]) newH = int((height*sin)+(width*cos)) newW = int((height*cos)+(width*sin)) rotateMatrix[0,2] += (newW/2) - center[0] #x rotateMatrix[1,2] += (newH/2) - center[1] #y # rotate image outMat = cv2.warpAffine(cvmat, rotateMatrix, (newH, newW), borderValue=(128, 128, 128)) # generate inv rotate matrix invRotateMatrix = cv2.invertAffineTransform(rotateMatrix) return (outMat, invRotateMatrix, (width, height))
Example 18
Project: sbb_textline_detection Author: qurator-spk File: main.py License: Apache License 2.0 | 6 votes |
def filter_contours_area_of_image(self, image, contours, hierarchy, max_area, min_area): found_polygons_early = list() jv = 0 for c in contours: if len(c) < 3: # A polygon cannot have less than 3 points continue polygon = geometry.Polygon([point[0] for point in c]) area = polygon.area if area >= min_area * np.prod(image.shape[:2]) and area <= max_area * np.prod( image.shape[:2]) and hierarchy[0][jv][3] == -1 : # and hierarchy[0][jv][3]==-1 : found_polygons_early.append( np.array([ [point] for point in polygon.exterior.coords], dtype=np.uint)) jv += 1 return found_polygons_early
Example 19
Project: sbb_textline_detection Author: qurator-spk File: main.py License: Apache License 2.0 | 6 votes |
def filter_contours_area_of_image_interiors(self, image, contours, hierarchy, max_area, min_area): found_polygons_early = list() jv = 0 for c in contours: if len(c) < 3: # A polygon cannot have less than 3 points continue polygon = geometry.Polygon([point[0] for point in c]) area = polygon.area if area >= min_area * np.prod(image.shape[:2]) and area <= max_area * np.prod(image.shape[:2]) and \ hierarchy[0][jv][3] != -1: # print(c[0][0][1]) found_polygons_early.append( np.array([point for point in polygon.exterior.coords], dtype=np.uint)) jv += 1 return found_polygons_early
Example 20
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc_4ch.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 21
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc_mllsll.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 22
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc_lbp.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 23
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 24
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc_4ch_rot.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 25
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc_lbp.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 26
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 27
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc_mllsll.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 28
Project: u24_lymphocyte Author: SBU-BMI File: conv_sup_cc_lbp.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def hit_mis(classn, Pr, Tr): print("Hit matrix:"); hit = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 1: hit[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit); print("Mis matrix:"); mis = np.zeros(shape=(classn, 2), dtype=np.uint); for i in range(Tr.shape[0]): for truth_ind in range(Tr.shape[1]): if Tr[i][truth_ind] == 0: mis[truth_ind, Pr[i][truth_ind]] += 1; print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis);
Example 29
Project: me-ica Author: ME-ICA File: test_scaling.py License: GNU Lesser General Public License v2.1 | 5 votes |
def test_finite_range(): # Finite range utility function a = np.array([[-1, 0, 1],[np.inf, np.nan, -np.inf]]) assert_equal(finite_range(a), (-1.0, 1.0)) a = np.array([[np.nan],[np.nan]]) assert_equal(finite_range(a), (np.inf, -np.inf)) a = np.array([[-3, 0, 1],[2,-1,4]], dtype=np.int) assert_equal(finite_range(a), (-3, 4)) a = np.array([[1, 0, 1],[2,3,4]], dtype=np.uint) assert_equal(finite_range(a), (0, 4)) a = a + 1j assert_raises(TypeError, finite_range, a) # 1D case a = np.array([0., 1, 2, 3]) assert_equal(finite_range(a), (0,3))
Example 30
Project: recruit Author: Frank-qlu File: histograms.py License: Apache License 2.0 | 5 votes |
def _unsigned_subtract(a, b): """ Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram """ # coerce to a single type signed_to_unsigned = { np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong } dt = np.result_type(a, b) try: dt = signed_to_unsigned[dt.type] except KeyError: return np.subtract(a, b, dtype=dt) else: # we know the inputs are integers, and we are deliberately casting # signed to unsigned return np.subtract(a, b, casting='unsafe', dtype=dt)