Esempio n. 1
0
    def fillFormat(self, data):
        import numeric as _nc
        errstate = _nc.seterr(all='ignore')
        try:
            special = isnan(data) | isinf(data) | isna(data)
            special[isna(data)] = False
            valid = not_equal(data, 0) & ~special
            valid[isna(data)] = False
            non_zero = absolute(data.compress(valid))
            if len(non_zero) == 0:
                max_val = 0.
                min_val = 0.
            else:
                max_val = maximum.reduce(non_zero, skipna=True)
                min_val = minimum.reduce(non_zero, skipna=True)
                if max_val >= 1.e8:
                    self.exp_format = True
                if not self.suppress_small and (min_val < 0.0001
                                           or max_val/min_val > 1000.):
                    self.exp_format = True
        finally:
            _nc.seterr(**errstate)

        if self.exp_format:
            self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100
            self.max_str_len = 8 + self.precision
            if self.large_exponent:
                self.max_str_len += 1
            if self.sign:
                format = '%+'
            else:
                format = '%'
            format = format + '%d.%de' % (self.max_str_len, self.precision)
        else:
            format = '%%.%df' % (self.precision,)
            if len(non_zero):
                precision = max([_digits(x, self.precision, format)
                                 for x in non_zero])
            else:
                precision = 0
            precision = min(self.precision, precision)
            self.max_str_len = len(str(int(max_val))) + precision + 2
            if _nc.any(special):
                self.max_str_len = max(self.max_str_len,
                                       len(_nan_str),
                                       len(_inf_str)+1,
                                       len(_na_str))
            if self.sign:
                format = '%#+'
            else:
                format = '%#'
            format = format + '%d.%df' % (self.max_str_len, precision)

        self.special_fmt = '%%%ds' % (self.max_str_len,)
        self.format = format
Esempio n. 2
0
    def fillFormat(self, data):
        import numeric as _nc
        errstate = _nc.seterr(all='ignore')
        try:
            special = isnan(data) | isinf(data) | isna(data)
            special[isna(data)] = False
            valid = not_equal(data, 0) & ~special
            valid[isna(data)] = False
            non_zero = absolute(data.compress(valid))
            if len(non_zero) == 0:
                max_val = 0.
                min_val = 0.
            else:
                max_val = maximum.reduce(non_zero, skipna=True)
                min_val = minimum.reduce(non_zero, skipna=True)
                if max_val >= 1.e8:
                    self.exp_format = True
                if not self.suppress_small and (min_val < 0.0001
                                                or max_val / min_val > 1000.):
                    self.exp_format = True
        finally:
            _nc.seterr(**errstate)

        if self.exp_format:
            self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100
            self.max_str_len = 8 + self.precision
            if self.large_exponent:
                self.max_str_len += 1
            if self.sign:
                format = '%+'
            else:
                format = '%'
            format = format + '%d.%de' % (self.max_str_len, self.precision)
        else:
            format = '%%.%df' % (self.precision, )
            if len(non_zero):
                precision = max(
                    [_digits(x, self.precision, format) for x in non_zero])
            else:
                precision = 0
            precision = min(self.precision, precision)
            self.max_str_len = len(str(int(max_val))) + precision + 2
            if _nc.any(special):
                self.max_str_len = max(self.max_str_len, len(_nan_str),
                                       len(_inf_str) + 1, len(_na_str))
            if self.sign:
                format = '%#+'
            else:
                format = '%#'
            format = format + '%d.%df' % (self.max_str_len, precision)

        self.special_fmt = '%%%ds' % (self.max_str_len, )
        self.format = format
Esempio n. 3
0
def _boolFormatter(x):
    if isna(x):
        return str(x).replace('NA', _na_str, 1)
    elif x:
        return ' True'
    else:
        return 'False'
Esempio n. 4
0
def _boolFormatter(x):
    if isna(x):
        return str(x).replace('NA', _na_str, 1)
    elif x:
        return ' True'
    else:
        return 'False'
Esempio n. 5
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     elif _MININT < x < _MAXINT:
         return self.format % x
     else:
         return "%s" % x
Esempio n. 6
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         r = self.real_format(x.real)
         i = self.imag_format(x.imag)
         return r + i + 'j'
Esempio n. 7
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     elif _MININT < x < _MAXINT:
         return self.format % x
     else:
         return "%s" % x
Esempio n. 8
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         r = self.real_format(x.real)
         i = self.imag_format(x.imag)
         return r + i + 'j'
