arrayprint.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  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. # 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 _extendLine_pretty(s, line, word, line_width, next_line_prefix, legacy):
  593. """
  594. Extends line with nicely formatted (possibly multi-line) string ``word``.
  595. """
  596. words = word.splitlines()
  597. if len(words) == 1 or legacy == '1.13':
  598. return _extendLine(s, line, word, line_width, next_line_prefix, legacy)
  599. max_word_length = max(len(word) for word in words)
  600. if (len(line) + max_word_length > line_width and
  601. len(line) > len(next_line_prefix)):
  602. s += line.rstrip() + '\n'
  603. line = next_line_prefix + words[0]
  604. indent = next_line_prefix
  605. else:
  606. indent = len(line)*' '
  607. line += words[0]
  608. for word in words[1::]:
  609. s += line.rstrip() + '\n'
  610. line = indent + word
  611. suffix_length = max_word_length - len(words[-1])
  612. line += suffix_length*' '
  613. return s, line
  614. def _formatArray(a, format_function, line_width, next_line_prefix,
  615. separator, edge_items, summary_insert, legacy):
  616. """formatArray is designed for two modes of operation:
  617. 1. Full output
  618. 2. Summarized output
  619. """
  620. def recurser(index, hanging_indent, curr_width):
  621. """
  622. By using this local function, we don't need to recurse with all the
  623. arguments. Since this function is not created recursively, the cost is
  624. not significant
  625. """
  626. axis = len(index)
  627. axes_left = a.ndim - axis
  628. if axes_left == 0:
  629. return format_function(a[index])
  630. # when recursing, add a space to align with the [ added, and reduce the
  631. # length of the line by 1
  632. next_hanging_indent = hanging_indent + ' '
  633. if legacy == '1.13':
  634. next_width = curr_width
  635. else:
  636. next_width = curr_width - len(']')
  637. a_len = a.shape[axis]
  638. show_summary = summary_insert and 2*edge_items < a_len
  639. if show_summary:
  640. leading_items = edge_items
  641. trailing_items = edge_items
  642. else:
  643. leading_items = 0
  644. trailing_items = a_len
  645. # stringify the array with the hanging indent on the first line too
  646. s = ''
  647. # last axis (rows) - wrap elements if they would not fit on one line
  648. if axes_left == 1:
  649. # the length up until the beginning of the separator / bracket
  650. if legacy == '1.13':
  651. elem_width = curr_width - len(separator.rstrip())
  652. else:
  653. elem_width = curr_width - max(len(separator.rstrip()), len(']'))
  654. line = hanging_indent
  655. for i in range(leading_items):
  656. word = recurser(index + (i,), next_hanging_indent, next_width)
  657. s, line = _extendLine_pretty(
  658. s, line, word, elem_width, hanging_indent, legacy)
  659. line += separator
  660. if show_summary:
  661. s, line = _extendLine(
  662. s, line, summary_insert, elem_width, hanging_indent, legacy)
  663. if legacy == '1.13':
  664. line += ", "
  665. else:
  666. line += separator
  667. for i in range(trailing_items, 1, -1):
  668. word = recurser(index + (-i,), next_hanging_indent, next_width)
  669. s, line = _extendLine_pretty(
  670. s, line, word, elem_width, hanging_indent, legacy)
  671. line += separator
  672. if legacy == '1.13':
  673. # width of the separator is not considered on 1.13
  674. elem_width = curr_width
  675. word = recurser(index + (-1,), next_hanging_indent, next_width)
  676. s, line = _extendLine_pretty(
  677. s, line, word, elem_width, hanging_indent, legacy)
  678. s += line
  679. # other axes - insert newlines between rows
  680. else:
  681. s = ''
  682. line_sep = separator.rstrip() + '\n'*(axes_left - 1)
  683. for i in range(leading_items):
  684. nested = recurser(index + (i,), next_hanging_indent, next_width)
  685. s += hanging_indent + nested + line_sep
  686. if show_summary:
  687. if legacy == '1.13':
  688. # trailing space, fixed nbr of newlines, and fixed separator
  689. s += hanging_indent + summary_insert + ", \n"
  690. else:
  691. s += hanging_indent + summary_insert + line_sep
  692. for i in range(trailing_items, 1, -1):
  693. nested = recurser(index + (-i,), next_hanging_indent,
  694. next_width)
  695. s += hanging_indent + nested + line_sep
  696. nested = recurser(index + (-1,), next_hanging_indent, next_width)
  697. s += hanging_indent + nested
  698. # remove the hanging indent, and wrap in []
  699. s = '[' + s[len(hanging_indent):] + ']'
  700. return s
  701. try:
  702. # invoke the recursive part with an initial index and prefix
  703. return recurser(index=(),
  704. hanging_indent=next_line_prefix,
  705. curr_width=line_width)
  706. finally:
  707. # recursive closures have a cyclic reference to themselves, which
  708. # requires gc to collect (gh-10620). To avoid this problem, for
  709. # performance and PyPy friendliness, we break the cycle:
  710. recurser = None
  711. def _none_or_positive_arg(x, name):
  712. if x is None:
  713. return -1
  714. if x < 0:
  715. raise ValueError("{} must be >= 0".format(name))
  716. return x
  717. class FloatingFormat:
  718. """ Formatter for subtypes of np.floating """
  719. def __init__(self, data, precision, floatmode, suppress_small, sign=False,
  720. *, legacy=None):
  721. # for backcompatibility, accept bools
  722. if isinstance(sign, bool):
  723. sign = '+' if sign else '-'
  724. self._legacy = legacy
  725. if self._legacy == '1.13':
  726. # when not 0d, legacy does not support '-'
  727. if data.shape != () and sign == '-':
  728. sign = ' '
  729. self.floatmode = floatmode
  730. if floatmode == 'unique':
  731. self.precision = None
  732. else:
  733. self.precision = precision
  734. self.precision = _none_or_positive_arg(self.precision, 'precision')
  735. self.suppress_small = suppress_small
  736. self.sign = sign
  737. self.exp_format = False
  738. self.large_exponent = False
  739. self.fillFormat(data)
  740. def fillFormat(self, data):
  741. # only the finite values are used to compute the number of digits
  742. finite_vals = data[isfinite(data)]
  743. # choose exponential mode based on the non-zero finite values:
  744. abs_non_zero = absolute(finite_vals[finite_vals != 0])
  745. if len(abs_non_zero) != 0:
  746. max_val = np.max(abs_non_zero)
  747. min_val = np.min(abs_non_zero)
  748. with errstate(over='ignore'): # division can overflow
  749. if max_val >= 1.e8 or (not self.suppress_small and
  750. (min_val < 0.0001 or max_val/min_val > 1000.)):
  751. self.exp_format = True
  752. # do a first pass of printing all the numbers, to determine sizes
  753. if len(finite_vals) == 0:
  754. self.pad_left = 0
  755. self.pad_right = 0
  756. self.trim = '.'
  757. self.exp_size = -1
  758. self.unique = True
  759. elif self.exp_format:
  760. trim, unique = '.', True
  761. if self.floatmode == 'fixed' or self._legacy == '1.13':
  762. trim, unique = 'k', False
  763. strs = (dragon4_scientific(x, precision=self.precision,
  764. unique=unique, trim=trim, sign=self.sign == '+')
  765. for x in finite_vals)
  766. frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs))
  767. int_part, frac_part = zip(*(s.split('.') for s in frac_strs))
  768. self.exp_size = max(len(s) for s in exp_strs) - 1
  769. self.trim = 'k'
  770. self.precision = max(len(s) for s in frac_part)
  771. # for back-compat with np 1.13, use 2 spaces & sign and full prec
  772. if self._legacy == '1.13':
  773. self.pad_left = 3
  774. else:
  775. # this should be only 1 or 2. Can be calculated from sign.
  776. self.pad_left = max(len(s) for s in int_part)
  777. # pad_right is only needed for nan length calculation
  778. self.pad_right = self.exp_size + 2 + self.precision
  779. self.unique = False
  780. else:
  781. # first pass printing to determine sizes
  782. trim, unique = '.', True
  783. if self.floatmode == 'fixed':
  784. trim, unique = 'k', False
  785. strs = (dragon4_positional(x, precision=self.precision,
  786. fractional=True,
  787. unique=unique, trim=trim,
  788. sign=self.sign == '+')
  789. for x in finite_vals)
  790. int_part, frac_part = zip(*(s.split('.') for s in strs))
  791. if self._legacy == '1.13':
  792. self.pad_left = 1 + max(len(s.lstrip('-+')) for s in int_part)
  793. else:
  794. self.pad_left = max(len(s) for s in int_part)
  795. self.pad_right = max(len(s) for s in frac_part)
  796. self.exp_size = -1
  797. if self.floatmode in ['fixed', 'maxprec_equal']:
  798. self.precision = self.pad_right
  799. self.unique = False
  800. self.trim = 'k'
  801. else:
  802. self.unique = True
  803. self.trim = '.'
  804. if self._legacy != '1.13':
  805. # account for sign = ' ' by adding one to pad_left
  806. if self.sign == ' ' and not any(np.signbit(finite_vals)):
  807. self.pad_left += 1
  808. # if there are non-finite values, may need to increase pad_left
  809. if data.size != finite_vals.size:
  810. neginf = self.sign != '-' or any(data[isinf(data)] < 0)
  811. nanlen = len(_format_options['nanstr'])
  812. inflen = len(_format_options['infstr']) + neginf
  813. offset = self.pad_right + 1 # +1 for decimal pt
  814. self.pad_left = max(self.pad_left, nanlen - offset, inflen - offset)
  815. def __call__(self, x):
  816. if not np.isfinite(x):
  817. with errstate(invalid='ignore'):
  818. if np.isnan(x):
  819. sign = '+' if self.sign == '+' else ''
  820. ret = sign + _format_options['nanstr']
  821. else: # isinf
  822. sign = '-' if x < 0 else '+' if self.sign == '+' else ''
  823. ret = sign + _format_options['infstr']
  824. return ' '*(self.pad_left + self.pad_right + 1 - len(ret)) + ret
  825. if self.exp_format:
  826. return dragon4_scientific(x,
  827. precision=self.precision,
  828. unique=self.unique,
  829. trim=self.trim,
  830. sign=self.sign == '+',
  831. pad_left=self.pad_left,
  832. exp_digits=self.exp_size)
  833. else:
  834. return dragon4_positional(x,
  835. precision=self.precision,
  836. unique=self.unique,
  837. fractional=True,
  838. trim=self.trim,
  839. sign=self.sign == '+',
  840. pad_left=self.pad_left,
  841. pad_right=self.pad_right)
  842. @set_module('numpy')
  843. def format_float_scientific(x, precision=None, unique=True, trim='k',
  844. sign=False, pad_left=None, exp_digits=None):
  845. """
  846. Format a floating-point scalar as a decimal string in scientific notation.
  847. Provides control over rounding, trimming and padding. Uses and assumes
  848. IEEE unbiased rounding. Uses the "Dragon4" algorithm.
  849. Parameters
  850. ----------
  851. x : python float or numpy floating scalar
  852. Value to format.
  853. precision : non-negative integer or None, optional
  854. Maximum number of digits to print. May be None if `unique` is
  855. `True`, but must be an integer if unique is `False`.
  856. unique : boolean, optional
  857. If `True`, use a digit-generation strategy which gives the shortest
  858. representation which uniquely identifies the floating-point number from
  859. other values of the same type, by judicious rounding. If `precision`
  860. was omitted, print all necessary digits, otherwise digit generation is
  861. cut off after `precision` digits and the remaining value is rounded.
  862. If `False`, digits are generated as if printing an infinite-precision
  863. value and stopping after `precision` digits, rounding the remaining
  864. value.
  865. trim : one of 'k', '.', '0', '-', optional
  866. Controls post-processing trimming of trailing digits, as follows:
  867. * 'k' : keep trailing zeros, keep decimal point (no trimming)
  868. * '.' : trim all trailing zeros, leave decimal point
  869. * '0' : trim all but the zero before the decimal point. Insert the
  870. zero if it is missing.
  871. * '-' : trim trailing zeros and any trailing decimal point
  872. sign : boolean, optional
  873. Whether to show the sign for positive values.
  874. pad_left : non-negative integer, optional
  875. Pad the left side of the string with whitespace until at least that
  876. many characters are to the left of the decimal point.
  877. exp_digits : non-negative integer, optional
  878. Pad the exponent with zeros until it contains at least this many digits.
  879. If omitted, the exponent will be at least 2 digits.
  880. Returns
  881. -------
  882. rep : string
  883. The string representation of the floating point value
  884. See Also
  885. --------
  886. format_float_positional
  887. Examples
  888. --------
  889. >>> np.format_float_scientific(np.float32(np.pi))
  890. '3.1415927e+00'
  891. >>> s = np.float32(1.23e24)
  892. >>> np.format_float_scientific(s, unique=False, precision=15)
  893. '1.230000071797338e+24'
  894. >>> np.format_float_scientific(s, exp_digits=4)
  895. '1.23e+0024'
  896. """
  897. precision = _none_or_positive_arg(precision, 'precision')
  898. pad_left = _none_or_positive_arg(pad_left, 'pad_left')
  899. exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits')
  900. return dragon4_scientific(x, precision=precision, unique=unique,
  901. trim=trim, sign=sign, pad_left=pad_left,
  902. exp_digits=exp_digits)
  903. @set_module('numpy')
  904. def format_float_positional(x, precision=None, unique=True,
  905. fractional=True, trim='k', sign=False,
  906. pad_left=None, pad_right=None):
  907. """
  908. Format a floating-point scalar as a decimal string in positional notation.
  909. Provides control over rounding, trimming and padding. Uses and assumes
  910. IEEE unbiased rounding. Uses the "Dragon4" algorithm.
  911. Parameters
  912. ----------
  913. x : python float or numpy floating scalar
  914. Value to format.
  915. precision : non-negative integer or None, optional
  916. Maximum number of digits to print. May be None if `unique` is
  917. `True`, but must be an integer if unique is `False`.
  918. unique : boolean, optional
  919. If `True`, use a digit-generation strategy which gives the shortest
  920. representation which uniquely identifies the floating-point number from
  921. other values of the same type, by judicious rounding. If `precision`
  922. was omitted, print out all necessary digits, otherwise digit generation
  923. is cut off after `precision` digits and the remaining value is rounded.
  924. If `False`, digits are generated as if printing an infinite-precision
  925. value and stopping after `precision` digits, rounding the remaining
  926. value.
  927. fractional : boolean, optional
  928. If `True`, the cutoff of `precision` digits refers to the total number
  929. of digits after the decimal point, including leading zeros.
  930. If `False`, `precision` refers to the total number of significant
  931. digits, before or after the decimal point, ignoring leading zeros.
  932. trim : one of 'k', '.', '0', '-', optional
  933. Controls post-processing trimming of trailing digits, as follows:
  934. * 'k' : keep trailing zeros, keep decimal point (no trimming)
  935. * '.' : trim all trailing zeros, leave decimal point
  936. * '0' : trim all but the zero before the decimal point. Insert the
  937. zero if it is missing.
  938. * '-' : trim trailing zeros and any trailing decimal point
  939. sign : boolean, optional
  940. Whether to show the sign for positive values.
  941. pad_left : non-negative integer, optional
  942. Pad the left side of the string with whitespace until at least that
  943. many characters are to the left of the decimal point.
  944. pad_right : non-negative integer, optional
  945. Pad the right side of the string with whitespace until at least that
  946. many characters are to the right of the decimal point.
  947. Returns
  948. -------
  949. rep : string
  950. The string representation of the floating point value
  951. See Also
  952. --------
  953. format_float_scientific
  954. Examples
  955. --------
  956. >>> np.format_float_positional(np.float32(np.pi))
  957. '3.1415927'
  958. >>> np.format_float_positional(np.float16(np.pi))
  959. '3.14'
  960. >>> np.format_float_positional(np.float16(0.3))
  961. '0.3'
  962. >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
  963. '0.3000488281'
  964. """
  965. precision = _none_or_positive_arg(precision, 'precision')
  966. pad_left = _none_or_positive_arg(pad_left, 'pad_left')
  967. pad_right = _none_or_positive_arg(pad_right, 'pad_right')
  968. return dragon4_positional(x, precision=precision, unique=unique,
  969. fractional=fractional, trim=trim,
  970. sign=sign, pad_left=pad_left,
  971. pad_right=pad_right)
  972. class IntegerFormat:
  973. def __init__(self, data):
  974. if data.size > 0:
  975. max_str_len = max(len(str(np.max(data))),
  976. len(str(np.min(data))))
  977. else:
  978. max_str_len = 0
  979. self.format = '%{}d'.format(max_str_len)
  980. def __call__(self, x):
  981. return self.format % x
  982. class BoolFormat:
  983. def __init__(self, data, **kwargs):
  984. # add an extra space so " True" and "False" have the same length and
  985. # array elements align nicely when printed, except in 0d arrays
  986. self.truestr = ' True' if data.shape != () else 'True'
  987. def __call__(self, x):
  988. return self.truestr if x else "False"
  989. class ComplexFloatingFormat:
  990. """ Formatter for subtypes of np.complexfloating """
  991. def __init__(self, x, precision, floatmode, suppress_small,
  992. sign=False, *, legacy=None):
  993. # for backcompatibility, accept bools
  994. if isinstance(sign, bool):
  995. sign = '+' if sign else '-'
  996. floatmode_real = floatmode_imag = floatmode
  997. if legacy == '1.13':
  998. floatmode_real = 'maxprec_equal'
  999. floatmode_imag = 'maxprec'
  1000. self.real_format = FloatingFormat(
  1001. x.real, precision, floatmode_real, suppress_small,
  1002. sign=sign, legacy=legacy
  1003. )
  1004. self.imag_format = FloatingFormat(
  1005. x.imag, precision, floatmode_imag, suppress_small,
  1006. sign='+', legacy=legacy
  1007. )
  1008. def __call__(self, x):
  1009. r = self.real_format(x.real)
  1010. i = self.imag_format(x.imag)
  1011. # add the 'j' before the terminal whitespace in i
  1012. sp = len(i.rstrip())
  1013. i = i[:sp] + 'j' + i[sp:]
  1014. return r + i
  1015. class _TimelikeFormat:
  1016. def __init__(self, data):
  1017. non_nat = data[~isnat(data)]
  1018. if len(non_nat) > 0:
  1019. # Max str length of non-NaT elements
  1020. max_str_len = max(len(self._format_non_nat(np.max(non_nat))),
  1021. len(self._format_non_nat(np.min(non_nat))))
  1022. else:
  1023. max_str_len = 0
  1024. if len(non_nat) < data.size:
  1025. # data contains a NaT
  1026. max_str_len = max(max_str_len, 5)
  1027. self._format = '%{}s'.format(max_str_len)
  1028. self._nat = "'NaT'".rjust(max_str_len)
  1029. def _format_non_nat(self, x):
  1030. # override in subclass
  1031. raise NotImplementedError
  1032. def __call__(self, x):
  1033. if isnat(x):
  1034. return self._nat
  1035. else:
  1036. return self._format % self._format_non_nat(x)
  1037. class DatetimeFormat(_TimelikeFormat):
  1038. def __init__(self, x, unit=None, timezone=None, casting='same_kind',
  1039. legacy=False):
  1040. # Get the unit from the dtype
  1041. if unit is None:
  1042. if x.dtype.kind == 'M':
  1043. unit = datetime_data(x.dtype)[0]
  1044. else:
  1045. unit = 's'
  1046. if timezone is None:
  1047. timezone = 'naive'
  1048. self.timezone = timezone
  1049. self.unit = unit
  1050. self.casting = casting
  1051. self.legacy = legacy
  1052. # must be called after the above are configured
  1053. super(DatetimeFormat, self).__init__(x)
  1054. def __call__(self, x):
  1055. if self.legacy == '1.13':
  1056. return self._format_non_nat(x)
  1057. return super(DatetimeFormat, self).__call__(x)
  1058. def _format_non_nat(self, x):
  1059. return "'%s'" % datetime_as_string(x,
  1060. unit=self.unit,
  1061. timezone=self.timezone,
  1062. casting=self.casting)
  1063. class TimedeltaFormat(_TimelikeFormat):
  1064. def _format_non_nat(self, x):
  1065. return str(x.astype('i8'))
  1066. class SubArrayFormat:
  1067. def __init__(self, format_function):
  1068. self.format_function = format_function
  1069. def __call__(self, arr):
  1070. if arr.ndim <= 1:
  1071. return "[" + ", ".join(self.format_function(a) for a in arr) + "]"
  1072. return "[" + ", ".join(self.__call__(a) for a in arr) + "]"
  1073. class StructuredVoidFormat:
  1074. """
  1075. Formatter for structured np.void objects.
  1076. This does not work on structured alias types like np.dtype(('i4', 'i2,i2')),
  1077. as alias scalars lose their field information, and the implementation
  1078. relies upon np.void.__getitem__.
  1079. """
  1080. def __init__(self, format_functions):
  1081. self.format_functions = format_functions
  1082. @classmethod
  1083. def from_data(cls, data, **options):
  1084. """
  1085. This is a second way to initialize StructuredVoidFormat, using the raw data
  1086. as input. Added to avoid changing the signature of __init__.
  1087. """
  1088. format_functions = []
  1089. for field_name in data.dtype.names:
  1090. format_function = _get_format_function(data[field_name], **options)
  1091. if data.dtype[field_name].shape != ():
  1092. format_function = SubArrayFormat(format_function)
  1093. format_functions.append(format_function)
  1094. return cls(format_functions)
  1095. def __call__(self, x):
  1096. str_fields = [
  1097. format_function(field)
  1098. for field, format_function in zip(x, self.format_functions)
  1099. ]
  1100. if len(str_fields) == 1:
  1101. return "({},)".format(str_fields[0])
  1102. else:
  1103. return "({})".format(", ".join(str_fields))
  1104. def _void_scalar_repr(x):
  1105. """
  1106. Implements the repr for structured-void scalars. It is called from the
  1107. scalartypes.c.src code, and is placed here because it uses the elementwise
  1108. formatters defined above.
  1109. """
  1110. return StructuredVoidFormat.from_data(array(x), **_format_options)(x)
  1111. _typelessdata = [int_, float_, complex_, bool_]
  1112. if issubclass(intc, int):
  1113. _typelessdata.append(intc)
  1114. if issubclass(longlong, int):
  1115. _typelessdata.append(longlong)
  1116. def dtype_is_implied(dtype):
  1117. """
  1118. Determine if the given dtype is implied by the representation of its values.
  1119. Parameters
  1120. ----------
  1121. dtype : dtype
  1122. Data type
  1123. Returns
  1124. -------
  1125. implied : bool
  1126. True if the dtype is implied by the representation of its values.
  1127. Examples
  1128. --------
  1129. >>> np.core.arrayprint.dtype_is_implied(int)
  1130. True
  1131. >>> np.array([1, 2, 3], int)
  1132. array([1, 2, 3])
  1133. >>> np.core.arrayprint.dtype_is_implied(np.int8)
  1134. False
  1135. >>> np.array([1, 2, 3], np.int8)
  1136. array([1, 2, 3], dtype=int8)
  1137. """
  1138. dtype = np.dtype(dtype)
  1139. if _format_options['legacy'] == '1.13' and dtype.type == bool_:
  1140. return False
  1141. # not just void types can be structured, and names are not part of the repr
  1142. if dtype.names is not None:
  1143. return False
  1144. return dtype.type in _typelessdata
  1145. def dtype_short_repr(dtype):
  1146. """
  1147. Convert a dtype to a short form which evaluates to the same dtype.
  1148. The intent is roughly that the following holds
  1149. >>> from numpy import *
  1150. >>> dt = np.int64([1, 2]).dtype
  1151. >>> assert eval(dtype_short_repr(dt)) == dt
  1152. """
  1153. if dtype.names is not None:
  1154. # structured dtypes give a list or tuple repr
  1155. return str(dtype)
  1156. elif issubclass(dtype.type, flexible):
  1157. # handle these separately so they don't give garbage like str256
  1158. return "'%s'" % str(dtype)
  1159. typename = dtype.name
  1160. # quote typenames which can't be represented as python variable names
  1161. if typename and not (typename[0].isalpha() and typename.isalnum()):
  1162. typename = repr(typename)
  1163. return typename
  1164. def _array_repr_implementation(
  1165. arr, max_line_width=None, precision=None, suppress_small=None,
  1166. array2string=array2string):
  1167. """Internal version of array_repr() that allows overriding array2string."""
  1168. if max_line_width is None:
  1169. max_line_width = _format_options['linewidth']
  1170. if type(arr) is not ndarray:
  1171. class_name = type(arr).__name__
  1172. else:
  1173. class_name = "array"
  1174. skipdtype = dtype_is_implied(arr.dtype) and arr.size > 0
  1175. prefix = class_name + "("
  1176. suffix = ")" if skipdtype else ","
  1177. if (_format_options['legacy'] == '1.13' and
  1178. arr.shape == () and not arr.dtype.names):
  1179. lst = repr(arr.item())
  1180. elif arr.size > 0 or arr.shape == (0,):
  1181. lst = array2string(arr, max_line_width, precision, suppress_small,
  1182. ', ', prefix, suffix=suffix)
  1183. else: # show zero-length shape unless it is (0,)
  1184. lst = "[], shape=%s" % (repr(arr.shape),)
  1185. arr_str = prefix + lst + suffix
  1186. if skipdtype:
  1187. return arr_str
  1188. dtype_str = "dtype={})".format(dtype_short_repr(arr.dtype))
  1189. # compute whether we should put dtype on a new line: Do so if adding the
  1190. # dtype would extend the last line past max_line_width.
  1191. # Note: This line gives the correct result even when rfind returns -1.
  1192. last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1)
  1193. spacer = " "
  1194. if _format_options['legacy'] == '1.13':
  1195. if issubclass(arr.dtype.type, flexible):
  1196. spacer = '\n' + ' '*len(class_name + "(")
  1197. elif last_line_len + len(dtype_str) + 1 > max_line_width:
  1198. spacer = '\n' + ' '*len(class_name + "(")
  1199. return arr_str + spacer + dtype_str
  1200. def _array_repr_dispatcher(
  1201. arr, max_line_width=None, precision=None, suppress_small=None):
  1202. return (arr,)
  1203. @array_function_dispatch(_array_repr_dispatcher, module='numpy')
  1204. def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
  1205. """
  1206. Return the string representation of an array.
  1207. Parameters
  1208. ----------
  1209. arr : ndarray
  1210. Input array.
  1211. max_line_width : int, optional
  1212. Inserts newlines if text is longer than `max_line_width`.
  1213. Defaults to ``numpy.get_printoptions()['linewidth']``.
  1214. precision : int, optional
  1215. Floating point precision.
  1216. Defaults to ``numpy.get_printoptions()['precision']``.
  1217. suppress_small : bool, optional
  1218. Represent numbers "very close" to zero as zero; default is False.
  1219. Very close is defined by precision: if the precision is 8, e.g.,
  1220. numbers smaller (in absolute value) than 5e-9 are represented as
  1221. zero.
  1222. Defaults to ``numpy.get_printoptions()['suppress']``.
  1223. Returns
  1224. -------
  1225. string : str
  1226. The string representation of an array.
  1227. See Also
  1228. --------
  1229. array_str, array2string, set_printoptions
  1230. Examples
  1231. --------
  1232. >>> np.array_repr(np.array([1,2]))
  1233. 'array([1, 2])'
  1234. >>> np.array_repr(np.ma.array([0.]))
  1235. 'MaskedArray([0.])'
  1236. >>> np.array_repr(np.array([], np.int32))
  1237. 'array([], dtype=int32)'
  1238. >>> x = np.array([1e-6, 4e-7, 2, 3])
  1239. >>> np.array_repr(x, precision=6, suppress_small=True)
  1240. 'array([0.000001, 0. , 2. , 3. ])'
  1241. """
  1242. return _array_repr_implementation(
  1243. arr, max_line_width, precision, suppress_small)
  1244. @_recursive_guard()
  1245. def _guarded_repr_or_str(v):
  1246. if isinstance(v, bytes):
  1247. return repr(v)
  1248. return str(v)
  1249. def _array_str_implementation(
  1250. a, max_line_width=None, precision=None, suppress_small=None,
  1251. array2string=array2string):
  1252. """Internal version of array_str() that allows overriding array2string."""
  1253. if (_format_options['legacy'] == '1.13' and
  1254. a.shape == () and not a.dtype.names):
  1255. return str(a.item())
  1256. # the str of 0d arrays is a special case: It should appear like a scalar,
  1257. # so floats are not truncated by `precision`, and strings are not wrapped
  1258. # in quotes. So we return the str of the scalar value.
  1259. if a.shape == ():
  1260. # obtain a scalar and call str on it, avoiding problems for subclasses
  1261. # for which indexing with () returns a 0d instead of a scalar by using
  1262. # ndarray's getindex. Also guard against recursive 0d object arrays.
  1263. return _guarded_repr_or_str(np.ndarray.__getitem__(a, ()))
  1264. return array2string(a, max_line_width, precision, suppress_small, ' ', "")
  1265. def _array_str_dispatcher(
  1266. a, max_line_width=None, precision=None, suppress_small=None):
  1267. return (a,)
  1268. @array_function_dispatch(_array_str_dispatcher, module='numpy')
  1269. def array_str(a, max_line_width=None, precision=None, suppress_small=None):
  1270. """
  1271. Return a string representation of the data in an array.
  1272. The data in the array is returned as a single string. This function is
  1273. similar to `array_repr`, the difference being that `array_repr` also
  1274. returns information on the kind of array and its data type.
  1275. Parameters
  1276. ----------
  1277. a : ndarray
  1278. Input array.
  1279. max_line_width : int, optional
  1280. Inserts newlines if text is longer than `max_line_width`.
  1281. Defaults to ``numpy.get_printoptions()['linewidth']``.
  1282. precision : int, optional
  1283. Floating point precision.
  1284. Defaults to ``numpy.get_printoptions()['precision']``.
  1285. suppress_small : bool, optional
  1286. Represent numbers "very close" to zero as zero; default is False.
  1287. Very close is defined by precision: if the precision is 8, e.g.,
  1288. numbers smaller (in absolute value) than 5e-9 are represented as
  1289. zero.
  1290. Defaults to ``numpy.get_printoptions()['suppress']``.
  1291. See Also
  1292. --------
  1293. array2string, array_repr, set_printoptions
  1294. Examples
  1295. --------
  1296. >>> np.array_str(np.arange(3))
  1297. '[0 1 2]'
  1298. """
  1299. return _array_str_implementation(
  1300. a, max_line_width, precision, suppress_small)
  1301. # needed if __array_function__ is disabled
  1302. _array2string_impl = getattr(array2string, '__wrapped__', array2string)
  1303. _default_array_str = functools.partial(_array_str_implementation,
  1304. array2string=_array2string_impl)
  1305. _default_array_repr = functools.partial(_array_repr_implementation,
  1306. array2string=_array2string_impl)
  1307. def set_string_function(f, repr=True):
  1308. """
  1309. Set a Python function to be used when pretty printing arrays.
  1310. Parameters
  1311. ----------
  1312. f : function or None
  1313. Function to be used to pretty print arrays. The function should expect
  1314. a single array argument and return a string of the representation of
  1315. the array. If None, the function is reset to the default NumPy function
  1316. to print arrays.
  1317. repr : bool, optional
  1318. If True (default), the function for pretty printing (``__repr__``)
  1319. is set, if False the function that returns the default string
  1320. representation (``__str__``) is set.
  1321. See Also
  1322. --------
  1323. set_printoptions, get_printoptions
  1324. Examples
  1325. --------
  1326. >>> def pprint(arr):
  1327. ... return 'HA! - What are you going to do now?'
  1328. ...
  1329. >>> np.set_string_function(pprint)
  1330. >>> a = np.arange(10)
  1331. >>> a
  1332. HA! - What are you going to do now?
  1333. >>> _ = a
  1334. >>> # [0 1 2 3 4 5 6 7 8 9]
  1335. We can reset the function to the default:
  1336. >>> np.set_string_function(None)
  1337. >>> a
  1338. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  1339. `repr` affects either pretty printing or normal string representation.
  1340. Note that ``__repr__`` is still affected by setting ``__str__``
  1341. because the width of each array element in the returned string becomes
  1342. equal to the length of the result of ``__str__()``.
  1343. >>> x = np.arange(4)
  1344. >>> np.set_string_function(lambda x:'random', repr=False)
  1345. >>> x.__str__()
  1346. 'random'
  1347. >>> x.__repr__()
  1348. 'array([0, 1, 2, 3])'
  1349. """
  1350. if f is None:
  1351. if repr:
  1352. return multiarray.set_string_function(_default_array_repr, 1)
  1353. else:
  1354. return multiarray.set_string_function(_default_array_str, 0)
  1355. else:
  1356. return multiarray.set_string_function(f, repr)