GVKun编程网logo

Python numpy 模块-uint64() 实例源码

4

本文将介绍Pythonnumpy模块-uint64()实例源码的详细情况,。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于Clickhouse中的UInt64

本文将介绍Python numpy 模块-uint64() 实例源码的详细情况,。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于Clickhouse 中的 UInt64 与字符串?、Go float vs uint64 比较问题、Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange的知识。

本文目录一览:

Python numpy 模块-uint64() 实例源码

Python numpy 模块-uint64() 实例源码

Python numpy 模块,uint64() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.uint64()

项目:ChessAI    作者:SamRagusa    | 项目源码 | 文件源码
  1. def get_table_and_array_for_set_of_dicts(dicts):
  2. for j in range(len(dicts)):
  3. if not j:
  4. all_keys = np.array([i for i in dicts[j].keys()], dtype=np.uint64)
  5. else:
  6. all_keys = np.concatenate([all_keys, np.array([i for i in dicts[j].keys()], dtype=np.uint64)])
  7.  
  8. unique_keys = sorted(set(all_keys))
  9.  
  10. # The sorted is so that the index of 0 will always be 0
  11. index_lookup_table = create_index_table(np.array(sorted([np.uint64(key) for key in unique_keys]), dtype=np.uint64))
  12.  
  13. array = np.zeros(shape=[len(dicts), len(unique_keys)], dtype=np.uint64)
  14.  
  15. for square_num, dict in enumerate(dicts):
  16. for key, value in dict.items():
  17. array[square_num][
  18. khash_get(ffi.cast("void *", index_lookup_table), np.uint64(key), np.uint64(0))] = np.uint64(value)
  19.  
  20. return index_lookup_table, array
项目:ChessAI    作者:SamRagusa    | 项目源码 | 文件源码
  1. def attacks_mask(board_state, square):
  2. bb_square = BB_SQUARES[square]
  3.  
  4. if bb_square & board_state.pawns:
  5. if bb_square & board_state.occupied_w:
  6. return BB_PAWN_ATTACKS[WHITE][square]
  7. else:
  8. return BB_PAWN_ATTACKS[BLACK][square]
  9. elif bb_square & board_state.knights:
  10. return BB_KNIGHT_ATTACKS[square]
  11. elif bb_square & board_state.kings:
  12. return BB_KING_ATTACKS[square]
  13. else:
  14. attacks = np.uint64(0)
  15. if bb_square & board_state.bishops or bb_square & board_state.queens:
  16. attacks = DIAG_ATTACK_ARRAY[square][
  17. khash_get(DIAG_ATTACK_INDEX_LOOKUP_TABLE, BB_DIAG_MASKS[square] & board_state.occupied, 0)]
  18. if bb_square & board_state.rooks or bb_square & board_state.queens:
  19.  
  20. attacks |= (RANK_ATTACK_ARRAY[square][
  21. khash_get(RANK_ATTACK_INDEX_LOOKUP_TABLE, BB_RANK_MASKS[square] & board_state.occupied,0)] |
  22. FILE_ATTACK_ARRAY[square][
  23. khash_get(FILE_ATTACK_INDEX_LOOKUP_TABLE, BB_FILE_MASKS[square] & board_state.occupied, 0)])
  24. return attacks
项目:pyelastix    作者:almarklein    | 项目源码 | 文件源码
  1. def _get_dtype_maps():
  2. """ Get dictionaries to map numpy data types to ITK types and the
  3. other way around.
  4. """
  5.  
  6. # Define pairs
  7. tmp = [ (np.float32, ''MET_FLOAT''), (np.float64, ''MET_DOUBLE''),
  8. (np.uint8, ''MET_UCHAR''), (np.int8, ''MET_CHAR''),
  9. (np.uint16, ''MET_USHORT''), (np.int16, ''MET_SHORT''),
  10. (np.uint32, ''MET_UINT''), (np.int32, ''MET_INT''),
  11. (np.uint64, ''MET_ULONG''), (np.int64, ''MET_LONG'') ]
  12.  
  13. # Create dictionaries
  14. map1, map2 = {}, {}
  15. for np_type, itk_type in tmp:
  16. map1[np_type.__name__] = itk_type
  17. map2[itk_type] = np_type.__name__
  18.  
  19. # Done
  20. return map1, map2
项目:Projects    作者:it2school    | 项目源码 | 文件源码
  1. def __init__(self, *args, **kwds):
  2. import numpy
  3.  
  4. self.dst_types = [numpy.uint8, numpy.uint16, numpy.uint32]
  5. try:
  6. self.dst_types.append(numpy.uint64)
  7. except AttributeError:
  8. pass
  9. pygame.display.init()
  10. try:
  11. unittest.TestCase.__init__(self, **kwds)
  12. self.sources = [self._make_src_surface(8),
  13. self._make_src_surface(16),
  14. self._make_src_surface(16, srcalpha=True),
  15. self._make_src_surface(24),
  16. self._make_src_surface(32),
  17. self._make_src_surface(32, srcalpha=True)]
  18. finally:
  19. pygame.display.quit()