Esempio n. 9
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         return "'%s'" % datetime_as_string(x,
                                            unit=self.unit,
                                            timezone=self.timezone,
                                            casting=self.casting)
Esempio n. 10
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         return "'%s'" % datetime_as_string(x,
                                     unit=self.unit,
                                     timezone=self.timezone,
                                     casting=self.casting)
Esempio n. 11
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         r = self.real_format(x.real, strip_zeros=False)
         i = self.imag_format(x.imag, strip_zeros=False)
         if not self.imag_format.exp_format:
             z = i.rstrip('0')
             i = z + 'j' + ' '*(len(i)-len(z))
         else:
             i = i + 'j'
         return r + i
Esempio n. 12
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         r = self.real_format(x.real, strip_zeros=False)
         i = self.imag_format(x.imag, strip_zeros=False)
         if not self.imag_format.exp_format:
             z = i.rstrip('0')
             i = z + 'j' + ' ' * (len(i) - len(z))
         else:
             i = i + 'j'
         return r + i
Esempio n. 13
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     elif isnan(x):
         if self.sign:
             return '+' + _nan_str
         else:
             return ' ' + _nan_str
     elif isinf(x):
         if x > 0:
             if self.sign:
                 return '+' + _inf_str
             else:
                 return ' ' + _inf_str
         else:
             return '-' + _inf_str
     elif x >= 0:
         if self.sign:
             return '+' + format_longfloat(x, self.precision)
         else:
             return ' ' + format_longfloat(x, self.precision)
     else:
         return format_longfloat(x, self.precision)
Esempio n. 14
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     elif isnan(x):
         if self.sign:
             return '+' + _nan_str
         else:
             return ' ' + _nan_str
     elif isinf(x):
         if x > 0:
             if self.sign:
                 return '+' + _inf_str
             else:
                 return ' ' + _inf_str
         else:
             return '-' + _inf_str
     elif x >= 0:
         if self.sign:
             return '+' + format_longfloat(x, self.precision)
         else:
             return ' ' + format_longfloat(x, self.precision)
     else:
         return format_longfloat(x, self.precision)
Esempio n. 15
0
    def __call__(self, x, strip_zeros=True):
        import numeric as _nc
        err = _nc.seterr(invalid='ignore')
        try:
            if isna(x):
                return self.special_fmt % (str(x).replace('NA', _na_str, 1),)
            elif isnan(x):
                if self.sign:
                    return self.special_fmt % ('+' + _nan_str,)
                else:
                    return self.special_fmt % (_nan_str,)
            elif isinf(x):
                if x > 0:
                    if self.sign:
                        return self.special_fmt % ('+' + _inf_str,)
                    else:
                        return self.special_fmt % (_inf_str,)
                else:
                    return self.special_fmt % ('-' + _inf_str,)
        finally:
            _nc.seterr(**err)

        s = self.format % x
        if self.large_exponent:
            # 3-digit exponent
            expsign = s[-3]
            if expsign == '+' or expsign == '-':
                s = s[1:-2] + '0' + s[-2:]
        elif self.exp_format:
            # 2-digit exponent
            if s[-3] == '0':
                s = ' ' + s[:-3] + s[-2:]
        elif strip_zeros:
            z = s.rstrip('0')
            s = z + ' '*(len(s)-len(z))
        return s
Esempio n. 16
0
    def __call__(self, x, strip_zeros=True):
        import numeric as _nc
        err = _nc.seterr(invalid='ignore')
        try:
            if isna(x):
                return self.special_fmt % (str(x).replace('NA', _na_str, 1), )
            elif isnan(x):
                if self.sign:
                    return self.special_fmt % ('+' + _nan_str, )
                else:
                    return self.special_fmt % (_nan_str, )
            elif isinf(x):
                if x > 0:
                    if self.sign:
                        return self.special_fmt % ('+' + _inf_str, )
                    else:
                        return self.special_fmt % (_inf_str, )
                else:
                    return self.special_fmt % ('-' + _inf_str, )
        finally:
            _nc.seterr(**err)

        s = self.format % x
        if self.large_exponent:
            # 3-digit exponent
            expsign = s[-3]
            if expsign == '+' or expsign == '-':
                s = s[1:-2] + '0' + s[-2:]
        elif self.exp_format:
            # 2-digit exponent
            if s[-3] == '0':
                s = ' ' + s[:-3] + s[-2:]
        elif strip_zeros:
            z = s.rstrip('0')
            s = z + ' ' * (len(s) - len(z))
        return s
