m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

564 lines
19 KiB

6 months ago
  1. """Machine limits for Float32 and Float64 and (long double) if available...
  2. """
  3. __all__ = ['finfo', 'iinfo']
  4. import warnings
  5. from .machar import MachAr
  6. from .overrides import set_module
  7. from . import numeric
  8. from . import numerictypes as ntypes
  9. from .numeric import array, inf
  10. from .umath import log10, exp2
  11. from . import umath
  12. def _fr0(a):
  13. """fix rank-0 --> rank-1"""
  14. if a.ndim == 0:
  15. a = a.copy()
  16. a.shape = (1,)
  17. return a
  18. def _fr1(a):
  19. """fix rank > 0 --> rank-0"""
  20. if a.size == 1:
  21. a = a.copy()
  22. a.shape = ()
  23. return a
  24. class MachArLike:
  25. """ Object to simulate MachAr instance """
  26. def __init__(self,
  27. ftype,
  28. *, eps, epsneg, huge, tiny, ibeta, **kwargs):
  29. params = _MACHAR_PARAMS[ftype]
  30. float_conv = lambda v: array([v], ftype)
  31. float_to_float = lambda v : _fr1(float_conv(v))
  32. float_to_str = lambda v: (params['fmt'] % array(_fr0(v)[0], ftype))
  33. self.title = params['title']
  34. # Parameter types same as for discovered MachAr object.
  35. self.epsilon = self.eps = float_to_float(eps)
  36. self.epsneg = float_to_float(epsneg)
  37. self.xmax = self.huge = float_to_float(huge)
  38. self.xmin = self.tiny = float_to_float(tiny)
  39. self.ibeta = params['itype'](ibeta)
  40. self.__dict__.update(kwargs)
  41. self.precision = int(-log10(self.eps))
  42. self.resolution = float_to_float(float_conv(10) ** (-self.precision))
  43. self._str_eps = float_to_str(self.eps)
  44. self._str_epsneg = float_to_str(self.epsneg)
  45. self._str_xmin = float_to_str(self.xmin)
  46. self._str_xmax = float_to_str(self.xmax)
  47. self._str_resolution = float_to_str(self.resolution)
  48. _convert_to_float = {
  49. ntypes.csingle: ntypes.single,
  50. ntypes.complex_: ntypes.float_,
  51. ntypes.clongfloat: ntypes.longfloat
  52. }
  53. # Parameters for creating MachAr / MachAr-like objects
  54. _title_fmt = 'numpy {} precision floating point number'
  55. _MACHAR_PARAMS = {
  56. ntypes.double: dict(
  57. itype = ntypes.int64,
  58. fmt = '%24.16e',
  59. title = _title_fmt.format('double')),
  60. ntypes.single: dict(
  61. itype = ntypes.int32,
  62. fmt = '%15.7e',
  63. title = _title_fmt.format('single')),
  64. ntypes.longdouble: dict(
  65. itype = ntypes.longlong,
  66. fmt = '%s',
  67. title = _title_fmt.format('long double')),
  68. ntypes.half: dict(
  69. itype = ntypes.int16,
  70. fmt = '%12.5e',
  71. title = _title_fmt.format('half'))}
  72. # Key to identify the floating point type. Key is result of
  73. # ftype('-0.1').newbyteorder('<').tobytes()
  74. # See:
  75. # https://perl5.git.perl.org/perl.git/blob/3118d7d684b56cbeb702af874f4326683c45f045:/Configure
  76. _KNOWN_TYPES = {}
  77. def _register_type(machar, bytepat):
  78. _KNOWN_TYPES[bytepat] = machar
  79. _float_ma = {}
  80. def _register_known_types():
  81. # Known parameters for float16
  82. # See docstring of MachAr class for description of parameters.
  83. f16 = ntypes.float16
  84. float16_ma = MachArLike(f16,
  85. machep=-10,
  86. negep=-11,
  87. minexp=-14,
  88. maxexp=16,
  89. it=10,
  90. iexp=5,
  91. ibeta=2,
  92. irnd=5,
  93. ngrd=0,
  94. eps=exp2(f16(-10)),
  95. epsneg=exp2(f16(-11)),
  96. huge=f16(65504),
  97. tiny=f16(2 ** -14))
  98. _register_type(float16_ma, b'f\xae')
  99. _float_ma[16] = float16_ma
  100. # Known parameters for float32
  101. f32 = ntypes.float32
  102. float32_ma = MachArLike(f32,
  103. machep=-23,
  104. negep=-24,
  105. minexp=-126,
  106. maxexp=128,
  107. it=23,
  108. iexp=8,
  109. ibeta=2,
  110. irnd=5,
  111. ngrd=0,
  112. eps=exp2(f32(-23)),
  113. epsneg=exp2(f32(-24)),
  114. huge=f32((1 - 2 ** -24) * 2**128),
  115. tiny=exp2(f32(-126)))
  116. _register_type(float32_ma, b'\xcd\xcc\xcc\xbd')
  117. _float_ma[32] = float32_ma
  118. # Known parameters for float64
  119. f64 = ntypes.float64
  120. epsneg_f64 = 2.0 ** -53.0
  121. tiny_f64 = 2.0 ** -1022.0
  122. float64_ma = MachArLike(f64,
  123. machep=-52,
  124. negep=-53,
  125. minexp=-1022,
  126. maxexp=1024,
  127. it=52,
  128. iexp=11,
  129. ibeta=2,
  130. irnd=5,
  131. ngrd=0,
  132. eps=2.0 ** -52.0,
  133. epsneg=epsneg_f64,
  134. huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4),
  135. tiny=tiny_f64)
  136. _register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf')
  137. _float_ma[64] = float64_ma
  138. # Known parameters for IEEE 754 128-bit binary float
  139. ld = ntypes.longdouble
  140. epsneg_f128 = exp2(ld(-113))
  141. tiny_f128 = exp2(ld(-16382))
  142. # Ignore runtime error when this is not f128
  143. with numeric.errstate(all='ignore'):
  144. huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4)
  145. float128_ma = MachArLike(ld,
  146. machep=-112,
  147. negep=-113,
  148. minexp=-16382,
  149. maxexp=16384,
  150. it=112,
  151. iexp=15,
  152. ibeta=2,
  153. irnd=5,
  154. ngrd=0,
  155. eps=exp2(ld(-112)),
  156. epsneg=epsneg_f128,
  157. huge=huge_f128,
  158. tiny=tiny_f128)
  159. # IEEE 754 128-bit binary float
  160. _register_type(float128_ma,
  161. b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
  162. _register_type(float128_ma,
  163. b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
  164. _float_ma[128] = float128_ma
  165. # Known parameters for float80 (Intel 80-bit extended precision)
  166. epsneg_f80 = exp2(ld(-64))
  167. tiny_f80 = exp2(ld(-16382))
  168. # Ignore runtime error when this is not f80
  169. with numeric.errstate(all='ignore'):
  170. huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4)
  171. float80_ma = MachArLike(ld,
  172. machep=-63,
  173. negep=-64,
  174. minexp=-16382,
  175. maxexp=16384,
  176. it=63,
  177. iexp=15,
  178. ibeta=2,
  179. irnd=5,
  180. ngrd=0,
  181. eps=exp2(ld(-63)),
  182. epsneg=epsneg_f80,
  183. huge=huge_f80,
  184. tiny=tiny_f80)
  185. # float80, first 10 bytes containing actual storage
  186. _register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf')
  187. _float_ma[80] = float80_ma
  188. # Guessed / known parameters for double double; see:
  189. # https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format#Double-double_arithmetic
  190. # These numbers have the same exponent range as float64, but extended number of
  191. # digits in the significand.
  192. huge_dd = (umath.nextafter(ld(inf), ld(0))
  193. if hasattr(umath, 'nextafter') # Missing on some platforms?
  194. else float64_ma.huge)
  195. float_dd_ma = MachArLike(ld,
  196. machep=-105,
  197. negep=-106,
  198. minexp=-1022,
  199. maxexp=1024,
  200. it=105,
  201. iexp=11,
  202. ibeta=2,
  203. irnd=5,
  204. ngrd=0,
  205. eps=exp2(ld(-105)),
  206. epsneg= exp2(ld(-106)),
  207. huge=huge_dd,
  208. tiny=exp2(ld(-1022)))
  209. # double double; low, high order (e.g. PPC 64)
  210. _register_type(float_dd_ma,
  211. b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf')
  212. # double double; high, low order (e.g. PPC 64 le)
  213. _register_type(float_dd_ma,
  214. b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<')
  215. _float_ma['dd'] = float_dd_ma
  216. def _get_machar(ftype):
  217. """ Get MachAr instance or MachAr-like instance
  218. Get parameters for floating point type, by first trying signatures of
  219. various known floating point types, then, if none match, attempting to
  220. identify parameters by analysis.
  221. Parameters
  222. ----------
  223. ftype : class
  224. Numpy floating point type class (e.g. ``np.float64``)
  225. Returns
  226. -------
  227. ma_like : instance of :class:`MachAr` or :class:`MachArLike`
  228. Object giving floating point parameters for `ftype`.
  229. Warns
  230. -----
  231. UserWarning
  232. If the binary signature of the float type is not in the dictionary of
  233. known float types.
  234. """
  235. params = _MACHAR_PARAMS.get(ftype)
  236. if params is None:
  237. raise ValueError(repr(ftype))
  238. # Detect known / suspected types
  239. key = ftype('-0.1').newbyteorder('<').tobytes()
  240. ma_like = None
  241. if ftype == ntypes.longdouble:
  242. # Could be 80 bit == 10 byte extended precision, where last bytes can
  243. # be random garbage.
  244. # Comparing first 10 bytes to pattern first to avoid branching on the
  245. # random garbage.
  246. ma_like = _KNOWN_TYPES.get(key[:10])
  247. if ma_like is None:
  248. ma_like = _KNOWN_TYPES.get(key)
  249. if ma_like is not None:
  250. return ma_like
  251. # Fall back to parameter discovery
  252. warnings.warn(
  253. 'Signature {} for {} does not match any known type: '
  254. 'falling back to type probe function'.format(key, ftype),
  255. UserWarning, stacklevel=2)
  256. return _discovered_machar(ftype)
  257. def _discovered_machar(ftype):
  258. """ Create MachAr instance with found information on float types
  259. """
  260. params = _MACHAR_PARAMS[ftype]
  261. return MachAr(lambda v: array([v], ftype),
  262. lambda v:_fr0(v.astype(params['itype']))[0],
  263. lambda v:array(_fr0(v)[0], ftype),
  264. lambda v: params['fmt'] % array(_fr0(v)[0], ftype),
  265. params['title'])
  266. @set_module('numpy')
  267. class finfo:
  268. """
  269. finfo(dtype)
  270. Machine limits for floating point types.
  271. Attributes
  272. ----------
  273. bits : int
  274. The number of bits occupied by the type.
  275. eps : float
  276. The difference between 1.0 and the next smallest representable float
  277. larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
  278. standard, ``eps = 2**-52``, approximately 2.22e-16.
  279. epsneg : float
  280. The difference between 1.0 and the next smallest representable float
  281. less than 1.0. For example, for 64-bit binary floats in the IEEE-754
  282. standard, ``epsneg = 2**-53``, approximately 1.11e-16.
  283. iexp : int
  284. The number of bits in the exponent portion of the floating point
  285. representation.
  286. machar : MachAr
  287. The object which calculated these parameters and holds more
  288. detailed information.
  289. machep : int
  290. The exponent that yields `eps`.
  291. max : floating point number of the appropriate type
  292. The largest representable number.
  293. maxexp : int
  294. The smallest positive power of the base (2) that causes overflow.
  295. min : floating point number of the appropriate type
  296. The smallest representable number, typically ``-max``.
  297. minexp : int
  298. The most negative power of the base (2) consistent with there
  299. being no leading 0's in the mantissa.
  300. negep : int
  301. The exponent that yields `epsneg`.
  302. nexp : int
  303. The number of bits in the exponent including its sign and bias.
  304. nmant : int
  305. The number of bits in the mantissa.
  306. precision : int
  307. The approximate number of decimal digits to which this kind of
  308. float is precise.
  309. resolution : floating point number of the appropriate type
  310. The approximate decimal resolution of this type, i.e.,
  311. ``10**-precision``.
  312. tiny : float
  313. The smallest positive floating point number with full precision
  314. (see Notes).
  315. Parameters
  316. ----------
  317. dtype : float, dtype, or instance
  318. Kind of floating point data-type about which to get information.
  319. See Also
  320. --------
  321. MachAr : The implementation of the tests that produce this information.
  322. iinfo : The equivalent for integer data types.
  323. spacing : The distance between a value and the nearest adjacent number
  324. nextafter : The next floating point value after x1 towards x2
  325. Notes
  326. -----
  327. For developers of NumPy: do not instantiate this at the module level.
  328. The initial calculation of these parameters is expensive and negatively
  329. impacts import times. These objects are cached, so calling ``finfo()``
  330. repeatedly inside your functions is not a problem.
  331. Note that ``tiny`` is not actually the smallest positive representable
  332. value in a NumPy floating point type. As in the IEEE-754 standard [1]_,
  333. NumPy floating point types make use of subnormal numbers to fill the
  334. gap between 0 and ``tiny``. However, subnormal numbers may have
  335. significantly reduced precision [2]_.
  336. References
  337. ----------
  338. .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
  339. pp.1-70, 2008, http://www.doi.org/10.1109/IEEESTD.2008.4610935
  340. .. [2] Wikipedia, "Denormal Numbers",
  341. https://en.wikipedia.org/wiki/Denormal_number
  342. """
  343. _finfo_cache = {}
  344. def __new__(cls, dtype):
  345. try:
  346. dtype = numeric.dtype(dtype)
  347. except TypeError:
  348. # In case a float instance was given
  349. dtype = numeric.dtype(type(dtype))
  350. obj = cls._finfo_cache.get(dtype, None)
  351. if obj is not None:
  352. return obj
  353. dtypes = [dtype]
  354. newdtype = numeric.obj2sctype(dtype)
  355. if newdtype is not dtype:
  356. dtypes.append(newdtype)
  357. dtype = newdtype
  358. if not issubclass(dtype, numeric.inexact):
  359. raise ValueError("data type %r not inexact" % (dtype))
  360. obj = cls._finfo_cache.get(dtype, None)
  361. if obj is not None:
  362. return obj
  363. if not issubclass(dtype, numeric.floating):
  364. newdtype = _convert_to_float[dtype]
  365. if newdtype is not dtype:
  366. dtypes.append(newdtype)
  367. dtype = newdtype
  368. obj = cls._finfo_cache.get(dtype, None)
  369. if obj is not None:
  370. return obj
  371. obj = object.__new__(cls)._init(dtype)
  372. for dt in dtypes:
  373. cls._finfo_cache[dt] = obj
  374. return obj
  375. def _init(self, dtype):
  376. self.dtype = numeric.dtype(dtype)
  377. machar = _get_machar(dtype)
  378. for word in ['precision', 'iexp',
  379. 'maxexp', 'minexp', 'negep',
  380. 'machep']:
  381. setattr(self, word, getattr(machar, word))
  382. for word in ['tiny', 'resolution', 'epsneg']:
  383. setattr(self, word, getattr(machar, word).flat[0])
  384. self.bits = self.dtype.itemsize * 8
  385. self.max = machar.huge.flat[0]
  386. self.min = -self.max
  387. self.eps = machar.eps.flat[0]
  388. self.nexp = machar.iexp
  389. self.nmant = machar.it
  390. self.machar = machar
  391. self._str_tiny = machar._str_xmin.strip()
  392. self._str_max = machar._str_xmax.strip()
  393. self._str_epsneg = machar._str_epsneg.strip()
  394. self._str_eps = machar._str_eps.strip()
  395. self._str_resolution = machar._str_resolution.strip()
  396. return self
  397. def __str__(self):
  398. fmt = (
  399. 'Machine parameters for %(dtype)s\n'
  400. '---------------------------------------------------------------\n'
  401. 'precision = %(precision)3s resolution = %(_str_resolution)s\n'
  402. 'machep = %(machep)6s eps = %(_str_eps)s\n'
  403. 'negep = %(negep)6s epsneg = %(_str_epsneg)s\n'
  404. 'minexp = %(minexp)6s tiny = %(_str_tiny)s\n'
  405. 'maxexp = %(maxexp)6s max = %(_str_max)s\n'
  406. 'nexp = %(nexp)6s min = -max\n'
  407. '---------------------------------------------------------------\n'
  408. )
  409. return fmt % self.__dict__
  410. def __repr__(self):
  411. c = self.__class__.__name__
  412. d = self.__dict__.copy()
  413. d['klass'] = c
  414. return (("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s,"
  415. " max=%(_str_max)s, dtype=%(dtype)s)") % d)
  416. @set_module('numpy')
  417. class iinfo:
  418. """
  419. iinfo(type)
  420. Machine limits for integer types.
  421. Attributes
  422. ----------
  423. bits : int
  424. The number of bits occupied by the type.
  425. min : int
  426. The smallest integer expressible by the type.
  427. max : int
  428. The largest integer expressible by the type.
  429. Parameters
  430. ----------
  431. int_type : integer type, dtype, or instance
  432. The kind of integer data type to get information about.
  433. See Also
  434. --------
  435. finfo : The equivalent for floating point data types.
  436. Examples
  437. --------
  438. With types:
  439. >>> ii16 = np.iinfo(np.int16)
  440. >>> ii16.min
  441. -32768
  442. >>> ii16.max
  443. 32767
  444. >>> ii32 = np.iinfo(np.int32)
  445. >>> ii32.min
  446. -2147483648
  447. >>> ii32.max
  448. 2147483647
  449. With instances:
  450. >>> ii32 = np.iinfo(np.int32(10))
  451. >>> ii32.min
  452. -2147483648
  453. >>> ii32.max
  454. 2147483647
  455. """
  456. _min_vals = {}
  457. _max_vals = {}
  458. def __init__(self, int_type):
  459. try:
  460. self.dtype = numeric.dtype(int_type)
  461. except TypeError:
  462. self.dtype = numeric.dtype(type(int_type))
  463. self.kind = self.dtype.kind
  464. self.bits = self.dtype.itemsize * 8
  465. self.key = "%s%d" % (self.kind, self.bits)
  466. if self.kind not in 'iu':
  467. raise ValueError("Invalid integer data type %r." % (self.kind,))
  468. @property
  469. def min(self):
  470. """Minimum value of given dtype."""
  471. if self.kind == 'u':
  472. return 0
  473. else:
  474. try:
  475. val = iinfo._min_vals[self.key]
  476. except KeyError:
  477. val = int(-(1 << (self.bits-1)))
  478. iinfo._min_vals[self.key] = val
  479. return val
  480. @property
  481. def max(self):
  482. """Maximum value of given dtype."""
  483. try:
  484. val = iinfo._max_vals[self.key]
  485. except KeyError:
  486. if self.kind == 'u':
  487. val = int((1 << self.bits) - 1)
  488. else:
  489. val = int((1 << (self.bits-1)) - 1)
  490. iinfo._max_vals[self.key] = val
  491. return val
  492. def __str__(self):
  493. """String representation."""
  494. fmt = (
  495. 'Machine parameters for %(dtype)s\n'
  496. '---------------------------------------------------------------\n'
  497. 'min = %(min)s\n'
  498. 'max = %(max)s\n'
  499. '---------------------------------------------------------------\n'
  500. )
  501. return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
  502. def __repr__(self):
  503. return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
  504. self.min, self.max, self.dtype)