项目:autolab_core    作者:BerkeleyAutomation    | 项目源码 | 文件源码
  1. def _check_valid_data(self, data):
  2. """Checks that the incoming data is a 2 x #elements ndarray of ints.
  3.  
  4. Parameters
  5. ----------
  6. data : :obj:`numpy.ndarray`
  7. The data to verify.
  8.  
  9. Raises
  10. ------
  11. ValueError
  12. If the data is not of the correct shape or type.
  13. """
  14. if data.dtype.type != np.int8 and data.dtype.type != np.int16 \\
  15. and data.dtype.type != np.int32 and data.dtype.type != np.int64 \\
  16. and data.dtype.type != np.uint8 and data.dtype.type != np.uint16 \\
  17. and data.dtype.type != np.uint32 and data.dtype.type != np.uint64:
  18. raise ValueError(''Must initialize image coords with a numpy int ndarray'')
  19. if data.shape[0] != 2:
  20. raise ValueError(''Illegal data array passed to image coords. Must have 2 coordinates'')
  21. if len(data.shape) > 2:
  22. raise ValueError(''Illegal data array passed to point cloud. Must have 1 or 2 dimensions'')
项目:compresso    作者:VCG    | 项目源码 | 文件源码
  1. def DecodeValues(block, values, encoded_values, bz, by, bx, nbits):
  2. # get the number of values per 8 byte uint64
  3. if (nbits > 0):
  4. values_per_uint64 = 64 / nbits
  5.  
  6. ie = 0
  7. for value in encoded_values:
  8. for i in range(0, values_per_uint64):
  9. lower_bits_to_remove = (
  10. (values_per_uint64 - i - 1) * nbits
  11. )
  12. values[ie] = (
  13. (value >> lower_bits_to_remove) % 2**nbits
  14. )
  15. ie += 1
  16.  
  17. ii = 0
  18. # get the lookup table
  19. for iw in range(0, bz):
  20. for iv in range(0, by):
  21. for iu in range(0, bx):
  22. block[iw, iv, iu] = values[ii]
  23. ii += 1
  24.  
  25. return block, values
项目:compresso    作者:VCG    | 项目源码 | 文件源码
  1. def to_best_type(array):
  2. ''''''Convert array to lowest possible bitrate.
  3. ''''''
  4. ui8 = np.iinfo(np.uint8)
  5. ui8 = ui8.max
  6. ui16 = np.iinfo(np.uint16)
  7. ui16 = ui16.max
  8. ui32 = np.iinfo(np.uint32)
  9. ui32 = ui32.max
  10. ui64 = np.iinfo(np.uint64)
  11. ui64 = ui64.max
  12.  
  13. if array.max() <= ui64:
  14. new_type = np.uint64
  15. if array.max() <= ui32:
  16. new_type = np.uint32
  17. if array.max() <= ui16:
  18. new_type = np.uint16
  19. if array.max() <= ui8:
  20. new_type = np.uint8
  21.  
  22. return array.astype(new_type)
项目:compresso    作者:VCG    | 项目源码 | 文件源码
  1. def load_data(name=''ac3'', N=-1, prefix=None, gold=False):
  2. ''''''Load data
  3. ''''''
  4.  
  5. if not ''mri'' in name:
  6. if gold: filename = ''~/compresso/data/'' + name + ''/gold/'' + name + ''_gold.h5''
  7. else: filename = ''~/compresso/data/'' + name + ''/rhoana/'' + name + ''_rhoana.h5''
  8.  
  9. with h5py.File(os.path.expanduser(filename), ''r'') as hf:
  10. output = np.array(hf[''main''], dtype=np.uint64)
  11. else:
  12. filename = ''~/compresso/data/MRI/'' + name + ''.h5''
  13.  
  14. with h5py.File(os.path.expanduser(filename), dtype=np.uint64)
  15.  
  16. if (not N == -1):
  17. output = output[0:N,:,:]
  18.  
  19. return output
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_int(self):
  2. for st, ut, s in [(np.int8, np.uint8, 8),
  3. (np.int16, np.uint16, 16),
  4. (np.int32, np.uint32, 32),
  5. (np.int64, np.uint64, 64)]:
  6. for i in range(1, s):
  7. assert_equal(hash(st(-2**i)), hash(-2**i),
  8. err_msg="%r: -2**%d" % (st, i))
  9. assert_equal(hash(st(2**(i - 1))), hash(2**(i - 1)),
  10. err_msg="%r: 2**%d" % (st, i - 1))
  11. assert_equal(hash(st(2**i - 1)), hash(2**i - 1),
  12. err_msg="%r: 2**%d - 1" % (st, i))
  13.  
  14. i = max(i - 1, 1)
  15. assert_equal(hash(ut(2**(i - 1))),
  16. err_msg="%r: 2**%d" % (ut, i - 1))
  17. assert_equal(hash(ut(2**i - 1)),
  18. err_msg="%r: 2**%d - 1" % (ut, i))
项目:digital_rf    作者:MIThaystack    | 项目源码 | 文件源码
  1. def _write(self, samples, keyvals):
  2. """Write new Metadata to the Digital Metadata channel.
  3.  
  4. This function does no input checking,see `write` for that.
  5.  
  6.  
  7. Parameters
  8. ----------
  9.  
  10. samples : 1-D numpy array of type uint64 sorted in ascending order
  11. An array of sample indices,given in the number of samples since
  12. the epoch (time_since_epoch*sample_rate).
  13.  
  14. keyvals : iterable of iterables same length as `samples`
  15. Each element of this iterable corresponds to a sample in `samples`
  16. and should be another iterable that produces (key,value) pairs to
  17. write for that sample.
  18.  
  19. """
  20. grp_iter = self._sample_group_generator(samples)
  21. for grp, keyval in zip(grp_iter, keyvals):
  22. for key, val in keyval:
  23. if val is not None:
  24. grp.create_dataset(key, data=val)
