arrayprint.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779
  1. """Array printing function
  2. $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
  3. """
  4. __all__ = ["array2string", "array_str", "array_repr",
  5. "set_printoptions", "get_printoptions", "printoptions",
  6. "format_float_positional", "format_float_scientific"]
  7. __docformat__ = 'restructuredtext'
  8. #
  9. # Written by Konrad Hinsen <hinsenk@ere.umontreal.ca>
  10. # last revision: 1996-3-13
  11. # modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details)
  12. # and by Perry Greenfield 2000-4-1 for numarray
  13. # and by Travis Oliphant 2005-8-22 for numpy
  14. # Note: Both scalartypes.c.src and arrayprint.py implement strs for numpy
  15. # scalars but for different purposes. scalartypes.c.src has str/reprs for when
  16. # the scalar is printed on its own, while arrayprint.py has strs for when
  17. # scalars are printed inside an ndarray. Only the latter strs are currently
  18. # user-customizable.
  19. import functools
  20. import numbers
  21. import sys
  22. try:
  23. from _thread import get_ident
  24. except ImportError:
  25. from _dummy_thread import get_ident
  26. import contextlib
  27. import operator
  28. import warnings
  29. import numpy as np
  30. from . import numerictypes as _nt
  31. from .fromnumeric import any
  32. from .multiarray import (
  33. array,
  34. datetime_as_string,
  35. datetime_data,
  36. dragon4_positional,
  37. dragon4_scientific,
  38. ndarray,
  39. )
  40. from .numeric import asarray, concatenate, errstate
  41. from .numerictypes import complex128, flexible, float64, int_
  42. from .overrides import array_function_dispatch, set_module
  43. from .printoptions import format_options
  44. from .umath import absolute, isfinite, isinf, isnat
  45. def _make_options_dict(precision=None, threshold=None, edgeitems=None,
  46. linewidth=None, suppress=None, nanstr=None, infstr=None,
  47. sign=None, formatter=None, floatmode=None, legacy=None,
  48. override_repr=None):
  49. """
  50. Make a dictionary out of the non-None arguments, plus conversion of
  51. *legacy* and sanity checks.
  52. """
  53. options = {k: v for k, v in list(locals().items()) if v is not None}
  54. if suppress is not None:
  55. options['suppress'] = bool(suppress)
  56. modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal']
  57. if floatmode not in modes + [None]:
  58. raise ValueError("floatmode option must be one of " +
  59. ", ".join(f'"{m}"' for m in modes))
  60. if sign not in [None, '-', '+', ' ']:
  61. raise ValueError("sign option must be one of ' ', '+', or '-'")
  62. if legacy is False:
  63. options['legacy'] = sys.maxsize
  64. elif legacy == False: # noqa: E712
  65. warnings.warn(
  66. f"Passing `legacy={legacy!r}` is deprecated.",
  67. FutureWarning, stacklevel=3
  68. )
  69. options['legacy'] = sys.maxsize
  70. elif legacy == '1.13':
  71. options['legacy'] = 113
  72. elif legacy == '1.21':
  73. options['legacy'] = 121
  74. elif legacy == '1.25':
  75. options['legacy'] = 125
  76. elif legacy == '2.1':
  77. options['legacy'] = 201
  78. elif legacy == '2.2':
  79. options['legacy'] = 202
  80. elif legacy is None:
  81. pass # OK, do nothing.
  82. else:
  83. warnings.warn(
  84. "legacy printing option can currently only be '1.13', '1.21', "
  85. "'1.25', '2.1', '2.2' or `False`", stacklevel=3)
  86. if threshold is not None:
  87. # forbid the bad threshold arg suggested by stack overflow, gh-12351
  88. if not isinstance(threshold, numbers.Number):
  89. raise TypeError("threshold must be numeric")
  90. if np.isnan(threshold):
  91. raise ValueError("threshold must be non-NAN, try "
  92. "sys.maxsize for untruncated representation")
  93. if precision is not None:
  94. # forbid the bad precision arg as suggested by issue #18254
  95. try:
  96. options['precision'] = operator.index(precision)
  97. except TypeError as e:
  98. raise TypeError('precision must be an integer') from e
  99. return options
  100. @set_module('numpy')
  101. def set_printoptions(precision=None, threshold=None, edgeitems=None,
  102. linewidth=None, suppress=None, nanstr=None,
  103. infstr=None, formatter=None, sign=None, floatmode=None,
  104. *, legacy=None, override_repr=None):
  105. """
  106. Set printing options.
  107. These options determine the way floating point numbers, arrays and
  108. other NumPy objects are displayed.
  109. Parameters
  110. ----------
  111. precision : int or None, optional
  112. Number of digits of precision for floating point output (default 8).
  113. May be None if `floatmode` is not `fixed`, to print as many digits as
  114. necessary to uniquely specify the value.
  115. threshold : int, optional
  116. Total number of array elements which trigger summarization
  117. rather than full repr (default 1000).
  118. To always use the full repr without summarization, pass `sys.maxsize`.
  119. edgeitems : int, optional
  120. Number of array items in summary at beginning and end of
  121. each dimension (default 3).
  122. linewidth : int, optional
  123. The number of characters per line for the purpose of inserting
  124. line breaks (default 75).
  125. suppress : bool, optional
  126. If True, always print floating point numbers using fixed point
  127. notation, in which case numbers equal to zero in the current precision
  128. will print as zero. If False, then scientific notation is used when
  129. absolute value of the smallest number is < 1e-4 or the ratio of the
  130. maximum absolute value to the minimum is > 1e3. The default is False.
  131. nanstr : str, optional
  132. String representation of floating point not-a-number (default nan).
  133. infstr : str, optional
  134. String representation of floating point infinity (default inf).
  135. sign : string, either '-', '+', or ' ', optional
  136. Controls printing of the sign of floating-point types. If '+', always
  137. print the sign of positive values. If ' ', always prints a space
  138. (whitespace character) in the sign position of positive values. If
  139. '-', omit the sign character of positive values. (default '-')
  140. .. versionchanged:: 2.0
  141. The sign parameter can now be an integer type, previously
  142. types were floating-point types.
  143. formatter : dict of callables, optional
  144. If not None, the keys should indicate the type(s) that the respective
  145. formatting function applies to. Callables should return a string.
  146. Types that are not specified (by their corresponding keys) are handled
  147. by the default formatters. Individual types for which a formatter
  148. can be set are:
  149. - 'bool'
  150. - 'int'
  151. - 'timedelta' : a `numpy.timedelta64`
  152. - 'datetime' : a `numpy.datetime64`
  153. - 'float'
  154. - 'longfloat' : 128-bit floats
  155. - 'complexfloat'
  156. - 'longcomplexfloat' : composed of two 128-bit floats
  157. - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
  158. - 'object' : `np.object_` arrays
  159. Other keys that can be used to set a group of types at once are:
  160. - 'all' : sets all types
  161. - 'int_kind' : sets 'int'
  162. - 'float_kind' : sets 'float' and 'longfloat'
  163. - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
  164. - 'str_kind' : sets 'numpystr'
  165. floatmode : str, optional
  166. Controls the interpretation of the `precision` option for
  167. floating-point types. Can take the following values
  168. (default maxprec_equal):
  169. * 'fixed': Always print exactly `precision` fractional digits,
  170. even if this would print more or fewer digits than
  171. necessary to specify the value uniquely.
  172. * 'unique': Print the minimum number of fractional digits necessary
  173. to represent each value uniquely. Different elements may
  174. have a different number of digits. The value of the
  175. `precision` option is ignored.
  176. * 'maxprec': Print at most `precision` fractional digits, but if
  177. an element can be uniquely represented with fewer digits
  178. only print it with that many.
  179. * 'maxprec_equal': Print at most `precision` fractional digits,
  180. but if every element in the array can be uniquely
  181. represented with an equal number of fewer digits, use that
  182. many digits for all elements.
  183. legacy : string or `False`, optional
  184. If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
  185. approximates numpy 1.13 print output by including a space in the sign
  186. position of floats and different behavior for 0d arrays. This also
  187. enables 1.21 legacy printing mode (described below).
  188. If set to the string ``'1.21'`` enables 1.21 legacy printing mode. This
  189. approximates numpy 1.21 print output of complex structured dtypes
  190. by not inserting spaces after commas that separate fields and after
  191. colons.
  192. If set to ``'1.25'`` approximates printing of 1.25 which mainly means
  193. that numeric scalars are printed without their type information, e.g.
  194. as ``3.0`` rather than ``np.float64(3.0)``.
  195. If set to ``'2.1'``, shape information is not given when arrays are
  196. summarized (i.e., multiple elements replaced with ``...``).
  197. If set to ``'2.2'``, the transition to use scientific notation for
  198. printing ``np.float16`` and ``np.float32`` types may happen later or
  199. not at all for larger values.
  200. If set to `False`, disables legacy mode.
  201. Unrecognized strings will be ignored with a warning for forward
  202. compatibility.
  203. .. versionchanged:: 1.22.0
  204. .. versionchanged:: 2.2
  205. override_repr: callable, optional
  206. If set a passed function will be used for generating arrays' repr.
  207. Other options will be ignored.
  208. See Also
  209. --------
  210. get_printoptions, printoptions, array2string
  211. Notes
  212. -----
  213. * ``formatter`` is always reset with a call to `set_printoptions`.
  214. * Use `printoptions` as a context manager to set the values temporarily.
  215. * These print options apply only to NumPy ndarrays, not to scalars.
  216. **Concurrency note:** see :ref:`text_formatting_options`
  217. Examples
  218. --------
  219. Floating point precision can be set:
  220. >>> import numpy as np
  221. >>> np.set_printoptions(precision=4)
  222. >>> np.array([1.123456789])
  223. [1.1235]
  224. Long arrays can be summarised:
  225. >>> np.set_printoptions(threshold=5)
  226. >>> np.arange(10)
  227. array([0, 1, 2, ..., 7, 8, 9], shape=(10,))
  228. Small results can be suppressed:
  229. >>> eps = np.finfo(float).eps
  230. >>> x = np.arange(4.)
  231. >>> x**2 - (x + eps)**2
  232. array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
  233. >>> np.set_printoptions(suppress=True)
  234. >>> x**2 - (x + eps)**2
  235. array([-0., -0., 0., 0.])
  236. A custom formatter can be used to display array elements as desired:
  237. >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
  238. >>> x = np.arange(3)
  239. >>> x
  240. array([int: 0, int: -1, int: -2])
  241. >>> np.set_printoptions() # formatter gets reset
  242. >>> x
  243. array([0, 1, 2])
  244. To put back the default options, you can use:
  245. >>> np.set_printoptions(edgeitems=3, infstr='inf',
  246. ... linewidth=75, nanstr='nan', precision=8,
  247. ... suppress=False, threshold=1000, formatter=None)
  248. Also to temporarily override options, use `printoptions`
  249. as a context manager:
  250. >>> with np.printoptions(precision=2, suppress=True, threshold=5):
  251. ... np.linspace(0, 10, 10)
  252. array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ], shape=(10,))
  253. """
  254. _set_printoptions(precision, threshold, edgeitems, linewidth, suppress,
  255. nanstr, infstr, formatter, sign, floatmode,
  256. legacy=legacy, override_repr=override_repr)
  257. def _set_printoptions(precision=None, threshold=None, edgeitems=None,
  258. linewidth=None, suppress=None, nanstr=None,
  259. infstr=None, formatter=None, sign=None, floatmode=None,
  260. *, legacy=None, override_repr=None):
  261. new_opt = _make_options_dict(precision, threshold, edgeitems, linewidth,
  262. suppress, nanstr, infstr, sign, formatter,
  263. floatmode, legacy)
  264. # formatter and override_repr are always reset
  265. new_opt['formatter'] = formatter
  266. new_opt['override_repr'] = override_repr
  267. updated_opt = format_options.get() | new_opt
  268. updated_opt.update(new_opt)
  269. if updated_opt['legacy'] == 113:
  270. updated_opt['sign'] = '-'
  271. return format_options.set(updated_opt)
  272. @set_module('numpy')
  273. def get_printoptions():
  274. """
  275. Return the current print options.
  276. Returns
  277. -------
  278. print_opts : dict
  279. Dictionary of current print options with keys
  280. - precision : int
  281. - threshold : int
  282. - edgeitems : int
  283. - linewidth : int
  284. - suppress : bool
  285. - nanstr : str
  286. - infstr : str
  287. - sign : str
  288. - formatter : dict of callables
  289. - floatmode : str
  290. - legacy : str or False
  291. For a full description of these options, see `set_printoptions`.
  292. Notes
  293. -----
  294. These print options apply only to NumPy ndarrays, not to scalars.
  295. **Concurrency note:** see :ref:`text_formatting_options`
  296. See Also
  297. --------
  298. set_printoptions, printoptions
  299. Examples
  300. --------
  301. >>> import numpy as np
  302. >>> np.get_printoptions()
  303. {'edgeitems': 3, 'threshold': 1000, ..., 'override_repr': None}
  304. >>> np.get_printoptions()['linewidth']
  305. 75
  306. >>> np.set_printoptions(linewidth=100)
  307. >>> np.get_printoptions()['linewidth']
  308. 100
  309. """
  310. opts = format_options.get().copy()
  311. opts['legacy'] = {
  312. 113: '1.13', 121: '1.21', 125: '1.25', 201: '2.1',
  313. 202: '2.2', sys.maxsize: False,
  314. }[opts['legacy']]
  315. return opts
  316. def _get_legacy_print_mode():
  317. """Return the legacy print mode as an int."""
  318. return format_options.get()['legacy']
  319. @set_module('numpy')
  320. @contextlib.contextmanager
  321. def printoptions(*args, **kwargs):
  322. """Context manager for setting print options.
  323. Set print options for the scope of the `with` block, and restore the old
  324. options at the end. See `set_printoptions` for the full description of
  325. available options.
  326. Examples
  327. --------
  328. >>> import numpy as np
  329. >>> from numpy.testing import assert_equal
  330. >>> with np.printoptions(precision=2):
  331. ... np.array([2.0]) / 3
  332. array([0.67])
  333. The `as`-clause of the `with`-statement gives the current print options:
  334. >>> with np.printoptions(precision=2) as opts:
  335. ... assert_equal(opts, np.get_printoptions())
  336. See Also
  337. --------
  338. set_printoptions, get_printoptions
  339. Notes
  340. -----
  341. These print options apply only to NumPy ndarrays, not to scalars.
  342. **Concurrency note:** see :ref:`text_formatting_options`
  343. """
  344. token = _set_printoptions(*args, **kwargs)
  345. try:
  346. yield get_printoptions()
  347. finally:
  348. format_options.reset(token)
  349. def _leading_trailing(a, edgeitems, index=()):
  350. """
  351. Keep only the N-D corners (leading and trailing edges) of an array.
  352. Should be passed a base-class ndarray, since it makes no guarantees about
  353. preserving subclasses.
  354. """
  355. axis = len(index)
  356. if axis == a.ndim:
  357. return a[index]
  358. if a.shape[axis] > 2 * edgeitems:
  359. return concatenate((
  360. _leading_trailing(a, edgeitems, index + np.index_exp[:edgeitems]),
  361. _leading_trailing(a, edgeitems, index + np.index_exp[-edgeitems:])
  362. ), axis=axis)
  363. else:
  364. return _leading_trailing(a, edgeitems, index + np.index_exp[:])
  365. def _object_format(o):
  366. """ Object arrays containing lists should be printed unambiguously """
  367. if type(o) is list:
  368. fmt = 'list({!r})'
  369. else:
  370. fmt = '{!r}'
  371. return fmt.format(o)
  372. def repr_format(x):
  373. if isinstance(x, (np.str_, np.bytes_)):
  374. return repr(x.item())
  375. return repr(x)
  376. def str_format(x):
  377. if isinstance(x, (np.str_, np.bytes_)):
  378. return str(x.item())
  379. return str(x)
  380. def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy,
  381. formatter, **kwargs):
  382. # note: extra arguments in kwargs are ignored
  383. # wrapped in lambdas to avoid taking a code path
  384. # with the wrong type of data
  385. formatdict = {
  386. 'bool': lambda: BoolFormat(data),
  387. 'int': lambda: IntegerFormat(data, sign),
  388. 'float': lambda: FloatingFormat(
  389. data, precision, floatmode, suppress, sign, legacy=legacy),
  390. 'longfloat': lambda: FloatingFormat(
  391. data, precision, floatmode, suppress, sign, legacy=legacy),
  392. 'complexfloat': lambda: ComplexFloatingFormat(
  393. data, precision, floatmode, suppress, sign, legacy=legacy),
  394. 'longcomplexfloat': lambda: ComplexFloatingFormat(
  395. data, precision, floatmode, suppress, sign, legacy=legacy),
  396. 'datetime': lambda: DatetimeFormat(data, legacy=legacy),
  397. 'timedelta': lambda: TimedeltaFormat(data),
  398. 'object': lambda: _object_format,
  399. 'void': lambda: str_format,
  400. 'numpystr': lambda: repr_format}
  401. # we need to wrap values in `formatter` in a lambda, so that the interface
  402. # is the same as the above values.
  403. def indirect(x):
  404. return lambda: x
  405. if formatter is not None:
  406. fkeys = [k for k in formatter.keys() if formatter[k] is not None]
  407. if 'all' in fkeys:
  408. for key in formatdict.keys():
  409. formatdict[key] = indirect(formatter['all'])
  410. if 'int_kind' in fkeys:
  411. for key in ['int']:
  412. formatdict[key] = indirect(formatter['int_kind'])
  413. if 'float_kind' in fkeys:
  414. for key in ['float', 'longfloat']:
  415. formatdict[key] = indirect(formatter['float_kind'])
  416. if 'complex_kind' in fkeys:
  417. for key in ['complexfloat', 'longcomplexfloat']:
  418. formatdict[key] = indirect(formatter['complex_kind'])
  419. if 'str_kind' in fkeys:
  420. formatdict['numpystr'] = indirect(formatter['str_kind'])
  421. for key in formatdict.keys():
  422. if key in fkeys:
  423. formatdict[key] = indirect(formatter[key])
  424. return formatdict
  425. def _get_format_function(data, **options):
  426. """
  427. find the right formatting function for the dtype_
  428. """
  429. dtype_ = data.dtype
  430. dtypeobj = dtype_.type
  431. formatdict = _get_formatdict(data, **options)
  432. if dtypeobj is None:
  433. return formatdict["numpystr"]()
  434. elif issubclass(dtypeobj, _nt.bool):
  435. return formatdict['bool']()
  436. elif issubclass(dtypeobj, _nt.integer):
  437. if issubclass(dtypeobj, _nt.timedelta64):
  438. return formatdict['timedelta']()
  439. else:
  440. return formatdict['int']()
  441. elif issubclass(dtypeobj, _nt.floating):
  442. if issubclass(dtypeobj, _nt.longdouble):
  443. return formatdict['longfloat']()
  444. else:
  445. return formatdict['float']()
  446. elif issubclass(dtypeobj, _nt.complexfloating):
  447. if issubclass(dtypeobj, _nt.clongdouble):
  448. return formatdict['longcomplexfloat']()
  449. else:
  450. return formatdict['complexfloat']()
  451. elif issubclass(dtypeobj, (_nt.str_, _nt.bytes_)):
  452. return formatdict['numpystr']()
  453. elif issubclass(dtypeobj, _nt.datetime64):
  454. return formatdict['datetime']()
  455. elif issubclass(dtypeobj, _nt.object_):
  456. return formatdict['object']()
  457. elif issubclass(dtypeobj, _nt.void):
  458. if dtype_.names is not None:
  459. return StructuredVoidFormat.from_data(data, **options)
  460. else:
  461. return formatdict['void']()
  462. else:
  463. return formatdict['numpystr']()
  464. def _recursive_guard(fillvalue='...'):
  465. """
  466. Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs
  467. Decorates a function such that if it calls itself with the same first
  468. argument, it returns `fillvalue` instead of recursing.
  469. Largely copied from reprlib.recursive_repr
  470. """
  471. def decorating_function(f):
  472. repr_running = set()
  473. @functools.wraps(f)
  474. def wrapper(self, *args, **kwargs):
  475. key = id(self), get_ident()
  476. if key in repr_running:
  477. return fillvalue
  478. repr_running.add(key)
  479. try:
  480. return f(self, *args, **kwargs)
  481. finally:
  482. repr_running.discard(key)
  483. return wrapper
  484. return decorating_function
  485. # gracefully handle recursive calls, when object arrays contain themselves
  486. @_recursive_guard()
  487. def _array2string(a, options, separator=' ', prefix=""):
  488. # The formatter __init__s in _get_format_function cannot deal with
  489. # subclasses yet, and we also need to avoid recursion issues in
  490. # _formatArray with subclasses which return 0d arrays in place of scalars
  491. data = asarray(a)
  492. if a.shape == ():
  493. a = data
  494. if a.size > options['threshold']:
  495. summary_insert = "..."
  496. data = _leading_trailing(data, options['edgeitems'])
  497. else:
  498. summary_insert = ""
  499. # find the right formatting function for the array
  500. format_function = _get_format_function(data, **options)
  501. # skip over "["
  502. next_line_prefix = " "
  503. # skip over array(
  504. next_line_prefix += " " * len(prefix)
  505. lst = _formatArray(a, format_function, options['linewidth'],
  506. next_line_prefix, separator, options['edgeitems'],
  507. summary_insert, options['legacy'])
  508. return lst
  509. def _array2string_dispatcher(
  510. a, max_line_width=None, precision=None,
  511. suppress_small=None, separator=None, prefix=None,
  512. *, formatter=None, threshold=None,
  513. edgeitems=None, sign=None, floatmode=None, suffix=None,
  514. legacy=None):
  515. return (a,)
  516. @array_function_dispatch(_array2string_dispatcher, module='numpy')
  517. def array2string(a, max_line_width=None, precision=None,
  518. suppress_small=None, separator=' ', prefix="",
  519. *, formatter=None, threshold=None,
  520. edgeitems=None, sign=None, floatmode=None, suffix="",
  521. legacy=None):
  522. """
  523. Return a string representation of an array.
  524. Parameters
  525. ----------
  526. a : ndarray
  527. Input array.
  528. max_line_width : int, optional
  529. Inserts newlines if text is longer than `max_line_width`.
  530. Defaults to ``numpy.get_printoptions()['linewidth']``.
  531. precision : int or None, optional
  532. Floating point precision.
  533. Defaults to ``numpy.get_printoptions()['precision']``.
  534. suppress_small : bool, optional
  535. Represent numbers "very close" to zero as zero; default is False.
  536. Very close is defined by precision: if the precision is 8, e.g.,
  537. numbers smaller (in absolute value) than 5e-9 are represented as
  538. zero.
  539. Defaults to ``numpy.get_printoptions()['suppress']``.
  540. separator : str, optional
  541. Inserted between elements.
  542. prefix : str, optional
  543. suffix : str, optional
  544. The length of the prefix and suffix strings are used to respectively
  545. align and wrap the output. An array is typically printed as::
  546. prefix + array2string(a) + suffix
  547. The output is left-padded by the length of the prefix string, and
  548. wrapping is forced at the column ``max_line_width - len(suffix)``.
  549. It should be noted that the content of prefix and suffix strings are
  550. not included in the output.
  551. formatter : dict of callables, optional
  552. If not None, the keys should indicate the type(s) that the respective
  553. formatting function applies to. Callables should return a string.
  554. Types that are not specified (by their corresponding keys) are handled
  555. by the default formatters. Individual types for which a formatter
  556. can be set are:
  557. - 'bool'
  558. - 'int'
  559. - 'timedelta' : a `numpy.timedelta64`
  560. - 'datetime' : a `numpy.datetime64`
  561. - 'float'
  562. - 'longfloat' : 128-bit floats
  563. - 'complexfloat'
  564. - 'longcomplexfloat' : composed of two 128-bit floats
  565. - 'void' : type `numpy.void`
  566. - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
  567. Other keys that can be used to set a group of types at once are:
  568. - 'all' : sets all types
  569. - 'int_kind' : sets 'int'
  570. - 'float_kind' : sets 'float' and 'longfloat'
  571. - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
  572. - 'str_kind' : sets 'numpystr'
  573. threshold : int, optional
  574. Total number of array elements which trigger summarization
  575. rather than full repr.
  576. Defaults to ``numpy.get_printoptions()['threshold']``.
  577. edgeitems : int, optional
  578. Number of array items in summary at beginning and end of
  579. each dimension.
  580. Defaults to ``numpy.get_printoptions()['edgeitems']``.
  581. sign : string, either '-', '+', or ' ', optional
  582. Controls printing of the sign of floating-point types. If '+', always
  583. print the sign of positive values. If ' ', always prints a space
  584. (whitespace character) in the sign position of positive values. If
  585. '-', omit the sign character of positive values.
  586. Defaults to ``numpy.get_printoptions()['sign']``.
  587. .. versionchanged:: 2.0
  588. The sign parameter can now be an integer type, previously
  589. types were floating-point types.
  590. floatmode : str, optional
  591. Controls the interpretation of the `precision` option for
  592. floating-point types.
  593. Defaults to ``numpy.get_printoptions()['floatmode']``.
  594. Can take the following values:
  595. - 'fixed': Always print exactly `precision` fractional digits,
  596. even if this would print more or fewer digits than
  597. necessary to specify the value uniquely.
  598. - 'unique': Print the minimum number of fractional digits necessary
  599. to represent each value uniquely. Different elements may
  600. have a different number of digits. The value of the
  601. `precision` option is ignored.
  602. - 'maxprec': Print at most `precision` fractional digits, but if
  603. an element can be uniquely represented with fewer digits
  604. only print it with that many.
  605. - 'maxprec_equal': Print at most `precision` fractional digits,
  606. but if every element in the array can be uniquely
  607. represented with an equal number of fewer digits, use that
  608. many digits for all elements.
  609. legacy : string or `False`, optional
  610. If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
  611. approximates numpy 1.13 print output by including a space in the sign
  612. position of floats and different behavior for 0d arrays. If set to
  613. `False`, disables legacy mode. Unrecognized strings will be ignored
  614. with a warning for forward compatibility.
  615. Returns
  616. -------
  617. array_str : str
  618. String representation of the array.
  619. Raises
  620. ------
  621. TypeError
  622. if a callable in `formatter` does not return a string.
  623. See Also
  624. --------
  625. array_str, array_repr, set_printoptions, get_printoptions
  626. Notes
  627. -----
  628. If a formatter is specified for a certain type, the `precision` keyword is
  629. ignored for that type.
  630. This is a very flexible function; `array_repr` and `array_str` are using
  631. `array2string` internally so keywords with the same name should work
  632. identically in all three functions.
  633. Examples
  634. --------
  635. >>> import numpy as np
  636. >>> x = np.array([1e-16,1,2,3])
  637. >>> np.array2string(x, precision=2, separator=',',
  638. ... suppress_small=True)
  639. '[0.,1.,2.,3.]'
  640. >>> x = np.arange(3.)
  641. >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
  642. '[0.00 1.00 2.00]'
  643. >>> x = np.arange(3)
  644. >>> np.array2string(x, formatter={'int':lambda x: hex(x)})
  645. '[0x0 0x1 0x2]'
  646. """
  647. overrides = _make_options_dict(precision, threshold, edgeitems,
  648. max_line_width, suppress_small, None, None,
  649. sign, formatter, floatmode, legacy)
  650. options = format_options.get().copy()
  651. options.update(overrides)
  652. if options['legacy'] <= 113:
  653. if a.shape == () and a.dtype.names is None:
  654. return repr(a.item())
  655. if options['legacy'] > 113:
  656. options['linewidth'] -= len(suffix)
  657. # treat as a null array if any of shape elements == 0
  658. if a.size == 0:
  659. return "[]"
  660. return _array2string(a, options, separator, prefix)
  661. def _extendLine(s, line, word, line_width, next_line_prefix, legacy):
  662. needs_wrap = len(line) + len(word) > line_width
  663. if legacy > 113:
  664. # don't wrap lines if it won't help
  665. if len(line) <= len(next_line_prefix):
  666. needs_wrap = False
  667. if needs_wrap:
  668. s += line.rstrip() + "\n"
  669. line = next_line_prefix
  670. line += word
  671. return s, line
  672. def _extendLine_pretty(s, line, word, line_width, next_line_prefix, legacy):
  673. """
  674. Extends line with nicely formatted (possibly multi-line) string ``word``.
  675. """
  676. words = word.splitlines()
  677. if len(words) == 1 or legacy <= 113:
  678. return _extendLine(s, line, word, line_width, next_line_prefix, legacy)
  679. max_word_length = max(len(word) for word in words)
  680. if (len(line) + max_word_length > line_width and
  681. len(line) > len(next_line_prefix)):
  682. s += line.rstrip() + '\n'
  683. line = next_line_prefix + words[0]
  684. indent = next_line_prefix
  685. else:
  686. indent = len(line) * ' '
  687. line += words[0]
  688. for word in words[1::]:
  689. s += line.rstrip() + '\n'
  690. line = indent + word
  691. suffix_length = max_word_length - len(words[-1])
  692. line += suffix_length * ' '
  693. return s, line
  694. def _formatArray(a, format_function, line_width, next_line_prefix,
  695. separator, edge_items, summary_insert, legacy):
  696. """formatArray is designed for two modes of operation:
  697. 1. Full output
  698. 2. Summarized output
  699. """
  700. def recurser(index, hanging_indent, curr_width):
  701. """
  702. By using this local function, we don't need to recurse with all the
  703. arguments. Since this function is not created recursively, the cost is
  704. not significant
  705. """
  706. axis = len(index)
  707. axes_left = a.ndim - axis
  708. if axes_left == 0:
  709. return format_function(a[index])
  710. # when recursing, add a space to align with the [ added, and reduce the
  711. # length of the line by 1
  712. next_hanging_indent = hanging_indent + ' '
  713. if legacy <= 113:
  714. next_width = curr_width
  715. else:
  716. next_width = curr_width - len(']')
  717. a_len = a.shape[axis]
  718. show_summary = summary_insert and 2 * edge_items < a_len
  719. if show_summary:
  720. leading_items = edge_items
  721. trailing_items = edge_items
  722. else:
  723. leading_items = 0
  724. trailing_items = a_len
  725. # stringify the array with the hanging indent on the first line too
  726. s = ''
  727. # last axis (rows) - wrap elements if they would not fit on one line
  728. if axes_left == 1:
  729. # the length up until the beginning of the separator / bracket
  730. if legacy <= 113:
  731. elem_width = curr_width - len(separator.rstrip())
  732. else:
  733. elem_width = curr_width - max(
  734. len(separator.rstrip()), len(']')
  735. )
  736. line = hanging_indent
  737. for i in range(leading_items):
  738. word = recurser(index + (i,), next_hanging_indent, next_width)
  739. s, line = _extendLine_pretty(
  740. s, line, word, elem_width, hanging_indent, legacy)
  741. line += separator
  742. if show_summary:
  743. s, line = _extendLine(
  744. s, line, summary_insert, elem_width, hanging_indent, legacy
  745. )
  746. if legacy <= 113:
  747. line += ", "
  748. else:
  749. line += separator
  750. for i in range(trailing_items, 1, -1):
  751. word = recurser(index + (-i,), next_hanging_indent, next_width)
  752. s, line = _extendLine_pretty(
  753. s, line, word, elem_width, hanging_indent, legacy)
  754. line += separator
  755. if legacy <= 113:
  756. # width of the separator is not considered on 1.13
  757. elem_width = curr_width
  758. word = recurser(index + (-1,), next_hanging_indent, next_width)
  759. s, line = _extendLine_pretty(
  760. s, line, word, elem_width, hanging_indent, legacy)
  761. s += line
  762. # other axes - insert newlines between rows
  763. else:
  764. s = ''
  765. line_sep = separator.rstrip() + '\n' * (axes_left - 1)
  766. for i in range(leading_items):
  767. nested = recurser(
  768. index + (i,), next_hanging_indent, next_width
  769. )
  770. s += hanging_indent + nested + line_sep
  771. if show_summary:
  772. if legacy <= 113:
  773. # trailing space, fixed nbr of newlines,
  774. # and fixed separator
  775. s += hanging_indent + summary_insert + ", \n"
  776. else:
  777. s += hanging_indent + summary_insert + line_sep
  778. for i in range(trailing_items, 1, -1):
  779. nested = recurser(index + (-i,), next_hanging_indent,
  780. next_width)
  781. s += hanging_indent + nested + line_sep
  782. nested = recurser(index + (-1,), next_hanging_indent, next_width)
  783. s += hanging_indent + nested
  784. # remove the hanging indent, and wrap in []
  785. s = '[' + s[len(hanging_indent):] + ']'
  786. return s
  787. try:
  788. # invoke the recursive part with an initial index and prefix
  789. return recurser(index=(),
  790. hanging_indent=next_line_prefix,
  791. curr_width=line_width)
  792. finally:
  793. # recursive closures have a cyclic reference to themselves, which
  794. # requires gc to collect (gh-10620). To avoid this problem, for
  795. # performance and PyPy friendliness, we break the cycle:
  796. recurser = None
  797. def _none_or_positive_arg(x, name):
  798. if x is None:
  799. return -1
  800. if x < 0:
  801. raise ValueError(f"{name} must be >= 0")
  802. return x
  803. class FloatingFormat:
  804. """ Formatter for subtypes of np.floating """
  805. def __init__(self, data, precision, floatmode, suppress_small, sign=False,
  806. *, legacy=None):
  807. # for backcompatibility, accept bools
  808. if isinstance(sign, bool):
  809. sign = '+' if sign else '-'
  810. self._legacy = legacy
  811. if self._legacy <= 113:
  812. # when not 0d, legacy does not support '-'
  813. if data.shape != () and sign == '-':
  814. sign = ' '
  815. self.floatmode = floatmode
  816. if floatmode == 'unique':
  817. self.precision = None
  818. else:
  819. self.precision = precision
  820. self.precision = _none_or_positive_arg(self.precision, 'precision')
  821. self.suppress_small = suppress_small
  822. self.sign = sign
  823. self.exp_format = False
  824. self.large_exponent = False
  825. self.fillFormat(data)
  826. def fillFormat(self, data):
  827. # only the finite values are used to compute the number of digits
  828. finite_vals = data[isfinite(data)]
  829. # choose exponential mode based on the non-zero finite values:
  830. abs_non_zero = absolute(finite_vals[finite_vals != 0])
  831. if len(abs_non_zero) != 0:
  832. max_val = np.max(abs_non_zero)
  833. min_val = np.min(abs_non_zero)
  834. if self._legacy <= 202:
  835. exp_cutoff_max = 1.e8
  836. else:
  837. # consider data type while deciding the max cutoff for exp format
  838. exp_cutoff_max = 10.**min(8, np.finfo(data.dtype).precision)
  839. with errstate(over='ignore'): # division can overflow
  840. if max_val >= exp_cutoff_max or (not self.suppress_small and
  841. (min_val < 0.0001 or max_val / min_val > 1000.)):
  842. self.exp_format = True
  843. # do a first pass of printing all the numbers, to determine sizes
  844. if len(finite_vals) == 0:
  845. self.pad_left = 0
  846. self.pad_right = 0
  847. self.trim = '.'
  848. self.exp_size = -1
  849. self.unique = True
  850. self.min_digits = None
  851. elif self.exp_format:
  852. trim, unique = '.', True
  853. if self.floatmode == 'fixed' or self._legacy <= 113:
  854. trim, unique = 'k', False
  855. strs = (dragon4_scientific(x, precision=self.precision,
  856. unique=unique, trim=trim, sign=self.sign == '+')
  857. for x in finite_vals)
  858. frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs))
  859. int_part, frac_part = zip(*(s.split('.') for s in frac_strs))
  860. self.exp_size = max(len(s) for s in exp_strs) - 1
  861. self.trim = 'k'
  862. self.precision = max(len(s) for s in frac_part)
  863. self.min_digits = self.precision
  864. self.unique = unique
  865. # for back-compat with np 1.13, use 2 spaces & sign and full prec
  866. if self._legacy <= 113:
  867. self.pad_left = 3
  868. else:
  869. # this should be only 1 or 2. Can be calculated from sign.
  870. self.pad_left = max(len(s) for s in int_part)
  871. # pad_right is only needed for nan length calculation
  872. self.pad_right = self.exp_size + 2 + self.precision
  873. else:
  874. trim, unique = '.', True
  875. if self.floatmode == 'fixed':
  876. trim, unique = 'k', False
  877. strs = (dragon4_positional(x, precision=self.precision,
  878. fractional=True,
  879. unique=unique, trim=trim,
  880. sign=self.sign == '+')
  881. for x in finite_vals)
  882. int_part, frac_part = zip(*(s.split('.') for s in strs))
  883. if self._legacy <= 113:
  884. self.pad_left = 1 + max(len(s.lstrip('-+')) for s in int_part)
  885. else:
  886. self.pad_left = max(len(s) for s in int_part)
  887. self.pad_right = max(len(s) for s in frac_part)
  888. self.exp_size = -1
  889. self.unique = unique
  890. if self.floatmode in ['fixed', 'maxprec_equal']:
  891. self.precision = self.min_digits = self.pad_right
  892. self.trim = 'k'
  893. else:
  894. self.trim = '.'
  895. self.min_digits = 0
  896. if self._legacy > 113:
  897. # account for sign = ' ' by adding one to pad_left
  898. if self.sign == ' ' and not any(np.signbit(finite_vals)):
  899. self.pad_left += 1
  900. # if there are non-finite values, may need to increase pad_left
  901. if data.size != finite_vals.size:
  902. neginf = self.sign != '-' or any(data[isinf(data)] < 0)
  903. offset = self.pad_right + 1 # +1 for decimal pt
  904. current_options = format_options.get()
  905. self.pad_left = max(
  906. self.pad_left, len(current_options['nanstr']) - offset,
  907. len(current_options['infstr']) + neginf - offset
  908. )
  909. def __call__(self, x):
  910. if not np.isfinite(x):
  911. with errstate(invalid='ignore'):
  912. current_options = format_options.get()
  913. if np.isnan(x):
  914. sign = '+' if self.sign == '+' else ''
  915. ret = sign + current_options['nanstr']
  916. else: # isinf
  917. sign = '-' if x < 0 else '+' if self.sign == '+' else ''
  918. ret = sign + current_options['infstr']
  919. return ' ' * (
  920. self.pad_left + self.pad_right + 1 - len(ret)
  921. ) + ret
  922. if self.exp_format:
  923. return dragon4_scientific(x,
  924. precision=self.precision,
  925. min_digits=self.min_digits,
  926. unique=self.unique,
  927. trim=self.trim,
  928. sign=self.sign == '+',
  929. pad_left=self.pad_left,
  930. exp_digits=self.exp_size)
  931. else:
  932. return dragon4_positional(x,
  933. precision=self.precision,
  934. min_digits=self.min_digits,
  935. unique=self.unique,
  936. fractional=True,
  937. trim=self.trim,
  938. sign=self.sign == '+',
  939. pad_left=self.pad_left,
  940. pad_right=self.pad_right)
  941. @set_module('numpy')
  942. def format_float_scientific(x, precision=None, unique=True, trim='k',
  943. sign=False, pad_left=None, exp_digits=None,
  944. min_digits=None):
  945. """
  946. Format a floating-point scalar as a decimal string in scientific notation.
  947. Provides control over rounding, trimming and padding. Uses and assumes
  948. IEEE unbiased rounding. Uses the "Dragon4" algorithm.
  949. Parameters
  950. ----------
  951. x : python float or numpy floating scalar
  952. Value to format.
  953. precision : non-negative integer or None, optional
  954. Maximum number of digits to print. May be None if `unique` is
  955. `True`, but must be an integer if unique is `False`.
  956. unique : boolean, optional
  957. If `True`, use a digit-generation strategy which gives the shortest
  958. representation which uniquely identifies the floating-point number from
  959. other values of the same type, by judicious rounding. If `precision`
  960. is given fewer digits than necessary can be printed. If `min_digits`
  961. is given more can be printed, in which cases the last digit is rounded
  962. with unbiased rounding.
  963. If `False`, digits are generated as if printing an infinite-precision
  964. value and stopping after `precision` digits, rounding the remaining
  965. value with unbiased rounding
  966. trim : one of 'k', '.', '0', '-', optional
  967. Controls post-processing trimming of trailing digits, as follows:
  968. * 'k' : keep trailing zeros, keep decimal point (no trimming)
  969. * '.' : trim all trailing zeros, leave decimal point
  970. * '0' : trim all but the zero before the decimal point. Insert the
  971. zero if it is missing.
  972. * '-' : trim trailing zeros and any trailing decimal point
  973. sign : boolean, optional
  974. Whether to show the sign for positive values.
  975. pad_left : non-negative integer, optional
  976. Pad the left side of the string with whitespace until at least that
  977. many characters are to the left of the decimal point.
  978. exp_digits : non-negative integer, optional
  979. Pad the exponent with zeros until it contains at least this
  980. many digits. If omitted, the exponent will be at least 2 digits.
  981. min_digits : non-negative integer or None, optional
  982. Minimum number of digits to print. This only has an effect for
  983. `unique=True`. In that case more digits than necessary to uniquely
  984. identify the value may be printed and rounded unbiased.
  985. .. versionadded:: 1.21.0
  986. Returns
  987. -------
  988. rep : string
  989. The string representation of the floating point value
  990. See Also
  991. --------
  992. format_float_positional
  993. Examples
  994. --------
  995. >>> import numpy as np
  996. >>> np.format_float_scientific(np.float32(np.pi))
  997. '3.1415927e+00'
  998. >>> s = np.float32(1.23e24)
  999. >>> np.format_float_scientific(s, unique=False, precision=15)
  1000. '1.230000071797338e+24'
  1001. >>> np.format_float_scientific(s, exp_digits=4)
  1002. '1.23e+0024'
  1003. """
  1004. precision = _none_or_positive_arg(precision, 'precision')
  1005. pad_left = _none_or_positive_arg(pad_left, 'pad_left')
  1006. exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits')
  1007. min_digits = _none_or_positive_arg(min_digits, 'min_digits')
  1008. if min_digits > 0 and precision > 0 and min_digits > precision:
  1009. raise ValueError("min_digits must be less than or equal to precision")
  1010. return dragon4_scientific(x, precision=precision, unique=unique,
  1011. trim=trim, sign=sign, pad_left=pad_left,
  1012. exp_digits=exp_digits, min_digits=min_digits)
  1013. @set_module('numpy')
  1014. def format_float_positional(x, precision=None, unique=True,
  1015. fractional=True, trim='k', sign=False,
  1016. pad_left=None, pad_right=None, min_digits=None):
  1017. """
  1018. Format a floating-point scalar as a decimal string in positional notation.
  1019. Provides control over rounding, trimming and padding. Uses and assumes
  1020. IEEE unbiased rounding. Uses the "Dragon4" algorithm.
  1021. Parameters
  1022. ----------
  1023. x : python float or numpy floating scalar
  1024. Value to format.
  1025. precision : non-negative integer or None, optional
  1026. Maximum number of digits to print. May be None if `unique` is
  1027. `True`, but must be an integer if unique is `False`.
  1028. unique : boolean, optional
  1029. If `True`, use a digit-generation strategy which gives the shortest
  1030. representation which uniquely identifies the floating-point number from
  1031. other values of the same type, by judicious rounding. If `precision`
  1032. is given fewer digits than necessary can be printed, or if `min_digits`
  1033. is given more can be printed, in which cases the last digit is rounded
  1034. with unbiased rounding.
  1035. If `False`, digits are generated as if printing an infinite-precision
  1036. value and stopping after `precision` digits, rounding the remaining
  1037. value with unbiased rounding
  1038. fractional : boolean, optional
  1039. If `True`, the cutoffs of `precision` and `min_digits` refer to the
  1040. total number of digits after the decimal point, including leading
  1041. zeros.
  1042. If `False`, `precision` and `min_digits` refer to the total number of
  1043. significant digits, before or after the decimal point, ignoring leading
  1044. zeros.
  1045. trim : one of 'k', '.', '0', '-', optional
  1046. Controls post-processing trimming of trailing digits, as follows:
  1047. * 'k' : keep trailing zeros, keep decimal point (no trimming)
  1048. * '.' : trim all trailing zeros, leave decimal point
  1049. * '0' : trim all but the zero before the decimal point. Insert the
  1050. zero if it is missing.
  1051. * '-' : trim trailing zeros and any trailing decimal point
  1052. sign : boolean, optional
  1053. Whether to show the sign for positive values.
  1054. pad_left : non-negative integer, optional
  1055. Pad the left side of the string with whitespace until at least that
  1056. many characters are to the left of the decimal point.
  1057. pad_right : non-negative integer, optional
  1058. Pad the right side of the string with whitespace until at least that
  1059. many characters are to the right of the decimal point.
  1060. min_digits : non-negative integer or None, optional
  1061. Minimum number of digits to print. Only has an effect if `unique=True`
  1062. in which case additional digits past those necessary to uniquely
  1063. identify the value may be printed, rounding the last additional digit.
  1064. .. versionadded:: 1.21.0
  1065. Returns
  1066. -------
  1067. rep : string
  1068. The string representation of the floating point value
  1069. See Also
  1070. --------
  1071. format_float_scientific
  1072. Examples
  1073. --------
  1074. >>> import numpy as np
  1075. >>> np.format_float_positional(np.float32(np.pi))
  1076. '3.1415927'
  1077. >>> np.format_float_positional(np.float16(np.pi))
  1078. '3.14'
  1079. >>> np.format_float_positional(np.float16(0.3))
  1080. '0.3'
  1081. >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
  1082. '0.3000488281'
  1083. """
  1084. precision = _none_or_positive_arg(precision, 'precision')
  1085. pad_left = _none_or_positive_arg(pad_left, 'pad_left')
  1086. pad_right = _none_or_positive_arg(pad_right, 'pad_right')
  1087. min_digits = _none_or_positive_arg(min_digits, 'min_digits')
  1088. if not fractional and precision == 0:
  1089. raise ValueError("precision must be greater than 0 if "
  1090. "fractional=False")
  1091. if min_digits > 0 and precision > 0 and min_digits > precision:
  1092. raise ValueError("min_digits must be less than or equal to precision")
  1093. return dragon4_positional(x, precision=precision, unique=unique,
  1094. fractional=fractional, trim=trim,
  1095. sign=sign, pad_left=pad_left,
  1096. pad_right=pad_right, min_digits=min_digits)
  1097. class IntegerFormat:
  1098. def __init__(self, data, sign='-'):
  1099. if data.size > 0:
  1100. data_max = np.max(data)
  1101. data_min = np.min(data)
  1102. data_max_str_len = len(str(data_max))
  1103. if sign == ' ' and data_min < 0:
  1104. sign = '-'
  1105. if data_max >= 0 and sign in "+ ":
  1106. data_max_str_len += 1
  1107. max_str_len = max(data_max_str_len,
  1108. len(str(data_min)))
  1109. else:
  1110. max_str_len = 0
  1111. self.format = f'{{:{sign}{max_str_len}d}}'
  1112. def __call__(self, x):
  1113. return self.format.format(x)
  1114. class BoolFormat:
  1115. def __init__(self, data, **kwargs):
  1116. # add an extra space so " True" and "False" have the same length and
  1117. # array elements align nicely when printed, except in 0d arrays
  1118. self.truestr = ' True' if data.shape != () else 'True'
  1119. def __call__(self, x):
  1120. return self.truestr if x else "False"
  1121. class ComplexFloatingFormat:
  1122. """ Formatter for subtypes of np.complexfloating """
  1123. def __init__(self, x, precision, floatmode, suppress_small,
  1124. sign=False, *, legacy=None):
  1125. # for backcompatibility, accept bools
  1126. if isinstance(sign, bool):
  1127. sign = '+' if sign else '-'
  1128. floatmode_real = floatmode_imag = floatmode
  1129. if legacy <= 113:
  1130. floatmode_real = 'maxprec_equal'
  1131. floatmode_imag = 'maxprec'
  1132. self.real_format = FloatingFormat(
  1133. x.real, precision, floatmode_real, suppress_small,
  1134. sign=sign, legacy=legacy
  1135. )
  1136. self.imag_format = FloatingFormat(
  1137. x.imag, precision, floatmode_imag, suppress_small,
  1138. sign='+', legacy=legacy
  1139. )
  1140. def __call__(self, x):
  1141. r = self.real_format(x.real)
  1142. i = self.imag_format(x.imag)
  1143. # add the 'j' before the terminal whitespace in i
  1144. sp = len(i.rstrip())
  1145. i = i[:sp] + 'j' + i[sp:]
  1146. return r + i
  1147. class _TimelikeFormat:
  1148. def __init__(self, data):
  1149. non_nat = data[~isnat(data)]
  1150. if len(non_nat) > 0:
  1151. # Max str length of non-NaT elements
  1152. max_str_len = max(len(self._format_non_nat(np.max(non_nat))),
  1153. len(self._format_non_nat(np.min(non_nat))))
  1154. else:
  1155. max_str_len = 0
  1156. if len(non_nat) < data.size:
  1157. # data contains a NaT
  1158. max_str_len = max(max_str_len, 5)
  1159. self._format = f'%{max_str_len}s'
  1160. self._nat = "'NaT'".rjust(max_str_len)
  1161. def _format_non_nat(self, x):
  1162. # override in subclass
  1163. raise NotImplementedError
  1164. def __call__(self, x):
  1165. if isnat(x):
  1166. return self._nat
  1167. else:
  1168. return self._format % self._format_non_nat(x)
  1169. class DatetimeFormat(_TimelikeFormat):
  1170. def __init__(self, x, unit=None, timezone=None, casting='same_kind',
  1171. legacy=False):
  1172. # Get the unit from the dtype
  1173. if unit is None:
  1174. if x.dtype.kind == 'M':
  1175. unit = datetime_data(x.dtype)[0]
  1176. else:
  1177. unit = 's'
  1178. if timezone is None:
  1179. timezone = 'naive'
  1180. self.timezone = timezone
  1181. self.unit = unit
  1182. self.casting = casting
  1183. self.legacy = legacy
  1184. # must be called after the above are configured
  1185. super().__init__(x)
  1186. def __call__(self, x):
  1187. if self.legacy <= 113:
  1188. return self._format_non_nat(x)
  1189. return super().__call__(x)
  1190. def _format_non_nat(self, x):
  1191. return "'%s'" % datetime_as_string(x,
  1192. unit=self.unit,
  1193. timezone=self.timezone,
  1194. casting=self.casting)
  1195. class TimedeltaFormat(_TimelikeFormat):
  1196. def _format_non_nat(self, x):
  1197. return str(x.astype('i8'))
  1198. class SubArrayFormat:
  1199. def __init__(self, format_function, **options):
  1200. self.format_function = format_function
  1201. self.threshold = options['threshold']
  1202. self.edge_items = options['edgeitems']
  1203. def __call__(self, a):
  1204. self.summary_insert = "..." if a.size > self.threshold else ""
  1205. return self.format_array(a)
  1206. def format_array(self, a):
  1207. if np.ndim(a) == 0:
  1208. return self.format_function(a)
  1209. if self.summary_insert and a.shape[0] > 2 * self.edge_items:
  1210. formatted = (
  1211. [self.format_array(a_) for a_ in a[:self.edge_items]]
  1212. + [self.summary_insert]
  1213. + [self.format_array(a_) for a_ in a[-self.edge_items:]]
  1214. )
  1215. else:
  1216. formatted = [self.format_array(a_) for a_ in a]
  1217. return "[" + ", ".join(formatted) + "]"
  1218. class StructuredVoidFormat:
  1219. """
  1220. Formatter for structured np.void objects.
  1221. This does not work on structured alias types like
  1222. np.dtype(('i4', 'i2,i2')), as alias scalars lose their field information,
  1223. and the implementation relies upon np.void.__getitem__.
  1224. """
  1225. def __init__(self, format_functions):
  1226. self.format_functions = format_functions
  1227. @classmethod
  1228. def from_data(cls, data, **options):
  1229. """
  1230. This is a second way to initialize StructuredVoidFormat,
  1231. using the raw data as input. Added to avoid changing
  1232. the signature of __init__.
  1233. """
  1234. format_functions = []
  1235. for field_name in data.dtype.names:
  1236. format_function = _get_format_function(data[field_name], **options)
  1237. if data.dtype[field_name].shape != ():
  1238. format_function = SubArrayFormat(format_function, **options)
  1239. format_functions.append(format_function)
  1240. return cls(format_functions)
  1241. def __call__(self, x):
  1242. str_fields = [
  1243. format_function(field)
  1244. for field, format_function in zip(x, self.format_functions)
  1245. ]
  1246. if len(str_fields) == 1:
  1247. return f"({str_fields[0]},)"
  1248. else:
  1249. return f"({', '.join(str_fields)})"
  1250. def _void_scalar_to_string(x, is_repr=True):
  1251. """
  1252. Implements the repr for structured-void scalars. It is called from the
  1253. scalartypes.c.src code, and is placed here because it uses the elementwise
  1254. formatters defined above.
  1255. """
  1256. options = format_options.get().copy()
  1257. if options["legacy"] <= 125:
  1258. return StructuredVoidFormat.from_data(array(x), **options)(x)
  1259. if options.get('formatter') is None:
  1260. options['formatter'] = {}
  1261. options['formatter'].setdefault('float_kind', str)
  1262. val_repr = StructuredVoidFormat.from_data(array(x), **options)(x)
  1263. if not is_repr:
  1264. return val_repr
  1265. cls = type(x)
  1266. cls_fqn = cls.__module__.replace("numpy", "np") + "." + cls.__name__
  1267. void_dtype = np.dtype((np.void, x.dtype))
  1268. return f"{cls_fqn}({val_repr}, dtype={void_dtype!s})"
  1269. _typelessdata = [int_, float64, complex128, _nt.bool]
  1270. def dtype_is_implied(dtype):
  1271. """
  1272. Determine if the given dtype is implied by the representation
  1273. of its values.
  1274. Parameters
  1275. ----------
  1276. dtype : dtype
  1277. Data type
  1278. Returns
  1279. -------
  1280. implied : bool
  1281. True if the dtype is implied by the representation of its values.
  1282. Examples
  1283. --------
  1284. >>> import numpy as np
  1285. >>> np._core.arrayprint.dtype_is_implied(int)
  1286. True
  1287. >>> np.array([1, 2, 3], int)
  1288. array([1, 2, 3])
  1289. >>> np._core.arrayprint.dtype_is_implied(np.int8)
  1290. False
  1291. >>> np.array([1, 2, 3], np.int8)
  1292. array([1, 2, 3], dtype=int8)
  1293. """
  1294. dtype = np.dtype(dtype)
  1295. if format_options.get()['legacy'] <= 113 and dtype.type == np.bool:
  1296. return False
  1297. # not just void types can be structured, and names are not part of the repr
  1298. if dtype.names is not None:
  1299. return False
  1300. # should care about endianness *unless size is 1* (e.g., int8, bool)
  1301. if not dtype.isnative:
  1302. return False
  1303. return dtype.type in _typelessdata
  1304. def dtype_short_repr(dtype):
  1305. """
  1306. Convert a dtype to a short form which evaluates to the same dtype.
  1307. The intent is roughly that the following holds
  1308. >>> from numpy import *
  1309. >>> dt = np.int64([1, 2]).dtype
  1310. >>> assert eval(dtype_short_repr(dt)) == dt
  1311. """
  1312. if type(dtype).__repr__ != np.dtype.__repr__:
  1313. # TODO: Custom repr for user DTypes, logic should likely move.
  1314. return repr(dtype)
  1315. if dtype.names is not None:
  1316. # structured dtypes give a list or tuple repr
  1317. return str(dtype)
  1318. elif issubclass(dtype.type, flexible):
  1319. # handle these separately so they don't give garbage like str256
  1320. return f"'{str(dtype)}'"
  1321. typename = dtype.name
  1322. if not dtype.isnative:
  1323. # deal with cases like dtype('<u2') that are identical to an
  1324. # established dtype (in this case uint16)
  1325. # except that they have a different endianness.
  1326. return f"'{str(dtype)}'"
  1327. # quote typenames which can't be represented as python variable names
  1328. if typename and not (typename[0].isalpha() and typename.isalnum()):
  1329. typename = repr(typename)
  1330. return typename
  1331. def _array_repr_implementation(
  1332. arr, max_line_width=None, precision=None, suppress_small=None,
  1333. array2string=array2string):
  1334. """Internal version of array_repr() that allows overriding array2string."""
  1335. current_options = format_options.get()
  1336. override_repr = current_options["override_repr"]
  1337. if override_repr is not None:
  1338. return override_repr(arr)
  1339. if max_line_width is None:
  1340. max_line_width = current_options['linewidth']
  1341. if type(arr) is not ndarray:
  1342. class_name = type(arr).__name__
  1343. else:
  1344. class_name = "array"
  1345. prefix = class_name + "("
  1346. if (current_options['legacy'] <= 113 and
  1347. arr.shape == () and not arr.dtype.names):
  1348. lst = repr(arr.item())
  1349. else:
  1350. lst = array2string(arr, max_line_width, precision, suppress_small,
  1351. ', ', prefix, suffix=")")
  1352. # Add dtype and shape information if these cannot be inferred from
  1353. # the array string.
  1354. extras = []
  1355. if ((arr.size == 0 and arr.shape != (0,))
  1356. or (current_options['legacy'] > 210
  1357. and arr.size > current_options['threshold'])):
  1358. extras.append(f"shape={arr.shape}")
  1359. if not dtype_is_implied(arr.dtype) or arr.size == 0:
  1360. extras.append(f"dtype={dtype_short_repr(arr.dtype)}")
  1361. if not extras:
  1362. return prefix + lst + ")"
  1363. arr_str = prefix + lst + ","
  1364. extra_str = ", ".join(extras) + ")"
  1365. # compute whether we should put extras on a new line: Do so if adding the
  1366. # extras would extend the last line past max_line_width.
  1367. # Note: This line gives the correct result even when rfind returns -1.
  1368. last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1)
  1369. spacer = " "
  1370. if current_options['legacy'] <= 113:
  1371. if issubclass(arr.dtype.type, flexible):
  1372. spacer = '\n' + ' ' * len(prefix)
  1373. elif last_line_len + len(extra_str) + 1 > max_line_width:
  1374. spacer = '\n' + ' ' * len(prefix)
  1375. return arr_str + spacer + extra_str
  1376. def _array_repr_dispatcher(
  1377. arr, max_line_width=None, precision=None, suppress_small=None):
  1378. return (arr,)
  1379. @array_function_dispatch(_array_repr_dispatcher, module='numpy')
  1380. def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
  1381. """
  1382. Return the string representation of an array.
  1383. Parameters
  1384. ----------
  1385. arr : ndarray
  1386. Input array.
  1387. max_line_width : int, optional
  1388. Inserts newlines if text is longer than `max_line_width`.
  1389. Defaults to ``numpy.get_printoptions()['linewidth']``.
  1390. precision : int, optional
  1391. Floating point precision.
  1392. Defaults to ``numpy.get_printoptions()['precision']``.
  1393. suppress_small : bool, optional
  1394. Represent numbers "very close" to zero as zero; default is False.
  1395. Very close is defined by precision: if the precision is 8, e.g.,
  1396. numbers smaller (in absolute value) than 5e-9 are represented as
  1397. zero.
  1398. Defaults to ``numpy.get_printoptions()['suppress']``.
  1399. Returns
  1400. -------
  1401. string : str
  1402. The string representation of an array.
  1403. See Also
  1404. --------
  1405. array_str, array2string, set_printoptions
  1406. Examples
  1407. --------
  1408. >>> import numpy as np
  1409. >>> np.array_repr(np.array([1,2]))
  1410. 'array([1, 2])'
  1411. >>> np.array_repr(np.ma.array([0.]))
  1412. 'MaskedArray([0.])'
  1413. >>> np.array_repr(np.array([], np.int32))
  1414. 'array([], dtype=int32)'
  1415. >>> x = np.array([1e-6, 4e-7, 2, 3])
  1416. >>> np.array_repr(x, precision=6, suppress_small=True)
  1417. 'array([0.000001, 0. , 2. , 3. ])'
  1418. """
  1419. return _array_repr_implementation(
  1420. arr, max_line_width, precision, suppress_small)
  1421. @_recursive_guard()
  1422. def _guarded_repr_or_str(v):
  1423. if isinstance(v, bytes):
  1424. return repr(v)
  1425. return str(v)
  1426. def _array_str_implementation(
  1427. a, max_line_width=None, precision=None, suppress_small=None,
  1428. array2string=array2string):
  1429. """Internal version of array_str() that allows overriding array2string."""
  1430. if (format_options.get()['legacy'] <= 113 and
  1431. a.shape == () and not a.dtype.names):
  1432. return str(a.item())
  1433. # the str of 0d arrays is a special case: It should appear like a scalar,
  1434. # so floats are not truncated by `precision`, and strings are not wrapped
  1435. # in quotes. So we return the str of the scalar value.
  1436. if a.shape == ():
  1437. # obtain a scalar and call str on it, avoiding problems for subclasses
  1438. # for which indexing with () returns a 0d instead of a scalar by using
  1439. # ndarray's getindex. Also guard against recursive 0d object arrays.
  1440. return _guarded_repr_or_str(np.ndarray.__getitem__(a, ()))
  1441. return array2string(a, max_line_width, precision, suppress_small, ' ', "")
  1442. def _array_str_dispatcher(
  1443. a, max_line_width=None, precision=None, suppress_small=None):
  1444. return (a,)
  1445. @array_function_dispatch(_array_str_dispatcher, module='numpy')
  1446. def array_str(a, max_line_width=None, precision=None, suppress_small=None):
  1447. """
  1448. Return a string representation of the data in an array.
  1449. The data in the array is returned as a single string. This function is
  1450. similar to `array_repr`, the difference being that `array_repr` also
  1451. returns information on the kind of array and its data type.
  1452. Parameters
  1453. ----------
  1454. a : ndarray
  1455. Input array.
  1456. max_line_width : int, optional
  1457. Inserts newlines if text is longer than `max_line_width`.
  1458. Defaults to ``numpy.get_printoptions()['linewidth']``.
  1459. precision : int, optional
  1460. Floating point precision.
  1461. Defaults to ``numpy.get_printoptions()['precision']``.
  1462. suppress_small : bool, optional
  1463. Represent numbers "very close" to zero as zero; default is False.
  1464. Very close is defined by precision: if the precision is 8, e.g.,
  1465. numbers smaller (in absolute value) than 5e-9 are represented as
  1466. zero.
  1467. Defaults to ``numpy.get_printoptions()['suppress']``.
  1468. See Also
  1469. --------
  1470. array2string, array_repr, set_printoptions
  1471. Examples
  1472. --------
  1473. >>> import numpy as np
  1474. >>> np.array_str(np.arange(3))
  1475. '[0 1 2]'
  1476. """
  1477. return _array_str_implementation(
  1478. a, max_line_width, precision, suppress_small)
  1479. # needed if __array_function__ is disabled
  1480. _array2string_impl = getattr(array2string, '__wrapped__', array2string)
  1481. _default_array_str = functools.partial(_array_str_implementation,
  1482. array2string=_array2string_impl)
  1483. _default_array_repr = functools.partial(_array_repr_implementation,
  1484. array2string=_array2string_impl)