当前位置: 首页>>代码示例>>Python>>正文


Python numpy.get_printoptions函数代码示例

本文整理汇总了Python中numpy.get_printoptions函数的典型用法代码示例。如果您正苦于以下问题:Python get_printoptions函数的具体用法?Python get_printoptions怎么用?Python get_printoptions使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_printoptions函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_precision

def test_precision():
    """test various values for float_precision."""
    f = PlainTextFormatter()
    nt.assert_equal(f(pi), repr(pi))
    f.float_precision = 0
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equal(po['precision'], 0)
    nt.assert_equal(f(pi), '3')
    f.float_precision = 2
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equal(po['precision'], 2)
    nt.assert_equal(f(pi), '3.14')
    f.float_precision = '%g'
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equal(po['precision'], 2)
    nt.assert_equal(f(pi), '3.14159')
    f.float_precision = '%e'
    nt.assert_equal(f(pi), '3.141593e+00')
    f.float_precision = ''
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equal(po['precision'], 8)
    nt.assert_equal(f(pi), repr(pi))
开发者ID:mattvonrocketstein,项目名称:smash,代码行数:26,代码来源:test_formatters.py

示例2: magic_push_print

def magic_push_print(self, arg):
    """ Set numpy array printing options by pushing onto a stack.

"""
    try:
        import numpy
    except ImportError:
        raise UsageError("could not import numpy.")
    args = parse_argstring(magic_push_print, arg)
    kwds = {}
    if args.precision is not None:
        kwds['precision'] = args.precision
    if args.threshold is not None:
        if args.threshold == 0:
            args.threshold = sys.maxint
        kwds['threshold'] = args.threshold
    if args.edgeitems is not None:
        kwds['edgeitems'] = args.edgeitems
    if args.linewidth is not None:
        kwds['linewidth'] = args.linewidth
    if args.suppress is not None:
        kwds['suppress'] = args.suppress
    if args.nanstr is not None:
        kwds['nanstr'] = args.nanstr
    if args.infstr is not None:
        kwds['infstr'] = args.infstr

    old_options = numpy.get_printoptions()
    numpy.set_printoptions(**kwds)
    stack = getattr(self, '_numpy_printoptions_stack', [])
    stack.append(old_options)
    self._numpy_printoptions_stack = stack
    if not args.quiet:
        print_numpy_printoptions(numpy.get_printoptions())
开发者ID:rkern,项目名称:kernmagic,代码行数:34,代码来源:mymagics.py

示例3: test_ctx_mgr_restores

 def test_ctx_mgr_restores(self):
     # test that print options are actually restrored
     opts = np.get_printoptions()
     with np.printoptions(precision=opts['precision'] - 1,
                          linewidth=opts['linewidth'] - 4):
         pass
     assert_equal(np.get_printoptions(), opts)
开发者ID:Nodd,项目名称:numpy,代码行数:7,代码来源:test_arrayprint.py

示例4: test_precision

def test_precision():
    """test various values for float_precision."""
    f = PlainTextFormatter()
    nt.assert_equals(f(pi), repr(pi))
    f.float_precision = 0
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equals(po["precision"], 0)
    nt.assert_equals(f(pi), "3")
    f.float_precision = 2
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equals(po["precision"], 2)
    nt.assert_equals(f(pi), "3.14")
    f.float_precision = "%g"
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equals(po["precision"], 2)
    nt.assert_equals(f(pi), "3.14159")
    f.float_precision = "%e"
    nt.assert_equals(f(pi), "3.141593e+00")
    f.float_precision = ""
    if numpy:
        po = numpy.get_printoptions()
        nt.assert_equals(po["precision"], 8)
    nt.assert_equals(f(pi), repr(pi))
开发者ID:chensunn,项目名称:PortableJekyll,代码行数:26,代码来源:test_formatters.py

示例5: _get_suppress

    def _get_suppress(self):
        """
        Gets the current suppression settings (from numpy).
        """

        suppress = np.get_printoptions()['suppress']
        suppress_thresh = 0.1 ** (np.get_printoptions()['precision'] + 0.5)
        return (suppress, suppress_thresh)
开发者ID:dstahlke,项目名称:qitensor,代码行数:8,代码来源:arrayformatter.py

示例6: test_ctx_mgr_exceptions

 def test_ctx_mgr_exceptions(self):
     # test that print options are restored even if an exeption is raised
     opts = np.get_printoptions()
     try:
         with np.printoptions(precision=2, linewidth=11):
             raise ValueError
     except ValueError:
         pass
     assert_equal(np.get_printoptions(), opts)
开发者ID:Nodd,项目名称:numpy,代码行数:9,代码来源:test_arrayprint.py

示例7: testTensorStrReprObeyNumpyPrintOptions

  def testTensorStrReprObeyNumpyPrintOptions(self):
    orig_threshold = np.get_printoptions()["threshold"]
    orig_edgeitems = np.get_printoptions()["edgeitems"]
    np.set_printoptions(threshold=2, edgeitems=1)

    t = _create_tensor(np.arange(10, dtype=np.int32))
    self.assertIn("[0 ..., 9]", str(t))
    self.assertIn("[0, ..., 9]", repr(t))

    # Clean up: reset to previous printoptions.
    np.set_printoptions(threshold=orig_threshold, edgeitems=orig_edgeitems)