项目:cupy    作者:cupy    | 项目源码 | 文件源码
  1. def seed(self, seed=None):
  2. """Resets the state of the random number generator with a seed.
  3.  
  4. .. seealso::
  5. :func:`cupy.random.seed` for full documentation,
  6. :meth:`numpy.random.RandomState.seed`
  7.  
  8. """
  9. if seed is None:
  10. try:
  11. seed_str = binascii.hexlify(os.urandom(8))
  12. seed = numpy.uint64(int(seed_str, 16))
  13. except NotImplementedError:
  14. seed = numpy.uint64(time.clock() * 1000000)
  15. else:
  16. seed = numpy.asarray(seed).astype(numpy.uint64, casting=''safe'')
  17.  
  18. curand.setPseudoRandomGeneratorSeed(self._generator, seed)
  19. curand.setGeneratorOffset(self._generator, 0)
项目:cupy    作者:cupy    | 项目源码 | 文件源码
  1. def get_random_state():
  2. """Gets the state of the random number generator for the current device.
  3.  
  4. If the state for the current device is not created yet,this function
  5. creates a new one,initializes it,and stores it as the state for the
  6. current device.
  7.  
  8. Returns:
  9. RandomState: The state of the random number generator for the
  10. device.
  11.  
  12. """
  13. dev = cuda.Device()
  14. rs = _random_states.get(dev.id, None)
  15. if rs is None:
  16. seed = os.getenv(''CUPY_SEED'')
  17. if seed is None:
  18. seed = os.getenv(''CHAINER_SEED'')
  19. if seed is not None:
  20. seed = numpy.uint64(int(seed))
  21. rs = RandomState(seed)
  22. rs = _random_states.setdefault(dev.id, rs)
  23. return rs
