Python numpy.int16() Examples
The following are 30
code examples of numpy.int16().
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: test_utils.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_can_cast(): tests = ((np.float32, np.float32, True, True, True), (np.float64, np.float32, True, True, True), (np.complex128, np.float32, False, False, False), (np.float32, np.complex128, True, True, True), (np.float32, np.uint8, False, True, True), (np.uint32, np.complex128, True, True, True), (np.int64, np.float32, True, True, True), (np.complex128, np.int16, False, False, False), (np.float32, np.int16, False, True, True), (np.uint8, np.int16, True, True, True), (np.uint16, np.int16, False, True, True), (np.int16, np.uint16, False, False, True), (np.int8, np.uint16, False, False, True), (np.uint16, np.uint8, False, True, True), ) for intype, outtype, def_res, scale_res, all_res in tests: assert_equal(def_res, can_cast(intype, outtype)) assert_equal(scale_res, can_cast(intype, outtype, False, True)) assert_equal(all_res, can_cast(intype, outtype, True, True))
Example #2
Source File: audio.py From blow with Apache License 2.0 | 6 votes |
def synthesize(frames,filename,stride,sr=16000,deemph=0,ymax=0.98,normalize=False): # Generate stream y=torch.zeros((len(frames)-1)*stride+len(frames[0])) for i,x in enumerate(frames): y[i*stride:i*stride+len(x)]+=x # To numpy & deemph y=y.numpy().astype(np.float32) if deemph>0: y=deemphasis(y,alpha=deemph) # Normalize if normalize: y-=np.mean(y) mx=np.max(np.abs(y)) if mx>0: y*=ymax/mx else: y=np.clip(y,-ymax,ymax) # To 16 bit & save wavfile.write(filename,sr,np.array(y*32767,dtype=np.int16)) return y ########################################################################################################################
Example #3
Source File: test_casting.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_able_int_type(): # The integer type cabable of containing values for vals, exp_out in ( ([0, 1], np.uint8), ([0, 255], np.uint8), ([-1, 1], np.int8), ([0, 256], np.uint16), ([-1, 128], np.int16), ([0.1, 1], None), ([0, 2**16], np.uint32), ([-1, 2**15], np.int32), ([0, 2**32], np.uint64), ([-1, 2**31], np.int64), ([-1, 2**64-1], None), ([0, 2**64-1], np.uint64), ([0, 2**64], None)): assert_equal(able_int_type(vals), exp_out)
Example #4
Source File: test_spatialimages.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_isolation(self): # Test image isolated from external changes to header and affine img_klass = self.image_class arr = np.arange(3, dtype=np.int16) aff = np.eye(4) img = img_klass(arr, aff) assert_array_equal(img.get_affine(), aff) aff[0,0] = 99 assert_false(np.all(img.get_affine() == aff)) # header, created by image creation ihdr = img.get_header() # Pass it back in img = img_klass(arr, aff, ihdr) # Check modifying header outside does not modify image ihdr.set_zooms((4,)) assert_not_equal(img.get_header(), ihdr)
Example #5
Source File: test_arraywriters.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_writer_maker(): arr = np.arange(10, dtype=np.float64) aw = make_array_writer(arr, np.float64) assert_true(isinstance(aw, SlopeInterArrayWriter)) aw = make_array_writer(arr, np.float64, True, True) assert_true(isinstance(aw, SlopeInterArrayWriter)) aw = make_array_writer(arr, np.float64, True, False) assert_true(isinstance(aw, SlopeArrayWriter)) aw = make_array_writer(arr, np.float64, False, False) assert_true(isinstance(aw, ArrayWriter)) assert_raises(ValueError, make_array_writer, arr, np.float64, False) assert_raises(ValueError, make_array_writer, arr, np.float64, False, True) # Does calc_scale get run by default? aw = make_array_writer(arr, np.int16, calc_scale=False) assert_equal((aw.slope, aw.inter), (1, 0)) aw.calc_scale() slope, inter = aw.slope, aw.inter assert_false((slope, inter) == (1, 0)) # Should run by default aw = make_array_writer(arr, np.int16) assert_equal((aw.slope, aw.inter), (slope, inter)) aw = make_array_writer(arr, np.int16, calc_scale=True) assert_equal((aw.slope, aw.inter), (slope, inter))
Example #6
Source File: hdf5dtypeTest.py From hsds with Apache License 2.0 | 6 votes |
def testCreateBaseType(self): dt = hdf5dtype.createDataType('H5T_STD_U32BE') self.assertEqual(dt.name, 'uint32') self.assertEqual(dt.byteorder, '>') self.assertEqual(dt.kind, 'u') dt = hdf5dtype.createDataType('H5T_STD_I16LE') self.assertEqual(dt.name, 'int16') self.assertEqual(dt.kind, 'i') dt = hdf5dtype.createDataType('H5T_IEEE_F64LE') self.assertEqual(dt.name, 'float64') self.assertEqual(dt.kind, 'f') dt = hdf5dtype.createDataType('H5T_IEEE_F32LE') self.assertEqual(dt.name, 'float32') self.assertEqual(dt.kind, 'f') typeItem = { 'class': 'H5T_INTEGER', 'base': 'H5T_STD_I32BE' } typeSize = hdf5dtype.getItemSize(typeItem) dt = hdf5dtype.createDataType(typeItem) self.assertEqual(dt.name, 'int32') self.assertEqual(dt.kind, 'i') self.assertEqual(typeSize, 4)
Example #7
Source File: numpy_helper.py From pyscf with Apache License 2.0 | 6 votes |
def frompointer(pointer, count, dtype=float): '''Interpret a buffer that the pointer refers to as a 1-dimensional array. Args: pointer : int or ctypes pointer address of a buffer count : int Number of items to read. dtype : data-type, optional Data-type of the returned array; default: float. Examples: >>> s = numpy.ones(3, dtype=numpy.int32) >>> ptr = s.ctypes.data >>> frompointer(ptr, count=6, dtype=numpy.int16) [1, 0, 1, 0, 1, 0] ''' dtype = numpy.dtype(dtype) count *= dtype.itemsize buf = (ctypes.c_char * count).from_address(pointer) a = numpy.ndarray(count, dtype=numpy.int8, buffer=buf) return a.view(dtype)
Example #8
Source File: test_arraywriters.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_no_offset_scale(): # Specific tests of no-offset scaling SAW = SlopeArrayWriter # Floating point for data in ((-128, 127), (-128, 126), (-128, -127), (-128, 0), (-128, -1), (126, 127), (-127, 127)): aw = SAW(np.array(data, dtype=np.float32), np.int8) assert_equal(aw.slope, 1.0) aw = SAW(np.array([-126, 127 * 2.0], dtype=np.float32), np.int8) assert_equal(aw.slope, 2) aw = SAW(np.array([-128 * 2.0, 127], dtype=np.float32), np.int8) assert_equal(aw.slope, 2) # Test that nasty abs behavior does not upset us n = -2**15 aw = SAW(np.array([n, n], dtype=np.int16), np.uint8) assert_array_almost_equal(aw.slope, n / 255.0, 5)
Example #9
Source File: utils.py From sklearn-audio-transfer-learning with ISC License | 6 votes |
def wavefile_to_waveform(wav_file, features_type): data, sr = sf.read(wav_file) if features_type == 'vggish': tmp_name = str(int(np.random.rand(1)*1000000)) + '.wav' sf.write(tmp_name, data, sr, subtype='PCM_16') sr, wav_data = wavfile.read(tmp_name) os.remove(tmp_name) # sr, wav_data = wavfile.read(wav_file) # as done in VGGish Audioset assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype data = wav_data / 32768.0 # Convert to [-1.0, +1.0] # at least one second of samples, if not repead-pad src_repeat = data while (src_repeat.shape[0] < sr): src_repeat = np.concatenate((src_repeat, data), axis=0) data = src_repeat[:sr] return data, sr
Example #10
Source File: test_arrayproxy.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_nifti1_init(): bio = BytesIO() shape = (2,3,4) hdr = Nifti1Header() arr = np.arange(24, dtype=np.int16).reshape(shape) write_raw_data(arr, hdr, bio) hdr.set_slope_inter(2, 10) ap = ArrayProxy(bio, hdr) assert_true(ap.file_like == bio) assert_equal(ap.shape, shape) # Check there has been a copy of the header assert_false(ap.header is hdr) # Get the data assert_array_equal(np.asarray(ap), arr * 2.0 + 10) with InTemporaryDirectory(): f = open('test.nii', 'wb') write_raw_data(arr, hdr, f) f.close() ap = ArrayProxy('test.nii', hdr) assert_true(ap.file_like == 'test.nii') assert_equal(ap.shape, shape) assert_array_equal(np.asarray(ap), arr * 2.0 + 10)
Example #11
Source File: test_scaling.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_calculate_scale(): # Test for special cases in scale calculation npa = np.array # Here the offset handles it res = calculate_scale(npa([-2, -1], dtype=np.int8), np.uint8, True) assert_equal(res, (1.0, -2.0, None, None)) # Not having offset not a problem obviously res = calculate_scale(npa([-2, -1], dtype=np.int8), np.uint8, 0) assert_equal(res, (-1.0, 0.0, None, None)) # Case where offset handles scaling res = calculate_scale(npa([-1, 1], dtype=np.int8), np.uint8, 1) assert_equal(res, (1.0, -1.0, None, None)) # Can't work for no offset case assert_raises(ValueError, calculate_scale, npa([-1, 1], dtype=np.int8), np.uint8, 0) # Offset trick can't work when max is out of range res = calculate_scale(npa([-1, 255], dtype=np.int16), np.uint8, 1) assert_not_equal(res, (1.0, -1.0, None, None))
Example #12
Source File: cutoff.py From GST-Tacotron with MIT License | 6 votes |
def cutoff(input_wav, output_wav): ''' input_wav --- input wav file path output_wav --- output wav file path ''' # read input wave file and get parameters. with wave.open(input_wav, 'r') as fw: params = fw.getparams() # print(params) nchannels, sampwidth, framerate, nframes = params[:4] strData = fw.readframes(nframes) waveData = np.fromstring(strData, dtype=np.int16) max_v = np.max(abs(waveData)) for i in range(waveData.shape[0]): if abs(waveData[i]) > 0.08 * max_v: break for j in range(waveData.shape[0] - 1, 0, -1): if abs(waveData[j]) > 0.08 * max_v: break # write new wav file with wave.open(output_wav, 'w') as fw: params = list(params) params[3] = nframes - i - (waveData.shape[0] - 1 - j) fw.setparams(params) fw.writeframes(strData[2 * i:2 * (j + 1)])
Example #13
Source File: xferfcn_input_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_clean_part_tuple_list_array(self): """Tuple of list of numpy arrays for all valid types.""" for dtype in int, int8, int16, int32, int64, float, float16, float32, float64, longdouble: num = ([array([1, 1], dtype=dtype), array([2, 2], dtype=dtype)],) num_ = _clean_part(num) assert isinstance(num_, list) assert np.all([isinstance(part, list) for part in num_]) np.testing.assert_array_equal(num_[0][0], array([1.0, 1.0], dtype=float)) np.testing.assert_array_equal(num_[0][1], array([2.0, 2.0], dtype=float))
Example #14
Source File: xferfcn_input_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_clean_part_tuple_tuples_arrays(self): """Tuple of tuples of numpy arrays for all valid types.""" for dtype in int, int8, int16, int32, int64, float, float16, float32, float64, longdouble: num = ((array([1, 1], dtype=dtype), array([2, 2], dtype=dtype)), (array([3, 4], dtype=dtype), array([4, 4], dtype=dtype))) num_ = _clean_part(num) assert isinstance(num_, list) assert np.all([isinstance(part, list) for part in num_]) np.testing.assert_array_equal(num_[0][0], array([1.0, 1.0], dtype=float)) np.testing.assert_array_equal(num_[0][1], array([2.0, 2.0], dtype=float))
Example #15
Source File: xferfcn_input_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_clean_part_tuple_all_types2(self): """Test tuple of a single value for all data types.""" for dtype in [int, int8, int16, int32, int64, float, float16, float32, float64, longdouble]: num = (dtype(1), dtype(2)) num_ = _clean_part(num) assert isinstance(num_, list) assert np.all([isinstance(part, list) for part in num_]) np.testing.assert_array_equal(num_[0][0], array([1, 2], dtype=float))
Example #16
Source File: xferfcn_input_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_clean_part_list_list_array(self): """List of list of numpy arrays for all valid types.""" for dtype in int, int8, int16, int32, int64, float, float16, float32, float64, longdouble: num = [[array([1, 1], dtype=dtype), array([2, 2], dtype=dtype)]] num_ = _clean_part(num) assert isinstance(num_, list) assert np.all([isinstance(part, list) for part in num_]) np.testing.assert_array_equal(num_[0][0], array([1.0, 1.0], dtype=float)) np.testing.assert_array_equal(num_[0][1], array([2.0, 2.0], dtype=float))
Example #17
Source File: test_spm99analyze.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_scaling(self): hdr = self.header_class() hdr.set_data_shape((1,2,3)) hdr.set_data_dtype(np.int16) S3 = BytesIO() data = np.arange(6, dtype=np.float64).reshape((1,2,3)) # This uses scaling hdr.data_to_fileobj(data, S3) data_back = hdr.data_from_fileobj(S3) assert_array_almost_equal(data, data_back, 4) # This is exactly the same call, just testing it works twice data_back2 = hdr.data_from_fileobj(S3) assert_array_equal(data_back, data_back2, 4)
Example #18
Source File: xferfcn_input_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_clean_part_list_tuple_array(self): """List of tuple of numpy array for all valid types.""" for dtype in int, int8, int16, int32, int64, float, float16, float32, float64, longdouble: num = [(array([1, 1], dtype=dtype), array([2, 2], dtype=dtype))] num_ = _clean_part(num) assert isinstance(num_, list) assert np.all([isinstance(part, list) for part in num_]) np.testing.assert_array_equal(num_[0][0], array([1.0, 1.0], dtype=float)) np.testing.assert_array_equal(num_[0][1], array([2.0, 2.0], dtype=float))
Example #19
Source File: detect_face.py From insightface with MIT License | 5 votes |
def nms(boxes, threshold, method): if boxes.size==0: return np.empty((0,3)) x1 = boxes[:,0] y1 = boxes[:,1] x2 = boxes[:,2] y2 = boxes[:,3] s = boxes[:,4] area = (x2-x1+1) * (y2-y1+1) I = np.argsort(s) pick = np.zeros_like(s, dtype=np.int16) counter = 0 while I.size>0: i = I[-1] pick[counter] = i counter += 1 idx = I[0:-1] xx1 = np.maximum(x1[i], x1[idx]) yy1 = np.maximum(y1[i], y1[idx]) xx2 = np.minimum(x2[i], x2[idx]) yy2 = np.minimum(y2[i], y2[idx]) w = np.maximum(0.0, xx2-xx1+1) h = np.maximum(0.0, yy2-yy1+1) inter = w * h if method is 'Min': o = inter / np.minimum(area[i], area[idx]) else: o = inter / (area[i] + area[idx] - inter) I = I[np.where(o<=threshold)] pick = pick[0:counter] return pick # function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h)
Example #20
Source File: vgm_to_wav.py From nesmdb with MIT License | 5 votes |
def save_vgmwav(wav_fp, wav): wav *= 32767. wav = np.clip(wav, -32768., 32767.) wav = wav.astype(np.int16) wavwrite(wav_fp, 44100, wav)
Example #21
Source File: test_nifti1.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_big_scaling(self): # Test that upcasting works for huge scalefactors # See tests for apply_read_scaling in test_utils hdr = self.header_class() hdr.set_data_shape((2,1,1)) hdr.set_data_dtype(np.int16) sio = BytesIO() dtt = np.float32 # This will generate a huge scalefactor finf = type_info(dtt) data = np.array([finf['min'], finf['max']], dtype=dtt)[:,None, None] hdr.data_to_fileobj(data, sio) data_back = hdr.data_from_fileobj(sio) assert_true(np.allclose(data, data_back))
Example #22
Source File: test_utils.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_a2f_dtype_default(): # that default dtype is input dtype arr = np.array([[0.0, 1.0],[2.0, 3.0]]) str_io = BytesIO() array_to_file(arr.astype(np.int16), str_io) data_back = array_from_file(arr.shape, np.int16, str_io) assert_array_equal(data_back, arr.astype(np.int16))
Example #23
Source File: test_spm99analyze.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_big_scaling(self): # Test that upcasting works for huge scalefactors # See tests for apply_read_scaling in test_utils hdr = self.header_class() hdr.set_data_shape((1,1,1)) hdr.set_data_dtype(np.int16) sio = BytesIO() dtt = np.float32 # This will generate a huge scalefactor data = np.array([type_info(dtt)['max']], dtype=dtt)[:,None, None] hdr.data_to_fileobj(data, sio) data_back = hdr.data_from_fileobj(sio) assert_true(np.allclose(data, data_back))
Example #24
Source File: hdf5dtypeTest.py From hsds with Apache License 2.0 | 5 votes |
def testCreateEnumType(self): typeItem = { "class": "H5T_ENUM", "base": { "base": "H5T_STD_I16LE", "class": "H5T_INTEGER" }, "mapping": { "GAS": 2, "LIQUID": 1, "PLASMA": 3, "SOLID": 0 } } typeSize = hdf5dtype.getItemSize(typeItem) self.assertEqual(typeSize, 2) dt = hdf5dtype.createDataType(typeItem) self.assertEqual(dt.name, 'int16') self.assertEqual(dt.kind, 'i') mapping = check_dtype(enum=dt) self.assertTrue(isinstance(mapping, dict)) self.assertEqual(mapping["SOLID"], 0) self.assertEqual(mapping["LIQUID"], 1) self.assertEqual(mapping["GAS"], 2) self.assertEqual(mapping["PLASMA"], 3)
Example #25
Source File: test_scaling.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_array_file_scales(): # Test scaling works for max, min when going from larger to smaller type, # and from float to integer. bio = BytesIO() for in_type, out_type, err in ((np.int16, np.int16, None), (np.int16, np.int8, None), (np.uint16, np.uint8, None), (np.int32, np.int8, None), (np.float32, np.uint8, None), (np.float32, np.int16, None)): out_dtype = np.dtype(out_type) arr = np.zeros((3,), dtype=in_type) info = type_info(in_type) arr[0], arr[1] = info['min'], info['max'] if not err is None: assert_raises(err, calculate_scale, arr, out_dtype, True) continue slope, inter, mn, mx = calculate_scale(arr, out_dtype, True) array_to_file(arr, bio, out_type, 0, inter, slope, mn, mx) bio.seek(0) arr2 = array_from_file(arr.shape, out_dtype, bio) arr3 = apply_read_scaling(arr2, slope, inter) # Max rounding error for integer type max_miss = slope / 2. assert_true(np.all(np.abs(arr - arr3) <= max_miss)) bio.truncate(0) bio.seek(0)
Example #26
Source File: test_spatialimages.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_get_shape(self): # Check there is a get_shape method # (it is deprecated) img_klass = self.image_class # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 img = img_klass(np.arange(1, dtype=np.int16), np.eye(4)) assert_equal(img.get_shape(), (1,)) img = img_klass(np.zeros((2,3,4), np.int16), np.eye(4)) assert_equal(img.get_shape(), (2,3,4))
Example #27
Source File: test_spatialimages.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_str(self): # Check something comes back from string representation img_klass = self.image_class # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 arr = np.arange(5, dtype=np.int16) img = img_klass(arr, np.eye(4)) assert_true(len(str(img)) > 0) assert_equal(img.shape, (5,)) img = img_klass(np.zeros((2,3,4), dtype=np.int16), np.eye(4)) assert_true(len(str(img)) > 0)
Example #28
Source File: test_spatialimages.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_data_shape(self): # Check shape correctly read img_klass = self.image_class # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 arr = np.arange(4, dtype=np.int16) img = img_klass(arr, np.eye(4)) assert_equal(img.shape, (4,)) img = img_klass(np.zeros((2,3,4)), np.eye(4)) assert_equal(img.shape, (2,3,4))
Example #29
Source File: test_spatialimages.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_images(self): # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 arr = np.arange(3, dtype=np.int16) img = self.image_class(arr, None) assert_array_equal(img.get_data(), arr) assert_equal(img.get_affine(), None) hdr = self.image_class.header_class() hdr.set_data_shape(arr.shape) hdr.set_data_dtype(arr.dtype) assert_equal(img.get_header(), hdr)
Example #30
Source File: test_analyze.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def test_affine_44(self): IC = self.image_class shape = (2,3,4) data = np.arange(24, dtype=np.int16).reshape(shape) affine = np.diag([2, 3, 4, 1]) # OK - affine correct shape img = IC(data, affine) assert_array_equal(affine, img.get_affine()) # OK - affine can be array-like img = IC(data, affine.tolist()) assert_array_equal(affine, img.get_affine()) # Not OK - affine wrong shape assert_raises(ValueError, IC, data, np.diag([2, 3, 4]))