开发者ID:marcomarchesi,项目名称:tensorflow,代码行数:11,代码来源:tensor_test.py

示例8: testTensorStrReprObeyNumpyPrintOptions

  def testTensorStrReprObeyNumpyPrintOptions(self):
    orig_threshold = np.get_printoptions()["threshold"]
    orig_edgeitems = np.get_printoptions()["edgeitems"]
    np.set_printoptions(threshold=2, edgeitems=1)

    t = _create_tensor(np.arange(10, dtype=np.int32))
    self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", str(t)))
    self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", repr(t)))

    # Clean up: reset to previous printoptions.
    np.set_printoptions(threshold=orig_threshold, edgeitems=orig_edgeitems)
开发者ID:adit-chandra,项目名称:tensorflow,代码行数:11,代码来源:tensor_test.py

示例9: __repr__

    def __repr__(self):
        if len(self) > np.get_printoptions()['threshold']:
            # Show only the first and last edgeitems.
            edgeitems = np.get_printoptions()['edgeitems']
            data = str(list(self[:edgeitems]))[:-1]
            data += ", ..., "
            data += str(list(self[-edgeitems:]))[1:]
        else:
            data = str(list(self))

        return "{name}({data})".format(name=self.__class__.__name__,
                                       data=data)
开发者ID:arokem,项目名称:nibabel,代码行数:12,代码来源:array_sequence.py

示例10: __repr__

    def __repr__(self):
        prefixstr = "    "

        if self._values.shape == ():
            v = [tuple([self._values[nm] for nm in self._values.dtype.names])]
            v = np.array(v, dtype=self._values.dtype)
        else:
            v = self._values

        names = self._values.dtype.names
        precision = np.get_printoptions()["precision"]
        fstyle = functools.partial(_fstyle, precision)
        format_val = lambda val: np.array2string(val, style=fstyle)
        formatter = {"numpystr": lambda x: "({0})".format(", ".join(format_val(x[name]) for name in names))}

        if NUMPY_LT_1P7:
            arrstr = np.array2string(v, separator=", ", prefix=prefixstr)

        else:
            arrstr = np.array2string(v, formatter=formatter, separator=", ", prefix=prefixstr)

        if self._values.shape == ():
            arrstr = arrstr[1:-1]

        unitstr = ("in " + self._unitstr) if self._unitstr else "[dimensionless]"
        return "<{0} ({1}) {2:s}\n{3}{4}>".format(
            self.__class__.__name__, ", ".join(self.components), unitstr, prefixstr, arrstr
        )
开发者ID:n0d,项目名称:astropy,代码行数:28,代码来源:representation.py

示例11: print_array

def print_array(x, debug=False, **kwargs):
    opt = np.get_printoptions()
    ndigits = int(np.log10(np.nanmax(x))) + 2

    if 'precision' in kwargs:
        nprec = kwargs['precision']
    else:
        nprec = 3

    if 'formatter' not in kwargs:
        if issubclass(x.dtype.type, np.int):
            ff = '{:%dd}' % (ndigits)
            kwargs['formatter'] = {'int': ff.format}
        else:
            ff = '{:%d.%df}' % (ndigits + nprec, nprec)
            kwargs['formatter'] = {'float': ff.format}

    if debug:
        print nprec, ndigits, kwargs

    np.set_printoptions(**kwargs)
    if isinstance(x, np.ndarray):
        if len(x.shape) > 1:
            _print_helper(x)
        else:
            print(x)
    np.set_printoptions(**opt)
开发者ID:MBlaschek,项目名称:radiosonde,代码行数:27,代码来源:support.py

示例12: __call__

    def __call__(self, report_folder, connection_holder, dsg_targets):
        """ Convert synaptic matrix for every application edge.
        """

        # Update the print options to display everything
        print_opts = numpy.get_printoptions()
        numpy.set_printoptions(threshold=numpy.nan)

        if dsg_targets is None:
            raise SynapticConfigurationException(
                "dsg_targets should not be none, used as a check for "
                "connection holder data to be generated")

        # generate folder for synaptic reports
        top_level_folder = os.path.join(report_folder, _DIRNAME)
        if not os.path.exists(top_level_folder):
            os.mkdir(top_level_folder)

        # create progress bar
        progress = ProgressBar(connection_holder.keys(),
                               "Generating synaptic matrix reports")

        # for each application edge, write matrix in new file
        for edge, _ in progress.over(connection_holder.keys()):
            # only write matrix's for edges which have matrix's
            if isinstance(edge, ProjectionApplicationEdge):
                # figure new file name
                file_name = os.path.join(
                    top_level_folder, _TMPL_FILENAME.format(edge.label))
                self._write_file(file_name, connection_holder, edge)

        # Reset the print options
        numpy.set_printoptions(**print_opts)