项目:cupy    作者:cupy    | 项目源码 | 文件源码
  1. def test_dtype2(self, dtype):
  2. dtype = numpy.dtype(dtype)
  3.  
  4. # randint does not support 64 bit integers
  5. if dtype in (numpy.int64, numpy.uint64):
  6. return
  7.  
  8. iinfo = numpy.iinfo(dtype)
  9. size = (10000,)
  10.  
  11. x = random.randint(iinfo.min, iinfo.max + 1, size, dtype)
  12. self.assertEqual(x.dtype, dtype)
  13. self.assertLessEqual(iinfo.min, min(x))
  14. self.assertLessEqual(max(x), iinfo.max)
  15.  
  16. # Lower bound check
  17. with self.assertRaises(ValueError):
  18. random.randint(iinfo.min - 1, iinfo.min + 10, dtype)
  19.  
  20. # Upper bound check
  21. with self.assertRaises(ValueError):
  22. random.randint(iinfo.max - 10, iinfo.max + 2, dtype)
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
  1. def _all_day_bars_of(self, instrument):
  2. i = self._index_of(instrument)
  3. mongo_data = self._day_bars[i][instrument.order_book_id].find({}, {"_id": 0})
  4. fields = mongo_data[0].keys()
  5. fields.remove(''date'')
  6.  
  7. result = []
  8. dtype = np.dtype(getType(i))
  9. result = np.empty(shape=(mongo_data.count(),), dtype=dtype)
  10.  
  11. for f in fields:
  12. bar_attr = []
  13. mongo_data = self._day_bars[i][instrument.order_book_id].find({}, {"_id": 0})
  14. for bar in mongo_data:
  15. bar_attr.append(bar[f])
  16. result[f] = np.array(bar_attr)
  17.  
  18. bar_attr = []
  19. mongo_data = self._day_bars[i][instrument.order_book_id].find({}, {"_id": 0})
  20. for bar in mongo_data:
  21. bar_attr.append(np.array(bar[''date'']).astype(np.uint64) * 1000000)
  22. result[''datetime''] = np.array(bar_attr)
  23. return result
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
  1. def _all_day_bars_of(self, {"_id": 0})
  2. for bar in mongo_data:
  3. bar_attr.append(np.array(bar[''date'']).astype(np.uint64) * 1000000)
  4. result[''datetime''] = np.array(bar_attr)
  5. return result
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
  1. def contains(self, order_book_id, dates):
  2. try:
  3. s, e = self._index[order_book_id]
  4. except KeyError:
  5. return [False] * len(dates)
  6.  
  7. def _to_dt_int(d):
  8. if isinstance(d, (int, np.int64, np.uint64)):
  9. if d > 100000000:
  10. return int(d // 1000000)
  11. else:
  12. return d.year*10000 + d.month*100 + d.day
  13.  
  14. date_set = self._get_set(s, e)
  15.  
  16. return [(_to_dt_int(d) in date_set) for d in dates]
项目:bifrost    作者:ledatelescope    | 项目源码 | 文件源码
  1. def numpy2string(dtype):
  2. if dtype == np.int8: return ''i8''
  3. elif dtype == np.int16: return ''i16''
  4. elif dtype == np.int32: return ''i32''
  5. elif dtype == np.int64: return ''i64''
  6. elif dtype == np.uint8: return ''u8''
  7. elif dtype == np.uint16: return ''u16''
  8. elif dtype == np.uint32: return ''u32''
  9. elif dtype == np.uint64: return ''u64''
  10. elif dtype == np.float16: return ''f16''
  11. elif dtype == np.float32: return ''f32''
  12. elif dtype == np.float64: return ''f64''
  13. elif dtype == np.float128: return ''f128''
  14. elif dtype == np.complex64: return ''cf32''
  15. elif dtype == np.complex128: return ''cf64''
  16. elif dtype == np.complex256: return ''cf128''
  17. else: raise TypeError("Unsupported dtype: " + str(dtype))
项目:DirectFuturePrediction    作者:IntelVCL    | 项目源码 | 文件源码
  1. def make_array(shape=(1, dtype=np.float32, shared=False, fill_val=None):
  2. np_type_to_ctype = {np.float32: ctypes.c_float,
  3. np.float64: ctypes.c_double,
  4. np.bool: ctypes.c_bool,
  5. np.uint8: ctypes.c_ubyte,
  6. np.uint64: ctypes.c_ulonglong}
  7.  
  8. if not shared:
  9. np_arr = np.empty(shape, dtype=dtype)
  10. else:
  11. numel = np.prod(shape)
  12. arr_ctypes = sharedctypes.RawArray(np_type_to_ctype[dtype], numel)
  13. np_arr = np.frombuffer(arr_ctypes, dtype=dtype, count=numel)
  14. np_arr.shape = shape
  15.  
  16. if not fill_val is None:
  17. np_arr[...] = fill_val
  18.  
  19. return np_arr
项目:scene_detection    作者:VieVie31    | 项目源码 | 文件源码
  1. def dhash(img):
  2. """Compute a perceptual has of an image.
  3.  
  4. Algo explained here :
  5. https://blog.bearstech.com/2014/07/numpy-par-lexemple-une-implementation-de-dhash.html
  6.  
  7. :param img: an image
  8.  
  9. :type img: numpy.ndarray
  10.  
  11. :return: a perceptual hash of img coded on 64 bits
  12. :rtype: int
  13. """
  14. TWOS = np.array([2 ** n for n in range(7, -1, -1)])
  15. BIGS = np.array([256 ** n for n in range(7, -1)], dtype=np.uint64)
  16. img = rgb2grey(resize(img, (9, 8)))
  17. h = np.array([0] * 8, dtype=np.uint8)
  18. for i in range(8):
  19. h[i] = TWOS[img[i] > img[i + 1]].sum()
  20. return (BIGS * h).sum()
项目:pycolor_detection    作者:parth1993    | 项目源码 | 文件源码
  1. def get_rgb_mask(img, debug=False):
  2. assert isinstance(img, numpy.ndarray), ''image must be a numpy array''
  3. assert img.ndim == 3, ''skin detection can only work on color images''
  4. logger.debug(''getting rgb mask'')
  5.  
  6. lower_thresh = numpy.array([45, 52, 108], dtype=numpy.uint8)
  7. upper_thresh = numpy.array([255, 255, 255], dtype=numpy.uint8)
  8.  
  9. mask_a = cv2.inRange(img, lower_thresh, upper_thresh)
  10. mask_b = 255 * ((img[:, :, 2] - img[:, 1]) / 20)
  11. mask_c = 255 * ((numpy.max(img, axis=2) - numpy.min(img, axis=2)) / 20)
  12. mask_d = numpy.bitwise_and(numpy.uint64(mask_a), numpy.uint64(mask_b))
  13. # mask = numpy.zeros_like(mask_d,dtype=numpy.uint8)
  14. msk_rgb = numpy.bitwise_and(numpy.uint64(mask_c), numpy.uint64(mask_d))
  15. # msk_rgb = cv2.fromarray(mask_rgb)
  16. msk_rgb[msk_rgb < 128] = 0
  17. msk_rgb[msk_rgb >= 128] = 1
  18.  
  19. if debug:
  20. scripts.display(''input'', img)
  21. scripts.display(''mask_rgb'', msk_rgb)
  22.  
  23. return msk_rgb.astype(float)
项目:incubator-airflow-old    作者:apache    | 项目源码 | 文件源码
  1. def default(self, obj):
  2. # convert dates and numpy objects in a json serializable format
  3. if isinstance(obj, datetime):
  4. return obj.strftime(''%Y-%m-%dT%H:%M:%sZ'')
  5. elif isinstance(obj, date):
  6. return obj.strftime(''%Y-%m-%d'')
  7. elif type(obj) in (np.int_, np.intc, np.intp, np.int8, np.int16,
  8. np.int32,
  9. np.uint32, np.uint64):
  10. return int(obj)
  11. elif type(obj) in (np.bool_,):
  12. return bool(obj)
  13. elif type(obj) in (np.float_, np.float16, np.float32, np.float64,
  14. np.complex_, np.complex64, np.complex128):
  15. return float(obj)
  16.  
  17. # Let the base class default method raise the TypeError
  18. return json.JSONEncoder.default(self, obj)
项目:varapp-backend-py    作者:varapp    | 项目源码 | 文件源码
  1. def scan_genotypes(self, genotypes, sub_ids=None, db=None):
  2. """Pass through all genotypes and return only the indices of those that pass the filter.
  3. :param genotypes: np.ndarray[uint64,dim=2]
  4. :rtype: np.ndarray[uint64]"""
  5. if self.shortcut:
  6. return np.zeros(0)
  7. N = len(genotypes)
  8. if sub_ids is not None:
  9. variant_ids = sub_ids
  10. elif self.val == ''x_linked'' and db:
  11. variant_ids = genotypes_service(db).chrX
  12. else:
  13. variant_ids = np.asarray(range(1,N+1), dtype=np.uint64)
  14. active_idx = np.asarray(self.ss.active_idx, dtype=np.uint16)
  15. conditions = self.conditions_vector
  16. is_and = self.merge_op == AND
  17. if len(conditions) == 0:
  18. passing = variant_ids
  19. else:
  20. passing = self.parallel_apply_bitwise(genotypes, variant_ids, conditions, active_idx, is_and)
  21. return passing
项目:varapp-backend-py    作者:varapp    | 项目源码 | 文件源码
  1. def scan_genotypes_compound(self, batches, parallel=True):
  2. """Scan the *genotypes* array for compounds. Variant ids are treated in batches,
  3. - one list of variant_ids per gene."""
  4. if self.shortcut:
  5. passing, sources, pairs = np.zeros(0), {}, []
  6. else:
  7. N = len(genotypes)
  8. active_idx = np.asarray(self.ss.active_idx, dtype=np.uint16)
  9. batches = list(batches.items())
  10. if parallel:
  11. passing, pairs = self.parallel_batches(genotypes, N)
  12. else:
  13. passing, pairs = self.process_batches(genotypes, N)
  14. passing = np.array(list(passing), dtype=np.uint64)
  15. passing.sort()
  16. return passing, pairs
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_int(self):
  2. for st, i))
