o 6a @sdZgdZdZddlZddlZzddlmZWney'ddlmZYnwddl Z ddl m Z ddlmZmZmZmZdd l mZdd lmZmZmZmZmZmZmZdd lmZdd lmZmZm Z dd l m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)m*Z*ddl+Z+ddl,Z,ddl-Z-dddddddddddd Z.   dtddZ/e*d   duddddZ0e*ddd Z1e*de-j2d!d"Z3dvd$d%Z4d&d'Z5d(d)Z6d*d+Z7d,d-Z8d.d/Z9dwd1d2Z:e:dxd5d6Z;    dyddd7d8Zdd?Z@d@dAZAdBdCZBGdDdEdEZCe*d G  dzdHdIZDe*d F  d{dJdKZEGdLdMdMZFGdNdOdOZGGdPdQdQZHGdRdSdSZIGdTdUdUeIZJGdVdWdWeIZKGdXdYdYZLGdZd[d[ZMd\d]ZNe#e$e%e&gZOePe"eQreORe"ePe!eQreORe!d^d_ZSd`daZTddde>fdbdcZU d|dddeZVe)eVdd9d|dfdgZWe:dhdiZXddde>fdjdkZY d|dldmZZe)eZdd9d|dndoZ[e\e>dpe>Z]ej^eYe]dqZ_ej^eUe]dqZ`d}drdsZadS)~zXArray printing function $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ ) array2string array_str array_reprset_string_functionset_printoptionsget_printoptions printoptionsformat_float_positionalformat_float_scientificrestructuredtextN) get_ident) numerictypes)absoluteisinfisfiniteisnat) multiarray)arraydragon4_positionaldragon4_scientificdatetime_as_string datetime_datandarrayset_legacy_print_mode)any) concatenateasarrayerrstate)longlongintcint_float_complex_bool_flexible)array_function_dispatch set_moduleimaxprecFKnaninf-) edgeitems threshold floatmode precisionsuppress linewidthnanstrinfstrsign formatterlegacyc  CsddtD} |durt|| d<gd} | | dgvr-tdddd | D|d vr5td | d vr@tjd dd|durWt|tj sNt dt |rWtd|durwz t || d<W| St yv} zt d| d} ~ ww| S)zE make a dictionary out of the non-None arguments, plus sanity checks cSsi|] \}}|dur||qSN).0kvr;r;7/usr/lib/python3/dist-packages/numpy/core/arrayprint.py Bsz&_make_options_dict..Nr3)fixeduniquer) maxprec_equalz floatmode option must be one of , css|]}d|VqdS)z"{}"Nformat)r<mr;r;r? Jz%_make_options_dict..)Nr.+ z+sign option must be one of ' ', '+', or '-')NF1.13z>legacy printing option can currently only be '1.13' or `False`r( stacklevelzthreshold must be numericzIthreshold must be non-NAN, try sys.maxsize for untruncated representationr2zprecision must be an integer)localsitemsbool ValueErrorjoinwarningswarn isinstancenumbersNumber TypeErrornpisnanoperatorindex)r2r0r/r4r3r5r6r7r8r1r9optionsmodeser;r;r?_make_options_dict=s8    ranumpyr9c  Csjt|||||||||| | } || d<t| tddkr'tddtd<d Stddur3tdd Sd S) a Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed. Parameters ---------- precision : int or None, optional Number of digits of precision for floating point output (default 8). May be None if `floatmode` is not `fixed`, to print as many digits as necessary to uniquely specify the value. threshold : int, optional Total number of array elements which trigger summarization rather than full repr (default 1000). To always use the full repr without summarization, pass `sys.maxsize`. edgeitems : int, optional Number of array items in summary at beginning and end of each dimension (default 3). linewidth : int, optional The number of characters per line for the purpose of inserting line breaks (default 75). suppress : bool, optional If True, always print floating point numbers using fixed point notation, in which case numbers equal to zero in the current precision will print as zero. If False, then scientific notation is used when absolute value of the smallest number is < 1e-4 or the ratio of the maximum absolute value to the minimum is > 1e3. The default is False. nanstr : str, optional String representation of floating point not-a-number (default nan). infstr : str, optional String representation of floating point infinity (default inf). sign : string, either '-', '+', or ' ', optional Controls printing of the sign of floating-point types. If '+', always print the sign of positive values. If ' ', always prints a space (whitespace character) in the sign position of positive values. If '-', omit the sign character of positive values. (default '-') formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpystr' : types `numpy.string_` and `numpy.unicode_` - 'object' : `np.object_` arrays Other keys that can be used to set a group of types at once are: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'numpystr' floatmode : str, optional Controls the interpretation of the `precision` option for floating-point types. Can take the following values (default maxprec_equal): * 'fixed': Always print exactly `precision` fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. * 'unique': Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the `precision` option is ignored. * 'maxprec': Print at most `precision` fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. * 'maxprec_equal': Print at most `precision` fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacy : string or `False`, optional If set to the string `'1.13'` enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to `False`, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. .. versionadded:: 1.14.0 See Also -------- get_printoptions, printoptions, set_string_function, array2string Notes ----- `formatter` is always reset with a call to `set_printoptions`. Use `printoptions` as a context manager to set the values temporarily. Examples -------- Floating point precision can be set: >>> np.set_printoptions(precision=4) >>> np.array([1.123456789]) [1.1235] Long arrays can be summarised: >>> np.set_printoptions(threshold=5) >>> np.arange(10) array([0, 1, 2, ..., 7, 8, 9]) Small results can be suppressed: >>> eps = np.finfo(float).eps >>> x = np.arange(4.) >>> x**2 - (x + eps)**2 array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) >>> np.set_printoptions(suppress=True) >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) A custom formatter can be used to display array elements as desired: >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)}) >>> x = np.arange(3) >>> x array([int: 0, int: -1, int: -2]) >>> np.set_printoptions() # formatter gets reset >>> x array([0, 1, 2]) To put back the default options, you can use: >>> np.set_printoptions(edgeitems=3, infstr='inf', ... linewidth=75, nanstr='nan', precision=8, ... suppress=False, threshold=1000, formatter=None) Also to temporarily override options, use `printoptions` as a context manager: >>> with np.printoptions(precision=2, suppress=True, threshold=5): ... np.linspace(0, 10, 10) array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ]) r8r9rLqr.r7Fr N)ra_format_optionsupdater) r2r0r/r4r3r5r6r8r7r1r9optr;r;r?res       rcCstS)a. Return the current print options. Returns ------- print_opts : dict Dictionary of current print options with keys - precision : int - threshold : int - edgeitems : int - linewidth : int - suppress : bool - nanstr : str - infstr : str - formatter : dict of callables - sign : str For a full description of these options, see `set_printoptions`. See Also -------- set_printoptions, printoptions, set_string_function )recopyr;r;r;r?r src osNt}ztj|i|tVWtjdi|dStjdi|w)aContext manager for setting print options. Set print options for the scope of the `with` block, and restore the old options at the end. See `set_printoptions` for the full description of available options. Examples -------- >>> from numpy.testing import assert_equal >>> with np.printoptions(precision=2): ... np.array([2.0]) / 3 array([0.67]) The `as`-clause of the `with`-statement gives the current print options: >>> with np.printoptions(precision=2) as opts: ... assert_equal(opts, np.get_printoptions()) See Also -------- set_printoptions, get_printoptions Nr;)rZrr)argskwargsoptsr;r;r?r*s  &rr;c Cst|}||jkr ||S|j|d|kr5tt|||tjd|t|||tj| df|dSt|||tjddS)z Keep only the N-D corners (leading and trailing edges) of an array. Should be passed a base-class ndarray, since it makes no guarantees about preserving subclasses. N)axis)lenndimshaper_leading_trailingrZ index_exp)ar/r]rmr;r;r?rqMs rqcCs t|tur d}nd}||S)z@ Object arrays containing lists should be printed unambiguously z list({!r})z{!r})typelistrF)ofmtr;r;r?_object_formatas  rxcCt|Sr:)reprxr;r;r? repr_formatir}cCryr:)strr{r;r;r? str_formatlr~rc sfddfddfddfddfddfddfddfd dd dd dd dd }dd} durfddD} d| vro|D] } | d|| <qdd| vrdD] } | d|| <qud| vrdD] } | d|| <qd| vrdD] } | d|| <qd| vr| d|d<|D]} | | vr| | || <q|S)NctSr:) BoolFormatr;datar;r?uz!_get_formatdict..crr:) IntegerFormatr;rr;r?rvrctdSNrcFloatingFormatr;rr1r9r2r7r3r;r?rw crrrr;rr;r?ryrcrrComplexFloatingFormatr;rr;r?r{rcrrrr;rr;r?r}rcs tdSr)DatetimeFormatr;)rr9r;r?rs crr:)TimedeltaFormatr;rr;r?rrcStSr:)rxr;r;r;r?rcSrr:)rr;r;r;r?rrcSrr:)r}r;r;r;r?rr) rQintfloat longfloat complexfloatlongcomplexfloatdatetime timedeltaobjectvoidnumpystrcs fddS)NcsSr:r;r;r{r;r?rrz3_get_formatdict..indirect..r;r{r;r{r?indirects z!_get_formatdict..indirectcsg|] }|dur|qSr:r;)r<r=)r8r;r? sz#_get_formatdict..allint_kind)r float_kind)rr complex_kind)rrstr_kindr)keys) rr2r1r3r7r9r8rj formatdictrfkeyskeyr;)rr1r8r9r2r7r3r?_get_formatdictosD      rcKs:|j}|j}t|fi|}t|tjr|dSt|tjr/t|tjr*|dS|dSt|tjrEt|tj r@|dS|dSt|tj r[t|tj rV|dS|dSt|tj tj fri|dSt|tjrt|d St|tjr|d St|tjr|jd urtj|fi|S|d S|dS) z; find the right formatting function for the dtype_ rQrrrrrrrrrNr)dtypertr issubclass_ntr$integer timedelta64floatingrcomplexfloating clongfloatunicode_string_ datetime64object_rnamesStructuredVoidFormat from_data)rr^dtype_dtypeobjrr;r;r?_get_format_functions8                       r...csfdd}|S)a  Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs Decorates a function such that if it calls itself with the same first argument, it returns `fillvalue` instead of recursing. Largely copied from reprlib.recursive_repr cs$ttfdd}|S)Nc sTt|tf}|vr S|z|g|Ri|W|S|wr:)idr adddiscard)selfrirjr)f fillvalue repr_runningr;r?wrappers z>_recursive_guard..decorating_function..wrapper)set functoolswraps)rrr)rrr?decorating_functions z-_recursive_guard..decorating_functionr;)rrr;rr?_recursive_guards rrKc Cst|}|jdkr |}|j|dkrd}t||d}nd}t|fi|}d}|dt|7}t|||d|||d||d}|S) Nr;r0rr/rrKr4r9)rrpsizerqrrn _formatArray) rsr^ separatorprefixrsummary_insertformat_functionnext_line_prefixlstr;r;r? _array2strings   rc C|fSr:r;)rsmax_line_widthr2suppress_smallrrstyler8r0r/r7r1suffixr9r;r;r?_array2string_dispatchersr)modulec  Cst||| ||dd| || | }t}|||ddkr6|tjur$t}|jdkr5|jj dur5|| Sn |tjurCt j dt dd|ddkrS|dt| 8<|jd krZd St||||S) a Return a string representation of an array. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int or None, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. separator : str, optional Inserted between elements. prefix : str, optional suffix : str, optional The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as:: prefix + array2string(a) + suffix The output is left-padded by the length of the prefix string, and wrapping is forced at the column ``max_line_width - len(suffix)``. It should be noted that the content of prefix and suffix strings are not included in the output. style : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.14.0 formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'void' : type `numpy.void` - 'numpystr' : types `numpy.string_` and `numpy.unicode_` Other keys that can be used to set a group of types at once are: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'numpystr' threshold : int, optional Total number of array elements which trigger summarization rather than full repr. Defaults to ``numpy.get_printoptions()['threshold']``. edgeitems : int, optional Number of array items in summary at beginning and end of each dimension. Defaults to ``numpy.get_printoptions()['edgeitems']``. sign : string, either '-', '+', or ' ', optional Controls printing of the sign of floating-point types. If '+', always print the sign of positive values. If ' ', always prints a space (whitespace character) in the sign position of positive values. If '-', omit the sign character of positive values. Defaults to ``numpy.get_printoptions()['sign']``. floatmode : str, optional Controls the interpretation of the `precision` option for floating-point types. Defaults to ``numpy.get_printoptions()['floatmode']``. Can take the following values: - 'fixed': Always print exactly `precision` fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. - 'unique': Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the `precision` option is ignored. - 'maxprec': Print at most `precision` fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. - 'maxprec_equal': Print at most `precision` fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacy : string or `False`, optional If set to the string `'1.13'` enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to `False`, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. .. versionadded:: 1.14.0 Returns ------- array_str : str String representation of the array. Raises ------ TypeError if a callable in `formatter` does not return a string. See Also -------- array_str, array_repr, set_printoptions, get_printoptions Notes ----- If a formatter is specified for a certain type, the `precision` keyword is ignored for that type. This is a very flexible function; `array_repr` and `array_str` are using `array2string` internally so keywords with the same name should work identically in all three functions. Examples -------- >>> x = np.array([1e-16,1,2,3]) >>> np.array2string(x, precision=2, separator=',', ... suppress_small=True) '[0.,1.,2.,3.]' >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0 0x1 0x2]' Nr9rLr;zT'style' argument is deprecated and no longer functional except in 1.13 'legacy' moder(rMr4r z[])rarerhrfrZ_NoValuerzrprritemrTrUDeprecationWarningrnrr)rsrr2rrrrr8r0r/r7r1rr9 overridesr^r;r;r?r s,       rcCsXt|t||k}|dkrt|t|krd}|r$||d7}|}||7}||fS)NrLF )rnrstrip)slineword line_widthrr9 needs_wrapr;r;r? _extendLinesrc Cs|}t|dks|dkrt||||||Stdd|D}t|||krAt|t|krA||d7}||d}|}n t|d}||d7}|ddD]}||d7}||}qS|t|d } || d7}||fS) zS Extends line with nicely formatted (possibly multi-line) string ``word``. r rLcs|]}t|VqdSr:rn)r<rr;r;r?rHz%_extendLine_pretty..rr rKN) splitlinesrnrmaxr) rrrrrr9wordsmax_word_lengthindent suffix_lengthr;r;r?_extendLine_prettys"     rcs4fddz d||dWdSdw)zgformatArray is designed for two modes of operation: 1. Full output 2. Summarized output cst|}j|}|dkr|S|d}dkr|}n|td}j|}o0d|k}|r8} } nd} |} d} |dkr׈dkrO|t} n |tttd} |} t| D]}||f||}t| | || |\} } | 7} qb|rt| | | |\} } dkr| d7} n| 7} t| dd D]}|| f||}t| | || |\} } | 7} qdkr|} |d ||}t| | || |\} } | | 7} ngd} d |d}t| D]}||f||}| |||7} q|rdkr | |d 7} n| ||7} t| dd D]}|| f||}| |||7} q|d ||}| ||7} d | t|dd} | S)z By using this local function, we don't need to recurse with all the arguments. Since this function is not created recursively, the cost is not significant r rKrL]rlrr rDr)rrz, [N)rnrorprrrangerr)r]hanging_indent curr_widthrm axes_leftnext_hanging_indent next_widtha_len show_summary leading_itemstrailing_itemsr elem_widthrirline_sepnestedrs edge_itemsrr9recurserrrr;r?rs                z_formatArray..recurserr;)r]rrNr;)rsrrrrrrr9r;rr?rs b rcCs&|durdS|dkrtd||S)Nrr z{} must be >= 0)rRrF)r|namer;r;r?_none_or_positive_arg\s rc@s0eZdZdZd ddddZddZd d ZdS) rz' Formatter for subtypes of np.floating FNrccCst|tr |r dnd}||_|jdkr|jdkr|dkrd}||_|dkr)d|_n||_t|jd|_||_||_d|_ d|_ | |dS) NrJr.rLr;rKrBr2F) rVrQ_legacyrpr1r2rrr7 exp_formatlarge_exponent fillFormat)rrr2r1rr7r9r;r;r?__init__es   zFloatingFormat.__init__cs |t|}t||dk}t|dkrGt|}t|}tdd|dks5js8|dks5||dkr8d_Wdn1sBwYt|dkr`d_ d_ d_ d _ d_ d_nۈjrd \jd ksqjd krud \fdd|D}tdd|D\}}} tdd|D\} } tdd| Dd_ d_ tdd| D_j__ jd krd_ n tdd| D_ j dj_ ngd \jd krd \fdd|D}tdd|D\} } jd kr dtdd| D_ n tdd| D_ tdd| D_ d _ _ jdvr5j __d_ nd_ d_jd krVjdkrVtt|sVj d7_ |j|jkrjd kplt|t|dk} ttd!} ttd"| }j d}tj | |||_ dSdS)#Nr ignore)overgחAg-C6?g@@T.r)rTrArL)r=Fc3s*|]}t|jjdkdVqdS)rJ)r2rBtrimr7N)rr2r7r<r|rrrBr;r?rHs  z,FloatingFormat.fillFormat..cs|]}|dVqdS)r`N) partitionr<rr;r;r?rHrIcsrrNsplitrr;r;r?rHrIcsrr:rrr;r;r?rHrr r=csrr:rrr;r;r?rHrr(csrr:rrr;r;r?rHrrlc 3s,|]}t|jdjdkdVqdS)TrJ)r2 fractionalrBrr7N)rr2r7rrr;r?rHscsrrrrr;r;r?rHrIcss|] }t|dVqdS)z-+N)rnlstriprr;r;r?rHscsrr:rrr;r;r?rHrcsrr:rrr;r;r?rHr)rArCrKr.r5r6)rrrnrZrminrrr pad_left pad_rightrexp_sizerB min_digitsr1rzipr2r7rsignbitrrre)rr finite_vals abs_non_zeromax_valmin_valstrs frac_strs_exp_strsint_part frac_partneginfnanleninflenoffsetr;rr?r s              zFloatingFormat.fillFormatc Cst|sTtddBt|r |jdkrdnd}|td}n|dkr&dn|jdkr-dnd}|td}d |j|jd t||WdS1sOwY|j rlt ||j |j |j |j|jdk|j|jd St||j |j |j d |j|jdk|j|jd S)Nr )invalidrJrr5r r.r6rKr )r2rrBrr7r exp_digitsT)r2rrBrrr7rr)rZrrr[r7rerrrnr rr2rrBrrr)rr|r7retr;r;r?__call__s:       zFloatingFormat.__call__F)__name__ __module__ __qualname____doc__r r r3r;r;r;r?rcs  TrTr=c Cs`t|d}t|d}t|d}t|d}|dkr$|dkr$||kr$tdt||||||||dS)a Format a floating-point scalar as a decimal string in scientific notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed. If `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. exp_digits : non-negative integer, optional Pad the exponent with zeros until it contains at least this many digits. If omitted, the exponent will be at least 2 digits. min_digits : non-negative integer or None, optional Minimum number of digits to print. This only has an effect for `unique=True`. In that case more digits than necessary to uniquely identify the value may be printed and rounded unbiased. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_positional Examples -------- >>> np.format_float_scientific(np.float32(np.pi)) '3.1415927e+00' >>> s = np.float32(1.23e24) >>> np.format_float_scientific(s, unique=False, precision=15) '1.230000071797338e+24' >>> np.format_float_scientific(s, exp_digits=4) '1.23e+0024' r2rr1rr 2min_digits must be less than or equal to precision)r2rBrr7rr1r)rrRr)r|r2rBrr7rr1rr;r;r?r s E   r c Csvt|d}t|d}t|d}t|d}|s|dkrtd|dkr.|dkr.||kr.tdt|||||||||d S) a Format a floating-point scalar as a decimal string in positional notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed, or if `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding fractional : boolean, optional If `True`, the cutoffs of `precision` and `min_digits` refer to the total number of digits after the decimal point, including leading zeros. If `False`, `precision` and `min_digits` refer to the total number of significant digits, before or after the decimal point, ignoring leading zeros. trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. pad_right : non-negative integer, optional Pad the right side of the string with whitespace until at least that many characters are to the right of the decimal point. min_digits : non-negative integer or None, optional Minimum number of digits to print. Only has an effect if `unique=True` in which case additional digits past those necessary to uniquely identify the value may be printed, rounding the last additional digit. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_scientific Examples -------- >>> np.format_float_positional(np.float32(np.pi)) '3.1415927' >>> np.format_float_positional(np.float16(np.pi)) '3.14' >>> np.format_float_positional(np.float16(0.3)) '0.3' >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10) '0.3000488281' r2rrrr z4precision must be greater than 0 if fractional=Falser9)r2rBrrr7rrr)rrRr) r|r2rBrrr7rrrr;r;r?rDs M    rc@eZdZddZddZdS)rcCsF|jdkrtttt|ttt|}nd}d||_dS)Nr z%{}d)rrrnrrZrrF)rr max_str_lenr;r;r?r s zIntegerFormat.__init__cCs |j|Sr:rErr|r;r;r?r3 zIntegerFormat.__call__Nr5r6r7r r3r;r;r;r?rs rc@r:)rcKs|jdkr d|_dSd|_dS)Nr;z TrueTrue)rptruestr)rrrjr;r;r?r szBoolFormat.__init__cCs|r|jSdS)NFalse)r@r<r;r;r?r3zBoolFormat.__call__Nr>r;r;r;r?rs rc@s*eZdZdZ d ddddZddZdS) rz. Formatter for subtypes of np.complexfloating FNrcc Csbt|tr |r dnd}|}}|dkrd}d}t|j|||||d|_t|j|||d|d|_dS)NrJr.rLrCr))r7r9)rVrQrreal real_formatimag imag_format) rr|r2r1rr7r9floatmode_realfloatmode_imagr;r;r?r s     zComplexFloatingFormat.__init__cCsH||j}||j}t|}|d|d||d}||S)Nj)rDrCrFrErnr)rr|rrspr;r;r?r3s   zComplexFloatingFormat.__call__r4)r5r6r7r8r r3r;r;r;r?rs rc@s$eZdZddZddZddZdS)_TimelikeFormatcCs~|t|}t|dkr#tt|t|t|t|}nd}t||jkr1t|d}d||_d ||_ dS)Nr z%{}sz'NaT') rrnr_format_non_natrZrrrF_formatrjust_nat)rrnon_natr;r;r;r?r s   z_TimelikeFormat.__init__cCstr:)NotImplementedErrorr<r;r;r?rNsz_TimelikeFormat._format_non_natcCst|r|jS|j||Sr:)rrQrOrNr<r;r;r?r3sz_TimelikeFormat.__call__N)r5r6r7r rNr3r;r;r;r?rLs rLcs6eZdZ  d fdd ZfddZdd ZZS) rN same_kindFcs\|dur|jjdkrt|jd}nd}|durd}||_||_||_||_t|dS)NMr rnaive) rkindrtimezoneunitcastingr9superr )rr|rYrXrZr9 __class__r;r?r s zDatetimeFormat.__init__cs |jdkr ||St|S)NrL)r9rNr[r3r<r\r;r?r3s   zDatetimeFormat.__call__cCsdt||j|j|jdS)N'%s')rYrXrZ)rrYrXrZr<r;r;r?rN s zDatetimeFormat._format_non_nat)NNrTF)r5r6r7r r3rN __classcell__r;r;r\r?rs  rc@seZdZddZdS)rcCst|dS)Ni8)rastyper<r;r;r?rNrBzTimedeltaFormat._format_non_natN)r5r6r7rNr;r;r;r?rs rc@r:)SubArrayFormatcC ||_dSr:r)rrr;r;r?r r=zSubArrayFormat.__init__csJ|jdkrddfdd|DdSddfdd|DdS)Nr rrDc3|]}|VqdSr:rdr<rsrr;r?rHrIz*SubArrayFormat.__call__..rc3rer:)r3rfrgr;r?rHrI)rorS)rarrr;rgr?r3s   zSubArrayFormat.__call__Nr>r;r;r;r?rbs rbc@s,eZdZdZddZeddZddZdS) rz Formatter for structured np.void objects. This does not work on structured alias types like np.dtype(('i4', 'i2,i2')), as alias scalars lose their field information, and the implementation relies upon np.void.__getitem__. cCrcr:)format_functions)rrir;r;r?r )r=zStructuredVoidFormat.__init__cKsPg}|jjD]}t||fi|}|j|jdkrt|}||q||S)z This is a second way to initialize StructuredVoidFormat, using the raw data as input. Added to avoid changing the signature of __init__. r;)rrrrprbappend)clsrr^ri field_namerr;r;r?r,s  zStructuredVoidFormat.from_datacCs@ddt||jD}t|dkrd|dSdd|S)NcSsg|]\}}||qSr;r;)r<fieldrr;r;r?r;sz1StructuredVoidFormat.__call__..r z({},)r z({})rD)r rirnrFrS)rr| str_fieldsr;r;r?r3:s   zStructuredVoidFormat.__call__N)r5r6r7r8r  classmethodrr3r;r;r;r?r!s   rcCstjt|fit|S)z Implements the repr for structured-void scalars. It is called from the scalartypes.c.src code, and is placed here because it uses the elementwise formatters defined above. )rrrrer{r;r;r?_void_scalar_reprEsrpcCs<t|}tddkr|jtkrdS|jdurdS|jtvS)a Determine if the given dtype is implied by the representation of its values. Parameters ---------- dtype : dtype Data type Returns ------- implied : bool True if the dtype is implied by the representation of its values. Examples -------- >>> np.core.arrayprint.dtype_is_implied(int) True >>> np.array([1, 2, 3], int) array([1, 2, 3]) >>> np.core.arrayprint.dtype_is_implied(np.int8) False >>> np.array([1, 2, 3], np.int8) array([1, 2, 3], dtype=int8) r9rLFN)rZrrertr$r _typelessdata)rr;r;r?dtype_is_impliedUs   rrcCsT|jdur t|St|jtrdt|S|j}|r(|dr$|s(t|}|S)z Convert a dtype to a short form which evaluates to the same dtype. The intent is roughly that the following holds >>> from numpy import * >>> dt = np.int64([1, 2]).dtype >>> assert eval(dtype_short_repr(dt)) == dt Nr^r ) rrrrtr%risalphaisalnumrz)rtypenamer;r;r?dtype_short_reprys   rvc Cs^|durtd}t|turt|j}nd}t|jo|jdk}|d}|r(dnd}tdd kr@|jd kr@|jjs@t | } n|jdksJ|jd krV|||||d ||d } ndt |jf} || |} |rh| Sd t |j} t | | dd} d} tdd krt|jjtrddt |d} n| t | d|krddt |d} | | | S)zEInternal version of array_repr() that allows overriding array2string.Nr4rr (),r9rLr;)r rD)rz [], shape=%sz dtype={})rr rK)rertrr5rrrrrprrzrrFrvrnrfindrr%)rhrr2rr class_name skipdtyperrrarr_str dtype_str last_line_lenspacerr;r;r?_array_repr_implementations:        rcCrr:r;rhrr2rr;r;r?_array_repr_dispatcherrcCt||||S)a  Return the string representation of an array. Parameters ---------- arr : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. Returns ------- string : str The string representation of an array. See Also -------- array_str, array2string, set_printoptions Examples -------- >>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' >>> x = np.array([1e-6, 4e-7, 2, 3]) >>> np.array_repr(x, precision=6, suppress_small=True) 'array([0.000001, 0. , 2. , 3. ])' )rrr;r;r?rs-rcCst|tr t|St|Sr:)rVbytesrzr)r>r;r;r?_guarded_repr_or_strs rcCsXtddkr|jdkr|jjst|S|jdkr#ttj |dS|||||ddS)zDInternal version of array_str() that allows overriding array2string.r9rLr;rKr) rerprrrrrrZr __getitem__)rsrr2rrr;r;r?_array_str_implementations   rcCrr:r;rsrr2rr;r;r?_array_str_dispatcherrrcCr)aa Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to `array_repr`, the difference being that `array_repr` also returns information on the kind of array and its data type. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. See Also -------- array2string, array_repr, set_printoptions Examples -------- >>> np.array_str(np.arange(3)) '[0 1 2]' )rrr;r;r?rs$r __wrapped__)rcCs0|dur|r ttdSttdSt||S)a Set a Python function to be used when pretty printing arrays. Parameters ---------- f : function or None Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays. repr : bool, optional If True (default), the function for pretty printing (``__repr__``) is set, if False the function that returns the default string representation (``__str__``) is set. See Also -------- set_printoptions, get_printoptions Examples -------- >>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> np.set_string_function(pprint) >>> a = np.arange(10) >>> a HA! - What are you going to do now? >>> _ = a >>> # [0 1 2 3 4 5 6 7 8 9] We can reset the function to the default: >>> np.set_string_function(None) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) `repr` affects either pretty printing or normal string representation. Note that ``__repr__`` is still affected by setting ``__str__`` because the width of each array element in the returned string becomes equal to the length of the result of ``__str__()``. >>> x = np.arange(4) >>> np.set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([0, 1, 2, 3])' Nr r )rr_default_array_repr_default_array_str)rrzr;r;r?rGs 3   r) NNNNNNNNNNN) NNNNNNNNNN)r;)r)rKr) NNNNNNNNNNNN)NTr=FNNN)NTTr=FNNN)NNN)T)br8__all__ __docformat__rrW_threadr ImportError _dummy_threadrbrZrrrumathrrrrrrrrrrrr fromnumericrnumericrrrrr r!r"r#r$r%rr&r'r\rT contextlibrerarrcontextmanagerrrqrxr}rrrrrrrrrrrrrr rrrrrLrrrbrrprqrrrjrrrvrrrrrrrgetattr_array2string_implpartialrrrr;r;r;r?s   $ $  ('   !1 '  2v O [  !  $    $ 0  0     (