U C^~ @sFdZddlmZmZmZddddddd d d g Zd Zdd lZdd lZdd l Z ej ddkrzddl m Z Wqe k rddlm Z YqXn2zddlm Z Wn e k rddlm Z YnXdd lZddlmZddlmZmZmZmZmZmZddlmZddlmZmZm Z m!Z!m"Z"m#Z#m$Z$ddl%m&Z&m'Z'ddl(m)Z)m*Z*m+Z+ddlm,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4m5Z5dd l6Z6dd l7Z7ddddddddd d dd! Z8dqd"d#Z9e5d$drd%dZ:e5d$d&dZ;e5d$e7jd+d,Z?d-d.Z@d/d0ZAd1d2ZBd3d4ZCdtd6d7ZDeDdud:d;ZEdvdd d d d8d9ejGd d d d d d9f d?dZHd@dAZIdBdCZJdDdEZKGdFdGdGeLZMe5d$dwdJd ZNe5d$dxdKd ZOGdLdMdMeLZPGdNdOdOeLZQGdPdQdQeLZRGdRdSdSeLZSGdTdUdUeSZTGdVdWdWeSZUGdXdYdYeLZVGdZd[d[eLZWd\d]ZXe.e/e0e1gZYeZe-e[rdeY\e-eZe,e[rzeY\e,d^d_Z]d`daZ^d d d eHfdbdcZ_dydddeZ`e4e`d$d>dzdfdZaeDdgdhZbd d d eHfdidjZcd{dkdlZde4edd$d>d|dmdZeefeHdneHZgejhecegdoZiejhe_egdoZjd}dpdZkekeidekejdHd S)~zXArray printing function $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ )divisionabsolute_importprint_function array2string array_str array_reprset_string_functionset_printoptionsget_printoptions printoptionsformat_float_positionalformat_float_scientificZrestructuredtextN) get_ident) numerictypes)absolute not_equalisnanisinfisfiniteisnat) multiarray)arraydragon4_positionaldragon4_scientificdatetime_as_string datetime_datandarrayset_legacy_print_mode)ravelany) concatenateasarrayerrstate)longlongintcint_float_complex_bool_flexible)array_function_dispatch set_moduleimaxprecFKnaninf-) edgeitems threshold floatmode precisionsuppress linewidthnanstrinfstrsign formatterlegacyc CsddtD} |dk r(t|| d<ddddg} | | dgkr^td d d d | D|d krntd| dkrtjddd|dk rt|tj st dt |rtd| S)zE make a dictionary out of the non-None arguments, plus sanity checks cSsi|]\}}|dk r||qSN).0kvr@r@8/tmp/pip-install-6_kvzl1k/numpy/numpy/core/arrayprint.py Jsz&_make_options_dict..Nr8fixeduniquer. maxprec_equalz floatmode option must be one of , css|]}d|VqdS)z"{}"Nformat)rAmr@r@rD Rsz%_make_options_dict..)Nr3+ 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 representation) localsitemsbool ValueErrorjoinwarningswarn isinstancenumbersNumber TypeErrornpr) r7r5r4r9r8r:r;r<r=r6r>optionsmodesr@r@rD_make_options_dictEs(    ranumpyc  Ks| dd} | r*d} t| | dt|||||||||| | } || d<t| tddkrvtddtd <ntdd krtddS) 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 - 'str' : all other strings 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 'str' and '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. ]) r>Nz7set_printoptions() got unexpected keyword argument '{}'rr=rPqr3r<F)popr]rKpopitemra_format_optionsupdater)r7r5r4r9r8r:r;r=r<r6kwargr>msgoptr@r@rDr ds*      cCstS)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 )rfcopyr@r@r@rDr sc os6t}ztj||tVW5tjf|XdS)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 N)r^r r )argskwargsoptsr@r@rDr /s  r@c Cst|}||jkr||S|j|d|krjtt|||tjd|t|||tj| df|dSt|||tjddSdS)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_trailingr^Z index_exp)ar4indexrpr@r@rDrtRs rtcCs t|tkrd}nd}||S)z@ Object arrays containing lists should be printed unambiguously z list({!r})z{!r})typelistrK)ofmtr@r@rD_object_formatfs r{cCst|Sr?)reprxr@r@rD repr_formatnsrcCst|Sr?strr}r@r@rD str_formatqsrc s|d|d|d|d|dfddfddfd dfd dfd dfd dfd dfddddddddddd }dd}|ddk rfddD}d|kr|D]}|d||<qd|krDdD]}|d||<q,d|krjdD]}|d||<qRd|krdD]}|d||<qxd |krd!D]}|d ||<q|D] }||kr||||<q|S)"Nr7r6r8r<r>cstSr?) BoolFormatr@datar@rD{z!_get_formatdict..cstSr?) IntegerFormatr@rr@rDr|rcstdSN)r>FloatingFormatr@rfmoder>precr<suppr@rDr}scstdSrrr@rr@rDrscstdSrComplexFloatingFormatr@rr@rDrscstdSrrr@rr@rDrscs tdSr)DatetimeFormatr@)rr>r@rDrrcstSr?)TimedeltaFormatr@rr@rDrrcSstSr?)r{r@r@r@rDrrcSstSr?)rr@r@r@rDrrcSstSr?)rr@r@r@rDrrcSstSr?rr@r@r@rDrr) rUintfloat longfloat complexfloatlongcomplexfloatdatetime timedeltaobjectvoidnumpystrrcs fddS)NcsSr?r@r@r}r@rDrrz3_get_formatdict..indirect..r@r}r@r}rDindirectsz!_get_formatdict..indirectr=csg|]}|dk r|qSr?r@)rArB)r=r@rD s z#_get_formatdict..allZint_kind)rZ float_kind)rrZ complex_kind)rrZstr_kind)rr)keys)rrj formatdictrZfkeyskeyr@)rrr=r>rr<rrD_get_formatdicttsN             rcKsD|j}|j}t|f|}t|tjr.|dSt|tjr\t|tjrP|dS|dSnt|tjrt|tj r~|dS|dSnt|tj rt|tj r|dS|dSnt|tj tj fr|dSt|tjr|d St|tjr|d St|tjr6|jd k r*tj|f|S|d Sn |dSd S) z; find the right formatting function for the dtype_ rUrrrrrrrrrNr)dtyperwr issubclass_ntr*integerZ timedelta64ZfloatingrZcomplexfloatingZ clongfloatZunicode_Zstring_Z datetime64Zobject_rnamesStructuredVoidFormat from_data)rr_Zdtype_Zdtypeobjrr@r@rD_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 sJt|tf}|krS|z|f||WS|XdSr?)idradddiscard)selfrlrmr)f fillvalue repr_runningr@rDwrappers z>_recursive_guard..decorating_function..wrapper)set functoolswraps)rrr)rrrDdecorating_functions z-_recursive_guard..decorating_functionr@)rrr@rrD_recursive_guards rrOc Cst|}|jdkr|}|j|dkr8d}t||d}nd}t|f|}d}|dt|7}t|||d|||d||d}|S) Nr@r5rr4rrOr9r>)r#rssizertrrq _formatArray) rur_ separatorprefixrsummary_insertformat_functionnext_line_prefixlstr@r@rD _array2strings$   rc Ks|fSr?r@)rumax_line_widthr7suppress_smallrrstyler=r5r4r<r6suffixrhr@r@rD_array2string_dispatcher sr)modulec  Ks| dd}| r*d}t|| dt||| ||dd| || | }t}|||ddkr|tj krrt }|j dkr|j j dkr||Sn|tj k rtjdtdd |ddkr|d t| 8<|jdkrd St||||S) a Return a string representation of an array. Parameters ---------- a : array_like 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_` - 'str' : all other strings 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 'str' and '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]' r>Nz3array2string() got unexpected keyword argument '{}'rrPr@zT'style' argument is deprecated and no longer functional except in 1.13 'legacy' moderrQr9z[])rdr]rKrerarfrkrgr^_NoValuer|rsrritemrXrYDeprecationWarningrqrr)rurr7rrrrr=r5r4r<r6rrhr>ri overridesr_r@r@rDrs@       cCs\t|t||k}|dkr4|t|t|kr4d}|rL||d7}|}||7}||fS)NrPF )rqrstrip)slineword line_widthrr>Z needs_wrapr@r@rD _extendLinesrcs6fddzd||dWSdXdS)zgformatArray is designed for two modes of operation: 1. Full output 2. Summarized output cst|}j|}|dkr&|S|d}dkr<|}n |td}j|}o`d|k}|rp} } nd} |} d} |dkrdkr|t} n|tttd} |} t| D]4}||f||}t| | || |\} } | 7} q|r4t| | | |\} } dkr,| d7} n| 7} t| dd D]8}|| f||}t| | || |\} } | 7} q@dkr|} |d ||}t| | || |\} } | | 7} nd} d |d}t| D](}||f||}| |||7} q|r4dkr$| |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 rrOrP]rorrrI)rrz, [N)rqrrrsrmaxranger)rvhanging_indent curr_widthrpZ axes_leftZnext_hanging_indentZ next_widthZa_lenZ show_summaryZ leading_itemsZtrailing_itemsrZ elem_widthrirZline_sepnestedru edge_itemsrr>recurserrrr@rDrs               z_formatArray..recurserNr@)rvrrr@)rurrrrrrr>r@rrDrs b rcCs&|dkr dS|dkr"td||S)Nrrz{} must be >= 0)rVrK)r~namer@r@rD_none_or_positive_argOs rc@s*eZdZdZd ddZddZddZd S) rz' Formatter for subtypes of np.floating FcKst|tr|rdnd}|dd|_|jdkrD|jdkrD|dkrDd}||_|dkrZd|_n||_t|jd |_||_||_ d|_ d|_ | |dS) NrNr3r>FrPr@rOrGr7) rZrUget_legacyrsr6r7rrr< exp_formatZlarge_exponent fillFormat)rrr7r6rr<rhr@r@rD__init__Xs    zFloatingFormat.__init__c s|t|}t||dk}t|dkrzt|}t|}tdd.|dksjjsp|dksj||dkrpd_W5QRXt|dkrd_ d_ d_ d _ d_ njrd \jd ks̈jd krd \fdd|D}tdd|D\}}} tdd|D\} } tdd| Dd_ d_ tdd| D_jd kr^d_ ntdd| D_ j dj_ d_ nd \jd krd \fdd|D}tdd|D\} } jd krdtdd| D_ ntdd| D_ tdd| D_ d _ jdkrJj _d_ d_ n d_ d_ jd krjd krtt|sj d7_ |j|jkrjd!kpt|t|dk} ttd"} ttd#| }j d}tj | |||_ dS)$Nrignore)ZovergחAg-C6?g@@T.r)rTrFrP)rBFc3s(|] }t|jjdkdVqdS)rN)r7rGtrimr<N)rr7r<rAr~rrrGr@rDrMs z,FloatingFormat.fillFormat..css|]}|dVqdS)eN) partitionrArr@r@rDrMscss|]}|dVqdSrNsplitrr@r@rDrMscss|]}t|VqdSr?rqrr@r@rDrMsrrBcss|]}t|VqdSr?rrr@r@rDrMsrcss|]}t|VqdSr?rrr@r@rDrMsroFc 3s*|]"}t|jdjdkdVqdS)TrN)r7 fractionalrGrr<N)rr7r<rrr@rDrMscss|]}|dVqdSrrrr@r@rDrMscss|]}t|dVqdS)z-+N)rqlstriprr@r@rDrMscss|]}t|VqdSr?rrr@r@rDrMscss|]}t|VqdSr?rrr@r@rDrMs)rFrHrOr3r:r;)rrrqr^rminr$rrpad_left pad_rightrexp_sizerGr6rzipr7r<r!Zsignbitrrrf)rrZ finite_valsZ abs_non_zeroZmax_valZmin_valstrsZ frac_strs_Zexp_strsZint_partZ frac_partZneginfZnanlenZinflenoffsetr@rrDrss|                zFloatingFormat.fillFormatc Cst|stddt|r@|jdkr.dnd}|td}n*|dkrLdn|jdkrZdnd}|td}d |j|jd t||W5QRSQRX|j rt ||j |j |j |jdk|j|jd St||j |j d |j |jdk|j|jd SdS)Nr)invalidrNrr:rr3r;rOrr7rGrr<r exp_digitsTr7rGrrr<rr)r^rr$rr<rfrrrqrrr7rGrrr)rr~r<retr@r@rD__call__s4    2zFloatingFormat.__call__N)F)__name__ __module__ __qualname____doc__rrrr@r@r@rDrVs TrTrBc Cs4t|d}t|d}t|d}t|||||||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` was omitted, print all necessary digits, otherwise digit generation is cut off after `precision` digits and the remaining value is rounded. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value. 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. 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' r7rrr)rr)r~r7rGrr<rrr@r@rDr s=   c Cs6t|d}t|d}t|d}t||||||||dS)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` was omitted, print out all necessary digits, otherwise digit generation is cut off after `precision` digits and the remaining value is rounded. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value. fractional : boolean, optional If `True`, the cutoff of `precision` digits refers to the total number of digits after the decimal point, including leading zeros. If `False`, `precision` refers 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. 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' r7rrr)rr)r~r7rGrrr<rrr@r@rDr *sD   c@seZdZddZddZdS)rcCsF|jdkr2tttt|ttt|}nd}d||_dS)Nrz%{}d)rrrqrr^rrK)rr max_str_lenr@r@rDrxs  zIntegerFormat.__init__cCs |j|Sr?rJrr~r@r@rDrszIntegerFormat.__call__Nrrrrrr@r@r@rDrwsrc@seZdZddZddZdS)rcKs|jdkrdnd|_dS)Nr@z TrueTrue)rstruestr)rrrmr@r@rDrszBoolFormat.__init__cCs|r |jSdS)NFalse)rr r@r@rDrszBoolFormat.__call__Nr r@r@r@rDrsrc@s"eZdZdZdddZddZdS) rz. Formatter for subtypes of np.complexfloating Fc Ksvt|tr|rdnd}|}}|dddkr6d}d}t|j|||fd|i||_t|j|||fddi||_dS) NrNr3r>FrPrHr.r<)rZrUrrreal real_formatimag imag_format) rr~r7r6rr<rhZfloatmode_realZfloatmode_imagr@r@rDrs(    zComplexFloatingFormat.__init__cCsH||j}||j}t|}|d|d||d}||S)Nj)rrrrrqr)rr~rrspr@r@rDrs    zComplexFloatingFormat.__call__N)F)rrrr rrr@r@r@rDrs rc@s$eZdZddZddZddZdS)_TimelikeFormatcCs~|t|}t|dkrFtt|t|t|t|}nd}t||jkrbt|d}d||_d ||_ dS)Nrz%{}sz'NaT') rrqr_format_non_natr^rrrK_formatrjust_nat)rrZnon_natr r@r@rDrs   z_TimelikeFormat.__init__cCstdSr?)NotImplementedErrorr r@r@rDrsz_TimelikeFormat._format_non_natcCs"t|r|jS|j||SdSr?)rrrrr r@r@rDrsz_TimelikeFormat.__call__N)rrrrrrr@r@r@rDrsrcs2eZdZd fdd ZfddZdd ZZS) rN same_kindFcs`|dkr(|jjdkr$t|jd}nd}|dkr4d}||_||_||_||_tt| |dS)NMrrZnaive) rkindrtimezoneunitcastingr>superrr)rr~r"r!r#r> __class__r@rDrs zDatetimeFormat.__init__cs$|jdkr||Stt||S)NrP)r>rr$rrr r%r@rDrs  zDatetimeFormat.__call__cCsdt||j|j|jdS)N'%s')r"r!r#)rr"r!r#r r@r@rDrs zDatetimeFormat._format_non_nat)NNrF)rrrrrr __classcell__r@r@r%rDrs  rc@seZdZddZdS)rcCst|dS)Ni8)rZastyper r@r@rDrszTimedeltaFormat._format_non_natN)rrrrr@r@r@rDrsrc@seZdZddZddZdS)SubArrayFormatcCs ||_dSr?r)rrr@r@rDrszSubArrayFormat.__init__csJ|jdkr*ddfdd|DdSddfdd|DdS)NrrrIc3s|]}|VqdSr?r+rArurr@rDrMsz*SubArrayFormat.__call__..rc3s|]}|VqdSr?)rr,r-r@rDrMs)rrrW)rarrr@r-rDrs  zSubArrayFormat.__call__Nr r@r@r@rDr*sr*c@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__. cCs ||_dSr?)format_functions)rr/r@r@rDrszStructuredVoidFormat.__init__cKsLg}|jjD]6}t||f|}|j|jdkr8t|}||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@)rrrrsr*append)clsrr_r/ field_namerr@r@rDrs  zStructuredVoidFormat.from_datacCsDddt||jD}t|dkr0d|dSdd|SdS)NcSsg|]\}}||qSr@r@)rAfieldrr@r@rDrsz1StructuredVoidFormat.__call__..rz({},)rz({})rI)rr/rqrKrW)rr~Z str_fieldsr@r@rDr s   zStructuredVoidFormat.__call__N)rrrr r classmethodrrr@r@r@rDrs  rcCstjt|ft|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. )rrrrfr}r@r@rD_void_scalar_reprsr5cCs<t|}tddkr$|jtkr$dS|jdk r2dS|jtkS)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) r>rPFN)r^rrfrwr*r _typelessdata)rr@r@rDdtype_is_implied(s   r7cCsT|jdk rt|St|jtr*dt|S|j}|rP|drH|sPt|}|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) rrrrwr+risalphaisalnumr|)rtypenamer@r@rDdtype_short_reprLs   r;c Csd|dkrtd}t|tk r(t|j}nd}t|jo>|jdk}|d}|rPdnd}tdd kr|jd kr|jjst | } n<|jdks|jd kr|||||d ||d } ndt |jf} || |} |r| Sd t |j} t | | dd} d} tdd kr.t|jjtrXddt |d} n*| t | d|krXddt |d} | | | S)zEInternal version of array_repr() that allows overriding array2string.Nr9rr(),r>rPr@)rrI)rz [], shape=%sz dtype={})rrrO)rfrwrrr7rrrsrr|rrKr;rqrfindrr+)r.rr7rr class_nameZ skipdtyperrrZarr_strZ dtype_strZ last_line_lenZspacerr@r@rD_array_repr_implementationesB      rAcCs|fSr?r@r.rr7rr@r@rD_array_repr_dispatchersrCcCst||||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. ])' )rArBr@r@rDrs -cCst|trt|St|Sr?)rZbytesr|r)rCr@r@rD_guarded_repr_or_strs rEcCsXtddkr*|jdkr*|jjs*t|S|jdkrFttj |dS|||||ddS)zDInternal version of array_str() that allows overriding array2string.r>rPr@rOr) rfrsrrrrrEr^r __getitem__)rurr7rrr@r@rD_array_str_implementations   rGcCs|fSr?r@rurr7rr@r@rD_array_str_dispatchersrIcCst||||S)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]' )rGrHr@r@rDrs $ __wrapped__)rcCs6|dkr&|rttdSttdSn t||SdS)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])' Nrr)rr_default_array_repr_default_array_str)rr|r@r@rDrs 3 ) NNNNNNNNNNN) NNNNNNNNNN)r@)r)rOr) NNNNNNNNNNNN)NTrBFNN)NTTrBFNN)NNN)NNN)NNN)NNN)T)lr  __future__rrr__all__Z __docformat__sysrr[ version_info_threadr ImportError _dummy_threadthread dummy_threadrbr^rrrZumathrrrrrrrrrrrrrrZ fromnumericr r!numericr"r#r$r%r&r'r(r)r*r+rr,r-rX contextlibrfrar r contextmanagerr rtr{rrrrrrrrrrrrrrr r rrrrrrr*rr5r6rrr0r7r;rArCrrErGrIrgetattrZ_array2string_implpartialrLrKrr@r@r@rDs^   $$   -  ! 5'    7v D L    $     $ 0   0     (  ;