项目:DeepEnhancer    作者:minxueric    | 项目源码 | 文件源码
  1. def enhchr(indexes):
  2. """chromosome length vs. enhancer numbers on it"""
  3. lens = np.array([len(sequences[keys[i]]) for i in range(24)], dtype=np.float)
  4. nums = np.zeros((24,))
  5. for index in indexes:
  6. chrkey = index[0]
  7. nums[keys.index(chrkey)] += 1
  8. print "The length of 24 Chromosomes are \\n{}".format(np.array(lens, dtype=np.uint64))
  9. print "The number of enhancers on each chromosome are \\n{}".format(np.array(nums, dtype=np.uint64))
  10.  
  11. ind = np.arange(24)
  12. w = 0.35
  13. fig, ax = plt.subplots()
  14. rects1 = ax.bar(ind, lens / np.sum(lens), w, color=''r'')
  15. rects2 = ax.bar(ind + w, nums / np.sum(nums), color=''y'')
  16. ax.set_ylabel(''Chrom Length & #Enhancers'')
  17. ax.set_xticks(ind + w)
  18. ax.set_xticklabels(keys)
  19. ax.legend((rects1[0], rects2[0]), (''Chrom Length (%)'', ''#Enahncers (%)''))
  20. plt.show()
项目:diced    作者:janelia-flyem    | 项目源码 | 文件源码
  1. def _getchunk(self, z, y, x, zsize, ysize, xsize):
  2. """Internal function to retrieve data.
  3. """
  4.  
  5. data = None
  6.  
  7. # interface is the same for labels and raw arrays but the function is stateless
  8. # and can benefit from extra compression possible in labels in some use cases
  9. if self.dtype == ArrayDtype.uint8:
  10. data = self.ns.get_array8bit3D(self.instancename, (zsize, xsize), (z, x), self.islabel3D)
  11. elif self.dtype == ArrayDtype.uint16:
  12. data = self.ns.get_array16bit3D(self.instancename, self.islabel3D)
  13. elif self.dtype == ArrayDtype.uint32:
  14. data = self.ns.get_array32bit3D(self.instancename, self.islabel3D)
  15. elif self.dtype == ArrayDtype.uint64:
  16. data = self.ns.get_array64bit3D(self.instancename, self.islabel3D)
  17. else:
  18. raise DicedException("Invalid datatype for array")
  19.  
  20. return data
项目:chainer-deconv    作者:germanRos    | 项目源码 | 文件源码
  1. def seed(self, 16))
  2. except NotImplementedError:
  3. seed = numpy.uint64(time.clock() * 1000000)
  4. else:
  5. seed = numpy.uint64(seed)
  6.  
  7. curand.setPseudoRandomGeneratorSeed(self._generator, 0)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_constructor_overflow_int64(self):
  2. values = np.array([2 ** 64 - i for i in range(1, 10)],
  3. dtype=np.uint64)
  4.  
  5. result = DataFrame({''a'': values})
  6. self.assertEqual(result[''a''].dtype, object)
  7.  
  8. # #2355
  9. data_scores = [(6311132704823138710, 273), (2685045978526272070, 23),
  10. (8921811264899370420, 45),
  11. (long(17019687244989530680), 270),
  12. (long(9930107427299601010), 273)]
  13. dtype = [(''uid'', ''u8''), (''score'', ''u8'')]
  14. data = np.zeros((len(data_scores), dtype=dtype)
  15. data[:] = data_scores
  16. df_crawls = DataFrame(data)
  17. self.assertEqual(df_crawls[''uid''].dtype, object)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_int(self):
  2. for st, i))
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
  1. def centroid(im, labels, return_mm3=True):
  2. """
  3. Centroid (center of mass,barycenter) of a list of labels.
  4. :param im:
  5. :param labels: list of labels,e.g. [3] or [2,3,45]
  6. :param return_mm3: if true the answer is in mm if false in voxel indexes.
  7. :return: list of centroids,one for each label in the input order.
  8. """
  9. centers_of_mass = centroid_array(im.get_data(), labels)
  10. ans = []
  11. if return_mm3:
  12. for cm in centers_of_mass:
  13. if isinstance(cm, np.ndarray):
  14. ans += [im.affine[:3, :3].dot(cm.astype(np.float64))]
  15. else:
  16. ans += [cm]
  17. else:
  18. for cm in centers_of_mass:
  19. if isinstance(cm, np.ndarray): # else it is np.nan.
  20. ans += [np.round(cm).astype(np.uint64)]
  21. else:
  22. ans += [cm]
  23. return ans
项目:mimclib    作者:stochasticNumerics    | 项目源码 | 文件源码
  1. def execute(self, query, params=[]):
  2. if len(params) > 0 and len(query.split('';'')) > 1:
  3. raise Exception("Multiple queries with parameters is unsupported")
  4.  
  5. # Expand lists in paramters
  6. prev = -1
  7. new_params = []
  8. for p in params:
  9. prev = query.find(''?'', prev+1)
  10. if type(p) in [np.uint16, np.uint64]:
  11. new_params.append(np.int64(p)) # sqlite is really fussy about this
  12. elif type(p) in [list, tuple]:
  13. rep = "(" + ",".join("?"*len(p)) + ")"
  14. query = query[:prev] + rep + query[prev+1:]
  15. prev += len(rep)
  16. new_params.extend(p)
  17. else:
  18. new_params.append(p)
  19.  
  20. for q in query.split('';''):
  21. self.cur.execute(q, tuple(new_params))
  22. return self.cur
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_int(self):
  2. for st, i))
