arrayprint.py 58 KB

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