arrayprint.py 58 KB

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