项目:python-offchain    作者:TrueBitFoundation    | 项目源码 | 文件源码
  1. def ctz(val, _type):
  2. cnt = int()
  3. power = int()
  4. if _type == ''uint32'':
  5. bits = np.uint32(val)
  6. while power < 32:
  7. if val & 2**power == 0:
  8. cnt += 1
  9. else:
  10. break
  11. power += 1
  12. elif _type == ''uint64'':
  13. bits = bin(np.uint64(val))
  14. while power < 64:
  15. if val & 2**power == 0:
  16. cnt += 1
  17. else:
  18. break
  19. power += 1
  20. else:
  21. raise Exception(Colors.red + "unsupported type passed to ctz." + Colors.ENDC)
  22. return cnt
项目:python-offchain    作者:TrueBitFoundation    | 项目源码 | 文件源码
  1. def pop_cnt(val, _type):
  2. cnt = int()
  3. power = int()
  4. if _type == ''uint32'':
  5. bits = np.uint32(val)
  6. while power < 32:
  7. if val & 2**power != 0:
  8. cnt += 1
  9. power += 1
  10. elif _type == ''uint64'':
  11. bits = bin(np.uint64(val))
  12. while power < 64:
  13. if val & 2**power != 0:
  14. cnt += 1
  15. power += 1
  16. else:
  17. raise Exception(Colors.red + "unsupported type passed to pop_cnt." + Colors.ENDC)
  18. return cnt
项目:scipy-2017-cython-tutorial    作者:kwmsmith    | 项目源码 | 文件源码
  1. def test_int64_uint64_corner_case(self):
  2. # When stored in Numpy arrays,`lbnd` is casted
  3. # as np.int64,and `ubnd` is casted as np.uint64.
  4. # Checking whether `lbnd` >= `ubnd` used to be
  5. # done solely via direct comparison,which is incorrect
  6. # because when Numpy tries to compare both numbers,
  7. # it casts both to np.float64 because there is
  8. # no integer superset of np.int64 and np.uint64. However,
  9. # `ubnd` is too large to be represented in np.float64,
  10. # causing it be round down to np.iinfo(np.int64).max,
  11. # leading to a ValueError because `lbnd` Now equals
  12. # the new `ubnd`.
  13.  
  14. dt = np.int64
  15. tgt = np.iinfo(np.int64).max
  16. lbnd = np.int64(np.iinfo(np.int64).max)
  17. ubnd = np.uint64(np.iinfo(np.int64).max + 1)
  18.  
  19. # None of these function calls should
  20. # generate a ValueError Now.
  21. actual = mt19937.randint(lbnd, ubnd, dtype=dt)
  22. assert_equal(actual, tgt)