开发者ID:SpiNNakerManchester,项目名称:sPyNNaker,代码行数:33,代码来源:spynnaker_synaptic_matrix_report.py

示例13: linprog_verbose_callback

def linprog_verbose_callback(xk, **kwargs):
    """
    This is a sample callback for use with linprog, demonstrating the callback interface.
    This callback produces detailed output to sys.stdout before each iteration and after
    the final iteration of the simplex algorithm.

    Parameters
    ----------
    xk : array_like
        The current solution vector.
    **kwargs : dict
        A dictionary containing the following parameters:

        tableau : array_like
            The current tableau of the simplex algorithm.  Its structure is defined in _solve_simplex.
        phase : int
            The current Phase of the simplex algorithm (1 or 2)
        iter : int
            The current iteration number.
        pivot : tuple(int, int)
            The index of the tableau selected as the next pivot, or nan if no pivot exists
        basis : array(int)
            A list of the current basic variables.  Each element contains the name of a basic variable and
            its value.
        complete : bool
            True if the simplex algorithm has completed (and this is the final call to callback), otherwise False.
    """
    tableau = kwargs["tableau"]
    iter = kwargs["iter"]
    pivrow, pivcol = kwargs["pivot"]
    phase = kwargs["phase"]
    basis = kwargs["basis"]
    complete = kwargs["complete"]

    saved_printoptions = np.get_printoptions()
    np.set_printoptions(linewidth=500,
                        formatter={'float':lambda x: "{: 12.4f}".format(x)})
    if complete:
        print("--------- Iteration Complete - Phase {:d} -------\n".format(phase))
        print("Tableau:")
    elif iter == 0:
        print("--------- Initial Tableau - Phase {:d} ----------\n".format(phase))

    else:
        print("--------- Iteration {:d}  - Phase {:d} --------\n".format(iter, phase))
        print("Tableau:")

    if iter >= 0:
        print("" + str(tableau) + "\n")
        if not complete:
            print("Pivot Element: T[{:.0f}, {:.0f}]\n".format(pivrow, pivcol))
        print("Basic Variables:", basis)
        print()
        print("Current Solution:")
        print("x = ", xk)
        print()
        print("Current Objective Value:")
        print("f = ", -tableau[-1, -1])
        print()
    np.set_printoptions(**saved_printoptions)
开发者ID:jabooth,项目名称:scipy,代码行数:60,代码来源:_linprog.py

示例14: print_table

 def print_table(self):
     '''Print a table of probabilities at each SNP.'''
     options = np.get_printoptions()
     np.set_printoptions(precision=3, suppress=True, threshold=np.nan, linewidth=200)
     print 'lambda = %s, Delta = %s, eps = %.1e' % (self.lam, repr(self.Delta)[6:-1], self.e)
     print 'Viterbi path (frame SNPs): ' + ' -> '.join(map(lambda x: '%d (%d-%d)' % (x[0], x[1][0], x[1][1]),
                                               itemutil.groupby_with_range(self.Q_star + 1)))
     print 'Viterbi path (SNPs):       ' + ' -> '.join(map(lambda x: '%d (%d-%d)' % (x[0], self.snps[x[1][0]], self.snps[x[1][1]]),
                                               itemutil.groupby_with_range(self.Q_star + 1)))
     print '    %-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s' % \
     ('t', 'SNP#', 'Obs', 'G1', 'G2', 'lam*dx', 'p',
      'Gam1', 'Gam2', 'Gam3', 'Gam4', 'Gam5', 'Gam6', 'Gam7', 'Gam8', 'Gam9',
      'p(IBD)', 'Viterbi', 'IBD?')
     print np.concatenate((np.arange(len(self.x))[np.newaxis].transpose(),
                           self.snps[np.newaxis].transpose(),
                           self.Obs[np.newaxis].transpose(),
                           np.array([ProbIbdHmmCalculator._T_STATE_G[t][0] for t in self.Obs])[np.newaxis].transpose(),
                           np.array([ProbIbdHmmCalculator._T_STATE_G[t][1] for t in self.Obs])[np.newaxis].transpose(),
                           np.concatenate((self.lam_x, [0]))[np.newaxis].transpose(),
                           self.p[np.newaxis].transpose(),
                           self.Gamma.transpose(),
                           self.p_ibd_gamma[np.newaxis].transpose(),
                           (self.Q_star + 1)[np.newaxis].transpose(),
                           self.p_ibd_viterbi[np.newaxis].transpose()
                           ), axis=1)
     util.set_printoptions(options)
开发者ID:orenlivne,项目名称:ober,代码行数:26,代码来源:ibd_hmm.py

示例15: printoptions

def printoptions(*args, **kwargs):
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    try:
        yield
    finally:
        np.set_printoptions(**original)
开发者ID:HounD,项目名称:IDNNs,代码行数:7,代码来源:mutual_info_estimation.py


注:本文中的numpy.get_printoptions函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。