a :jg~ @sdZgdZdZddlZddlZddlZzddlmZWneyVddl mZYn0ddl Z ddl m ZddlmZmZmZmZdd l mZdd lmZmZmZmZmZmZmZdd lmZdd lmZm Z m!Z!dd l m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)m*Z*ddl+Z+ddl,Z,ddl-Z-ddddddddddej.d Z/dvddZ0e*ddwddddZ1e*ddd Z2d!d"Z3e*de-j4d#d$Z5dxd&d'Z6d(d)Z7d*d+Z8d,d-Z9d.d/Z:d0d1Z;dyd3d4Ze)e>dd;dddd5d6e j?dddddd6f dddd?ZAd@dAZBdBdCZCdDdEZDGdFdGdGZEe*dd|dJdKZFe*dd}dLdMZGGdNdOdOZHGdPdQdQZIGdRdSdSZJGdTdUdUZKGdVdWdWeKZLGdXdYdYeKZMGdZd[d[ZNGd\d]d]ZOd~d^d_ZPe$e%e&ejQgZRd`daZSdbdcZTddde@fdddeZUddfdgZVe)eVdd;ddhdiZWe<djdkZXddde@fdldmZYddndoZZe)eZdd;ddpdqZ[e\e@dre@Z]ej^eYe]dsZ_ej^eUe]dsZ`ddtduZadS)zXArray printing function $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ ) array2string array_str array_reprset_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_float64 complex128flexible)array_function_dispatch set_moduleimaxprecFKnaninf-) edgeitems threshold floatmode precisionsuppress linewidthnanstrinfstrsign formatterlegacyc  CsPddttD} |dur,t|| d<gd} | | dgvr^tdddd | D|d vrntd | d krtj| d <nN| dkrd| d <n<| dkrd| d <n*| dkrd| d <n| durntj ddd|durt |t j st dt|rtd|durLzt|| d<Wn0t yJ} zt d| WYd} ~ n d} ~ 00| S)zm Make a dictionary out of the non-None arguments, plus conversion of *legacy* and sanity checks. cSsi|]\}}|dur||qSN).0kvr9r9@/usr/local/lib/python3.9/site-packages/numpy/_core/arrayprint.py Hz&_make_options_dict..Nr1)fixeduniquer' maxprec_equalz floatmode option must be one of , css|]}d|VqdS)z"{}"Nformat)r:mr9r9r= Pr?z%_make_options_dict..)Nr,+ z+sign option must be one of ' ', '+', or '-'Fr71.13q1.21y1.25}zOlegacy printing option can currently only be '1.13', '1.21', '1.25', or `False`r& stacklevelzthreshold must be numericzIthreshold must be non-NAN, try sys.maxsize for untruncated representationr0zprecision must be an integer)listlocalsitemsbool ValueErrorjoinsysmaxsizewarningswarn isinstancenumbersNumber TypeErrornpisnanoperatorindex)r0r.r-r2r1r3r4r5r6r/r7optionsmodeser9r9r=_make_options_dict@sF         rgnumpyr7c  Cst|||||||||| | } || d<t| tddkrLtddtd<nBtddkrbtdn,tddkrxtdntdtjkrtdd 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 '-') .. versionchanged:: 2.0 The sign parameter can now be an integer type, previously types were floating-point types. 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.bytes_` and `numpy.str_` - '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. This also enables 1.21 legacy printing mode (described below). If set to the string ``'1.21'`` enables 1.21 legacy printing mode. This approximates numpy 1.21 print output of complex structured dtypes by not inserting spaces after commas that separate fields and after colons. If set to ``'1.25'`` approximates printing of 1.25 which mainly means that numeric scalars are printed without their type information, e.g. as ``3.0`` rather than ``np.float64(3.0)``. If set to `False`, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. .. versionadded:: 1.14.0 .. versionchanged:: 1.22.0 .. versionchanged:: 2.0 See Also -------- get_printoptions, printoptions, 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. ]) r6r7rKr,r5rMrOr N)rg_format_optionsupdaterrXrY) r0r.r-r2r1r3r4r6r5r/r7optr9r9r=rvs .         rcCs.t}ddddddtjdi|d|d<|S) 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 rKrJrMrLrOrNFr7)rjcopyrXrY)optsr9r9r=r7s rcCstdS)z'Return the legacy print mode as an int.r7)rjr9r9r9r=_get_legacy_print_modeYsroc osNt}z.tj|i|tVWtjfi|ntjfi|0dS)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`rr)argskwargsrnr9r9r=r^s  rr9c 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)ar-rcrsr9r9r=rws rwcCs t|turd}nd}||S)z@ Object arrays containing lists should be printed unambiguously z list({!r})z{!r})typerRrE)ofmtr9r9r=_object_formats r|cCs&t|tjtjfrt|St|Sr8)r\r`str_bytes_repritemxr9r9r= repr_formats rcCs&t|tjtjfrt|St|Sr8)r\r`r}r~strrrr9r9r= str_formats rc sfddfddfddfddfddfddfddfd dd dd dd dd }dd} durfddD} d| vr|D]} | d|| <qd| vrdD]} | d|| <qd| vr,dD]} | d|| <qd| vrRdD]} | d|| <q:d| vrl| d|d<|D] } | | vrt| | || <qt|S)NcstSr8) BoolFormatr9datar9r=r?z!_get_formatdict..cs tSr8) IntegerFormatr9)rr5r9r=rr?cstdSNriFloatingFormatr9rr/r7r0r5r1r9r=rs cstdSrrr9rr9r=rs cstdSrComplexFloatingFormatr9rr9r=rs cstdSrrr9rr9r=rs cs tdSr)DatetimeFormatr9)rr7r9r=rr?cstSr8)TimedeltaFormatr9rr9r=rr?cSstSr8)r|r9r9r9r=rr?cSstSr8)rr9r9r9r=rr?cSstSr8)rr9r9r9r=rr?) rUintfloat longfloat complexfloatlongcomplexfloatdatetime timedeltaobjectvoidnumpystrcs fddS)NcsSr8r9r9rr9r=rr?z3_get_formatdict..indirect..r9rr9rr=indirectsz!_get_formatdict..indirectcsg|]}|dur|qSr8r9)r:r;)r6r9r= r?z#_get_formatdict..allZint_kind)r float_kind)rrZ complex_kind)rrZstr_kindr)keys) rr0r/r1r5r7r6rq formatdictrZfkeyskeyr9)rr/r6r7r0r5r1r=_get_formatdictsB            rcKs`|j}|j}t|fi|}|dur.|dSt|tjrD|dSt|tjrrt|tjrf|dS|dSnt|tjrt|tj r|dS|dSnt|tj rt|tj r|dS|d Snt|tj tj fr|dSt|tjr|d St|tjr|d St|tjrR|jdurFtj|fi|S|d Sn |dSdS) z; find the right formatting function for the dtype_ NrrUrrrrrrrrr)dtyperyr issubclass_ntrUintegerZ timedelta64ZfloatingZ longdoubleZcomplexfloatingZ clongdoubler}r~Z datetime64Zobject_rnamesStructuredVoidFormat from_data)rrdZdtype_Zdtypeobjrr9r9r=_get_format_functions<                    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 sXt|tf}|vrS|z"|g|Ri|W|S|0dSr8)idr adddiscard)selfrprqr)f fillvalue repr_runningr9r=wrappers  z>_recursive_guard..decorating_function..wrapper)set functoolswraps)rrr)rrr=decorating_function s z-_recursive_guard..decorating_functionr9)rrr9rr=_recursive_guards rrIc Cst|}|jdkr|}|j|dkr8d}t||d}nd}t|fi|}d}|dt|7}t|||d|||d||d}|S) Nr9r.rr-rrIr2r7)rrvsizerwrrt _formatArray) rxrd separatorprefixrsummary_insertformat_functionnext_line_prefixlstr9r9r= _array2string s   rc Cs|fSr8r9)rxmax_line_widthr0suppress_smallrrstyler6r.r-r5r/suffixr7r9r9r=_array2string_dispatcher=sr)modulec  Cst||| ||dd| || | }t}|||ddkrl|tjurHt}|jdkr|jj dur|| Sn|tjurt j dt dd|ddkr|dt| 8<|jd krd 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.bytes_` and `numpy.str_` 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']``. .. versionchanged:: 2.0 The sign parameter can now be an integer type, previously types were floating-point types. 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]' Nr7rKr9zT'style' argument is deprecated and no longer functional except in 1.13 'legacy' moderrrPr2r z[])rgrjrmrkr`_NoValuerrvrrrrZr[DeprecationWarningrtrr)rxrr0rrrrr6r.r-r5r/rr7 overridesrdr9r9r=rFs*      rcCsXt|t||k}|dkr0t|t|kr0d}|rH||d7}|}||7}||fS)NrKF )rtrstrip)slineword line_widthrr7Z needs_wrapr9r9r= _extendLinesrc Cs|}t|dks|dkr.t||||||Stdd|D}t|||krt|t|kr||d7}||d}|}nt|d}||d7}|ddD]}||d7}||}q|t|d } || d7}||fS) zS Extends line with nicely formatted (possibly multi-line) string ``word``. r rKcss|]}t|VqdSr8rt)r:rr9r9r=rGr?z%_extendLine_pretty..rr rIN) splitlinesrtrmaxr) rrrrrr7wordsZmax_word_lengthindentZ suffix_lengthr9r9r=_extendLine_pretty s$     rcs8fddzd||dWdSd0dS)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 r rIrK]rrrr rCr)rrz, [N)rtrurvrrrangerr)rchanging_indent curr_widthrsZ axes_leftZnext_hanging_indentZ next_widthZa_lenZ show_summaryZ leading_itemsZtrailing_itemsrZ elem_widthrirZline_sepnestedrx edge_itemsrr7recurserrrr9r=r/s                    z_formatArray..recurserr9)rcrrNr9)rxrrrrrrr7r9rr=r&s hrcCs&|dur dS|dkr"td||S)Nrr z{} must be >= 0)rVrE)rnamer9r9r=_none_or_positive_args rc@s0eZdZdZd ddddZddZd d ZdS) rz' Formatter for subtypes of np.floating FNricCst|tr|rdnd}||_|jdkr<|jdkr<|dkr.css|]}|dVqdS)rfN) partitionr:rr9r9r=rGr?css|]}|dVqdSrNsplitrr9r9r=rGr?css|]}t|VqdSr8rrr9r9r=rGr?r r;css|]}t|VqdSr8rrr9r9r=rGr?r&css|]}t|VqdSr8rrr9r9r=rGr?rrc 3s*|]"}t|jdjdkdVqdS)TrH)r0 fractionalrArr5N)rr0r5rrr9r=rGs css|]}|dVqdSrrrr9r9r=rGr?css|]}t|dVqdS)z-+N)rtlstriprr9r9r=rGr?css|]}t|VqdSr8rrr9r9r=rGr?css|]}t|VqdSr8rrr9r9r=rGr?)r@rBrIr,r3r4)rrrtr`rminrrrpad_left pad_rightrexp_sizerA min_digitsr/rzipr0r5rZsignbitrrrj)rrZ finite_valsZ abs_non_zeroZmax_valZmin_valstrsZ frac_strs_Zexp_strsZint_partZ frac_partZneginfZnanlenZinflenoffsetr9rr=rs      $          zFloatingFormat.fillFormatc Cst|stddt|r@|jdkr.dnd}|td}n*|dkrLdn|jdkrZdnd}|td}d |j|jd t||WdS1s0Y|j rt ||j |j |j |j|jdk|j|jd St||j |j |j d |j|jdk|j|jd SdS)Nr)invalidrHrr3r r,r4rIr )r0rrArr5r exp_digitsT)r0rrArrr5rr)r`rrrar5rjrrrtrrr0rrArrr)rrr5retr9r9r=__call__s@    " zFloatingFormat.__call__)F)__name__ __module__ __qualname____doc__rrrr9r9r9r=rs  VrTr;c Cs`t|d}t|d}t|d}t|d}|dkrH|dkrH||krHtdt||||||||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' r0rrrr 2min_digits must be less than or equal to precision)r0rArr5rrr)rrVr)rr0rArr5rrrr9r9r=r>sE    rc Csvt|d}t|d}t|d}t|d}|s<|dkr>> 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' r0rrrr z4precision must be greater than 0 if fractional=Falser )r0rArrr5rrr)rrVr) rr0rArrr5rrrr9r9r=rsM     rc@seZdZdddZddZdS)rr,cCs|jdkrjt|}t|}tt|}|dkr>|dkr>d}|dkrV|dvrV|d7}t|tt|}nd}d||d|_dS)Nr rIr,z+ r z{:zd})rr`rrrtrrE)rrr5Zdata_maxZdata_minZdata_max_str_len max_str_lenr9r9r=rs     zIntegerFormat.__init__cCs |j|Sr8rDrrr9r9r=rszIntegerFormat.__call__N)r,rrrrrr9r9r9r=rs rc@seZdZddZddZdS)rcKs|jdkrdnd|_dS)Nr9z TrueTrue)rvtruestr)rrrqr9r9r=rszBoolFormat.__init__cCs|r |jSdS)NFalse)rr r9r9r=rszBoolFormat.__call__Nr r9r9r9r=rsrc@s(eZdZdZd ddddZddZdS) rz. Formatter for subtypes of np.complexfloating FNric Csbt|tr|rdnd}|}}|dkr.d}d}t|j|||||d|_t|j|||d|d|_dS)NrHr,rKrBr')r5r7)r\rUrreal real_formatimag imag_format) rrr0r/rr5r7Zfloatmode_realZfloatmode_imagr9r9r=rs    zComplexFloatingFormat.__init__cCsH||j}||j}t|}|d|d||d}||S)Nj)rrrrrtr)rrrrspr9r9r=rs    zComplexFloatingFormat.__call__)F)rrrr rrr9r9r9r=rs  rc@s$eZdZddZddZddZdS)_TimelikeFormatcCs~|t|}t|dkrFtt|t|t|t|}nd}t||jkrbt|d}d||_d ||_ dS)Nr z%{}sz'NaT') rrtr_format_non_natr`rrrE_formatrjust_nat)rrZnon_natr r9r9r=r(s   z_TimelikeFormat.__init__cCstdSr8)NotImplementedErrorr r9r9r=r6sz_TimelikeFormat._format_non_natcCs"t|r|jS|j||SdSr8)rrrrr r9r9r=r:sz_TimelikeFormat.__call__N)rrrrrrr9r9r9r=r'srcs2eZdZd fdd ZfddZdd ZZS) rN same_kindFcs\|dur(|jjdkr$t|jd}nd}|dur4d}||_||_||_||_t|dS)NMr rZnaive) rkindrtimezoneunitcastingr7superr)rrr#r"r$r7 __class__r9r=rBs zDatetimeFormat.__init__cs |jdkr||St|S)NrK)r7rr%rr r&r9r=rUs  zDatetimeFormat.__call__cCsdt||j|j|jdS)N'%s')r#r"r$)rr#r"r$r r9r9r=rZs zDatetimeFormat._format_non_nat)NNrF)rrrrrr __classcell__r9r9r&r=rAs  rc@seZdZddZdS)rcCst|dS)Ni8)rZastyper r9r9r=rbszTimedeltaFormat._format_non_natN)rrrrr9r9r9r=rasrc@s$eZdZddZddZddZdS)SubArrayFormatcKs||_|d|_|d|_dS)Nr.r-)rr.r)rrrdr9r9r=rgs zSubArrayFormat.__init__cCs |j|jkrdnd|_||S)Nrr)rr.r format_array)rrxr9r9r=rlszSubArrayFormat.__call__cst|dkr|Sjrv|jddjkrvfdd|djDjgfdd|j dD}nfdd|D}dd|d S) Nr rrcsg|]}|qSr9r,r:Za_rr9r=rvr?z/SubArrayFormat.format_array..csg|]}|qSr9r-r.r/r9r=rxr?csg|]}|qSr9r-r.r/r9r=r{r?rrCr)r`rurrrvrrW)rrx formattedr9r/r=r,ps zSubArrayFormat.format_arrayN)rrrrrr,r9r9r9r=r+fsr+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 ||_dSr8)format_functions)rr1r9r9r=rszStructuredVoidFormat.__init__cKsXg}|jjD]B}t||fi|}|j|jdkrDt|fi|}||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__. r9)rrrrvr+append)clsrrdr1 field_namerr9r9r=rs  zStructuredVoidFormat.from_datacCsDddt||jD}t|dkr0d|dSdd|SdS)NcSsg|]\}}||qSr9r9)r:fieldrr9r9r=rsz1StructuredVoidFormat.__call__..r z({},)r z({})rC)rr1rtrErW)rrZ str_fieldsr9r9r=rs   zStructuredVoidFormat.__call__N)rrrr r classmethodrrr9r9r9r=rs  rcCst}|ddkr.tjt|fit|S|ddurDi|d<|ddttjt|fi||}|sv|St|}|j ddd|j }t t j|j f}|d |d |d 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. r7rOr6Nrrhr`r(z, dtype=))rjrmrrrget setdefaultrryrreplacerr`rr)rZis_reprrdZval_reprr3Zcls_fqnZ void_dtyper9r9r=_void_scalar_to_strings r<cCsHt|}tddkr&|jtjkr&dS|jdur4dS|js>dS|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) r7rKFN)r`rrjryrUrisnative _typelessdata)rr9r9r=dtype_is_implieds  r?cCst|jtjjkrt|S|jdur,t|St|jtrDdt|S|j }|j s\dt|S|r||d rt| 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 ) ry__repr__r`rrrrrr#rr=isalphaisalnum)rtypenamer9r9r=dtype_short_reprs     rDc Csd|durtd}t|tur(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.Nr2rr r7r8,r7rKr9)r rC)rz [], shape=%sz dtype={})rr rI)rjryrrr?rrrvrrrrErDrtrfindrr#)arrrr0rr class_nameZ skipdtyperrrZarr_strZ dtype_strZ last_line_lenZspacerr9r9r=_array_repr_implementations>      rIcCs|fSr8r9rGrr0rr9r9r=_array_repr_dispatcher7srKcCst||||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. ])' )rIrJr9r9r=r<s-rcCst|trt|St|Sr8)r\bytesrr)r<r9r9r=_guarded_repr_or_strms rMcCsXtddkr*|jdkr*|jjs*t|S|jdkrFttj |dS|||||ddS)zDInternal version of array_str() that allows overriding array2string.r7rKr9rIr) rjrvrrrrrMr`r __getitem__)rxrr0rrr9r9r=_array_str_implementationts   rOcCs|fSr8r9rxrr0rr9r9r=_array_str_dispatchersrQcCst||||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]' )rOrPr9r9r=rs$r __wrapped__)rcCsFtjdtdd|dur6|r(ttdSttdSn t||SdS)a Set a Python function to be used when pretty printing arrays. .. deprecated:: 2.0 Use `np.set_printoptions` instead with a formatter for custom printing of NumPy objects. 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 -------- >>> from numpy._core.arrayprint import set_string_function >>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> 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: >>> 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) >>> set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([0, 1, 2, 3])' z`set_string_function` is deprecated. Use `np.set_printoptions` with a formatter for custom printing NumPy objects. (deprecated in NumPy 2.0)rrrPNr r )rZr[rrset_string_function_default_array_repr_default_array_str)rrr9r9r=rSs: rS) NNNNNNNNNNN) NNNNNNNNNN)r9)r)rIr) NNNNNNNNNNNN)NTr;FNNN)NTTr;FNNN)T)NNN)NNN)NNN)NNN)T)br __all__ __docformat__rr]rX_threadr ImportError _dummy_threadrhr`rr rZumathrrrrrrrrrrrrZ fromnumericrnumericrrrrrr r!r"r#rr$r%rbrZ contextlibrYrjrgrrrocontextmanagerrrwr|rrrrrrrrrrrrrrrrrrrrrrr+rr<rUr>r?rDrIrKrrMrOrQrgetattrZ_array2string_implpartialrUrTrSr9r9r9r=s   $   6A ! ! 2)   7| O Z ! % )! 0   0     (