项目:chainercv    作者:chainer    | 项目源码 | 文件源码
  1. def _call_nms_kernel(bBox, thresh):
  2. n_bBox = bBox.shape[0]
  3. threads_per_block = 64
  4. col_blocks = np.ceil(n_bBox / threads_per_block).astype(np.int32)
  5. blocks = (col_blocks, col_blocks, 1)
  6. threads = (threads_per_block, 1, 1)
  7.  
  8. mask_dev = cp.zeros((n_bBox * col_blocks, dtype=np.uint64)
  9. bBox = cp.ascontiguousarray(bBox, dtype=np.float32)
  10. kern = _load_kernel(''nms_kernel'', _nms_gpu_code)
  11. kern(blocks, threads, args=(cp.int32(n_bBox), cp.float32(thresh),
  12. bBox, mask_dev))
  13.  
  14. mask_host = mask_dev.get()
  15. selection, n_selec = _nms_gpu_post(
  16. mask_host, n_bBox, threads_per_block, col_blocks)
  17. return selection, n_selec
项目:stuff    作者:yaroslavvb    | 项目源码 | 文件源码
  1. def dump(result, fname, no_prefix=False):
  2. """Save result to file."""
  3. result = result.eval() if hasattr(result, "eval") else result
  4. result = np.asarray(result)
  5. if result.shape == (): # savetxt has problems with scalars
  6. result = np.expand_dims(result, 0)
  7. if no_prefix:
  8. location = os.getcwd()+"/"+fname
  9. else:
  10. location = os.getcwd()+"/data/"+fname
  11. # special handling for integer datatypes
  12. if (
  13. result.dtype == np.uint8 or result.dtype == np.int8 or
  14. result.dtype == np.uint16 or result.dtype == np.int16 or
  15. result.dtype == np.uint32 or result.dtype == np.int32 or
  16. result.dtype == np.uint64 or result.dtype == np.int64
  17. ):
  18. np.savetxt(location, result, fmt="%d", delimiter='','')
  19. else:
  20. np.savetxt(location,'')
  21. print(location)
项目:stuff    作者:yaroslavvb    | 项目源码 | 文件源码
  1. def dump(result,'')
  2. print(location)
项目:stuff    作者:yaroslavvb    | 项目源码 | 文件源码
  1. def dump(result,'')
  2. print(location)
项目:stuff    作者:yaroslavvb    | 项目源码 | 文件源码
  1. def dump(result,'')
  2. print(location)
项目:stuff    作者:yaroslavvb    | 项目源码 | 文件源码
  1. def dump(result,'')
  2. print(location)
项目:stuff    作者:yaroslavvb    | 项目源码 | 文件源码
  1. def dump(result,'')
  2. print(location)
项目:satpy    作者:pytroll    | 项目源码 | 文件源码
  1. def time_seconds(tc_array, year):
  2. """Return the time object from the timecodes
  3. """
  4. tc_array = np.array(tc_array, copy=True)
  5. word = tc_array[:, 0]
  6. day = word >> 1
  7. word = tc_array[:, 1].astype(np.uint64)
  8. msecs = ((127) & word) * 1024
  9. word = tc_array[:, 2]
  10. msecs += word & 1023
  11. msecs *= 1024
  12. word = tc_array[:, 3]
  13. msecs += word & 1023
  14. return (np.datetime64(
  15. str(year) + ''-01-01T00:00:00Z'', ''s'') +
  16. msecs[:].astype(''timedelta64[ms]'') +
  17. (day - 1)[:].astype(''timedelta64[D]''))
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
  1. def test_channel_uint64_wrong_dimensions(self):
  2. """ Test posting with the wrong xyz dims"""
  3.  
  4. test_mat = np.random.randint(1, 2 ** 16 - 1, (16, 128, 128))
  5. test_mat = test_mat.astype(np.uint64)
  6. h = test_mat.tobytes()
  7. bb = blosc.compress(h, typesize=64)
  8.  
  9. # Create request
  10. factory = APIRequestFactory()
  11. request = factory.post(''/'' + version + ''/cutout/col1/exp1/layer1/0/0:100/0:128/0:16/'', bb,
  12. content_type=''application/blosc'')
  13. # log in user
  14. force_authenticate(request, user=self.user)
  15.  
  16. # Make request
  17. response = Cutout.as_view()(request, collection=''col1'', experiment=''exp1'', channel=''layer1'',
  18. resolution=''0'', x_range=''0:100'', y_range=''0:128'', z_range=''0:16'', t_range=None)
  19. self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
  1. def test_channel_uint64_wrong_dimensions_numpy(self):
  2. """ Test posting with the wrong xyz dims using the numpy interface"""
  3.  
  4. test_mat = np.random.randint(1, 128))
  5. test_mat = test_mat.astype(np.uint64)
  6. bb = blosc.pack_array(test_mat)
  7.  
  8. # Create request
  9. factory = APIRequestFactory()
  10. request = factory.post(''/'' + version + ''/cutout/col1/exp1/layer1/0/0:100/0:128/0:16/'',
  11. content_type=''application/blosc-python'')
  12. # log in user
  13. force_authenticate(request, status.HTTP_400_BAD_REQUEST)
项目:xpandas    作者:alan-turing-institute    | 项目源码 | 文件源码
  1. def _is_class_a_primitive(cls):
  2. ''''''
  3. Check if class is a number or string including numpy numbers
  4. :param cls: any class
  5. :return: True if class is a primitive class,else False
  6. ''''''
  7. primitives = [
  8. np.float16, np.float128,
  9. np.int8, np.int32,
  10. bool, str,
  11. int, float
  12. ]
  13. return cls in primitives
项目:cellranger    作者:10XGenomics    | 项目源码 | 文件源码
  1. def decompress_seq(x, length, bits=64):
  2. x = np.uint64(x)
  3. assert length <= (bits/2 - 1)
  4. if x & (1L << (bits-1)):
  5. return ''N'' * length
  6. result = bytearray(length)
  7. for i in xrange(length):
  8. result[(length-1)-i] = tk_seq.NUCS[x & np.uint64(0b11)]
  9. x = x >> np.uint64(2)
  10. return str(result)
项目:sharedbuffers    作者:jampp    | 项目源码 | 文件源码
  1. def __init__(self, buf, offset = 0, idmap = None, idmap_size = 1024):
  2. if idmap is None:
  3. idmap = Cache(idmap_size)
  4. self.offset = offset
  5. if offset != 0:
  6. self.buf = buf = buffer(buf, offset)
  7. else:
  8. self.buf = buf
  9. self.total_size, self.index_offset, self.index_elements = self._Header.unpack_from(buf, 0)
  10. self.index = numpy.frombuffer(buf,
  11. offset = self.index_offset,
  12. dtype = numpy.uint64,
  13. count = self.index_elements)
  14. self.idmap = idmap
  15.  
  16. if self.index_elements > 0 and self.index[0] >= (self._Header.size + self._NewHeader.size):
  17. # New version,most likely
  18. self.version, min_reader_version, self.schema_offset, self.schema_size = self._NewHeader.unpack_from(
  19. buf, self._Header.size)
  20. if self._CURRENT_VERSION < min_reader_version:
  21. raise ValueError((
  22. "Incompatible buffer,this buffer needs a reader with support for version %d at least,"
  23. "this reader supports up to version %d") % (
  24. min_reader_version,
  25. self._CURRENT_VERSION
  26. ))
  27. if self.schema_offset and self.schema_size:
  28. if self.schema_offset > len(buf) or (self.schema_size + self.schema_offset) > len(buf):
  29. raise ValueError("Corrupted input - bad schema location")
  30. stored_schema = cPickle.loads(bytes(buffer(buf, self.schema_size)))
  31. if not isinstance(stored_schema, Schema):
  32. raise ValueError("Corrupted input - unrecognizable schema")
  33. if self.schema is None or not self.schema.compatible(stored_schema):
  34. self.schema = stored_schema
  35. elif self.schema is None:
  36. raise ValueError("Cannot map schema-less buffer without specifying schema")
  37. elif self.index_elements > 0:
  38. raise ValueError("Cannot reliably map version-0 buffers")