Esempio n. 17
0
def array2string(a,
                 max_line_width=None,
                 precision=None,
                 suppress_small=None,
                 separator=' ',
                 prefix="",
                 style=repr,
                 formatter=None):
    """
    Return a string representation of an array.

    Parameters
    ----------
    a : ndarray
        Input array.
    max_line_width : int, optional
        The maximum number of columns the string should span. Newline
        characters splits the string appropriately after array elements.
    precision : int, optional
        Floating point precision. Default is the current printing
        precision (usually 8), which can be altered using `set_printoptions`.
    suppress_small : bool, optional
        Represent very small numbers as zero. A number is "very small" if it
        is smaller than the current printing precision.
    separator : str, optional
        Inserted between elements.
    prefix : str, optional
        An array is typically printed as::

          'prefix(' + array2string(a) + ')'

        The length of the prefix string is used to align the
        output correctly.
    style : function, optional
        A function that accepts an ndarray and returns a string.  Used only
        when the shape of `a` is equal to ``()``, i.e. for 0-D arrays.
    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
            - 'numpy_str' : 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'

    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.

    Examples
    --------
    >>> x = np.array([1e-16,1,2,3])
    >>> print 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)})
    '[0x0L 0x1L 0x2L]'

    """

    if a.shape == ():
        x = a.item()
        if isna(x):
            lst = str(x).replace('NA', _na_str, 1)
        else:
            try:
                lst = a._format(x)
                msg = "The `_format` attribute is deprecated in Numpy " \
                      "2.0 and will be removed in 2.1. Use the " \
                      "`formatter` kw instead."
                import warnings
                warnings.warn(msg, DeprecationWarning)
            except AttributeError:
                if isinstance(x, tuple):
                    x = _convert_arrays(x)
                lst = style(x)
    elif reduce(product, a.shape) == 0:
        # treat as a null array if any of shape elements == 0
        lst = "[]"
    else:
        lst = _array2string(a,
                            max_line_width,
                            precision,
                            suppress_small,
                            separator,
                            prefix,
                            formatter=formatter)
    return lst
Esempio n. 18
0
def repr_format(x):
    if isna(x):
        return str(x).replace('NA', _na_str, 1)
    else:
        return repr(x)
Esempio n. 19
0
def repr_format(x):
    if isna(x):
        return str(x).replace('NA', _na_str, 1)
    else:
        return repr(x)
Esempio n. 20
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         return self.format % x.astype('i8')
Esempio n. 21
0
 def __call__(self, x):
     if isna(x):
         return str(x).replace('NA', _na_str, 1)
     else:
         return self.format % x.astype('i8')
Esempio n. 22
0
def array2string(a, max_line_width=None, precision=None,
                 suppress_small=None, separator=' ', prefix="",
                 style=repr, formatter=None):
    """
    Return a string representation of an array.

    Parameters
    ----------
    a : ndarray
        Input array.
    max_line_width : int, optional
        The maximum number of columns the string should span. Newline
        characters splits the string appropriately after array elements.
    precision : int, optional
        Floating point precision. Default is the current printing
        precision (usually 8), which can be altered using `set_printoptions`.
    suppress_small : bool, optional
        Represent very small numbers as zero. A number is "very small" if it
        is smaller than the current printing precision.
    separator : str, optional
        Inserted between elements.
    prefix : str, optional
        An array is typically printed as::

          'prefix(' + array2string(a) + ')'

        The length of the prefix string is used to align the
        output correctly.
    style : function, optional
        A function that accepts an ndarray and returns a string.  Used only
        when the shape of `a` is equal to ``()``, i.e. for 0-D arrays.
    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
            - 'numpy_str' : 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'

    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.

    Examples
    --------
    >>> x = np.array([1e-16,1,2,3])
    >>> print 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)})
    '[0x0L 0x1L 0x2L]'

    """

    if a.shape == ():
        x = a.item()
        if isna(x):
            lst = str(x).replace('NA', _na_str, 1)
        else:
            try:
                lst = a._format(x)
                msg = "The `_format` attribute is deprecated in Numpy " \
                      "2.0 and will be removed in 2.1. Use the " \
                      "`formatter` kw instead."
                import warnings
                warnings.warn(msg, DeprecationWarning)
            except AttributeError:
                if isinstance(x, tuple):
                    x = _convert_arrays(x)
                lst = style(x)
    elif reduce(product, a.shape) == 0:
        # treat as a null array if any of shape elements == 0
        lst = "[]"
    else:
        lst = _array2string(a, max_line_width, precision, suppress_small,
                            separator, prefix, formatter=formatter)
    return lst