项目:supremm    作者:ubccr    | 项目源码 | 文件源码
  1. def normalise_data(self, timestamp, data):
  2. """ Convert the data if needed """
  3.  
  4. if self._passthrough:
  5. return
  6.  
  7. i = 0
  8. for datum in data:
  9.  
  10. if self.needsfixup[i] is None:
  11. i += 1
  12. continue
  13.  
  14. if len(datum) == 0:
  15. # Ignore entries with no data - this typically occurs when the
  16. # plugin requests multiple metrics and the metrics do not all appear
  17. # at every timestep
  18. i += 1
  19. continue
  20.  
  21. if self.accumulator[i] is None:
  22. self.accumulator[i] = numpy.array(datum)
  23. self.last[i] = numpy.array(datum)
  24. else:
  25. self.accumulator[i] += (datum - self.last[i]) % numpy.uint64(1L << self.needsfixup[i][''range''])
  26. numpy.copyto(self.last[i], datum)
  27. numpy.copyto(datum, self.accumulator[i])
  28.  
  29. i += 1
项目:ml-pyxis    作者:vicolab    | 项目源码 | 文件源码
  1. def batch(self):
  2. """Return a batch of samples sampled uniformly from the database.
  3.  
  4. Returns
  5. -------
  6. (numpy.ndarray,...)
  7. The sample values are returned in a tuple in the order of the
  8. `keys` specified by the user.
  9. """
  10. # Count the number of keys (i.e. data objects)
  11. nb_keys = len(self.keys)
  12.  
  13. data = []
  14. for key in self.keys:
  15. data.append(np.zeros((self.batch_size,) + self.spec[key][''shape''],
  16. dtype=self.spec[key][''dtype'']))
  17.  
  18. while True:
  19. # Sample indices uniformly
  20. batch_idxs = self.rng.randint(self.db.nb_samples,
  21. size=self.batch_size,
  22. dtype=np.uint64)
  23.  
  24. for i, v in enumerate(batch_idxs):
  25. sample = self.db.get_sample(v)
  26. for k in range(nb_keys):
  27. data[k][i] = sample[self.keys[k]]
  28.  
  29. # Account for batches with only one key
  30. if 1 == len(data):
  31. yield tuple(data)[0]
  32. else:
  33. yield tuple(data)

Clickhouse 中的 UInt64 与字符串?

Clickhouse 中的 UInt64 与字符串?

如何解决Clickhouse 中的 UInt64 与字符串?

我在一张表中存储了大量信息,记录大约有 10 亿条记录。我假设一段时间后它会超过 40 亿,这是 uint32 的最大值。所以我想知道在这种情况下 uint64 比 string 快吗? Clickhouse 使用分区具有良好的性能,但有时我将不在分区内进行搜索。那么,它们中的哪一个具有良好的性能?

解决方法

Uint64 比 String 快。

但我认为这个问题更复杂。

如果您需要在某个时候将 Uint64 标识符解码为字符串,那么情况可能正好相反。

Go float vs uint64 比较问题

Go float vs uint64 比较问题

如何解决Go float vs uint64 比较问题

正在解决一个比较浮点数和 uint64 的问题,其中浮点数等于 MaxUint64+1。比较适用于浮点文字。但是,当将浮点数分配给变量时,比较会中断。

func main() {
    x := 18446744073709551616.0
    fmt.Println(x == 18446744073709551616.0) //true
    fmt.Println(18446744073709551616.0 > math.MaxUint64) //true
    fmt.Println(x > math.MaxUint64) //false
}

https://play.golang.org/p/O65padWxV8L

进一步挖掘表明,并非所有浮点数 > MaxUint64 都会出现此问题。当 x 分配给 18446744073709553665.0(或 MaxUint64+2050)中的任何值时,比较有效。

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy.random.random & numpy.ndarray.astype & numpy.arange

numpy.random.random & numpy.ndarray.astype & numpy.arange

今天看到这样一句代码:

xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值

要理解这两句代码需要理解三个函数

1、生成随机数

numpy.random.random(size=None) 

size为None时,返回float。

size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组

 

2、对numpy数组中每一个元素进行类型转换

numpy.ndarray.astype(dtype)

返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]

 

3、获取等差数列

numpy.arange([start,]stop,[step,]dtype=None)

功能类似python中自带的range()和numpy中的numpy.linspace

返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]

今天关于Python numpy 模块-uint64() 实例源码的介绍到此结束,谢谢您的阅读,有关Clickhouse 中的 UInt64 与字符串?、Go float vs uint64 比较问题、Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange等更多相关知识的信息可以在本站进行查询。

本文标签: