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


Python numpy.set_string_function函数代码示例

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


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

示例1: process_Iqxy_data

def process_Iqxy_data(file_content):
    """
        Process the content of an I(qx,qy) file and return a string representation
        of the data that we can ship to the client for plotting.
        @param file_content: content of the data file
    """
    fd = tempfile.NamedTemporaryFile()
    fd.write(file_content)
    fd.seek(0)
    
    numpy.set_printoptions(threshold='nan', nanstr='0', infstr='0')
    fd = h5py.File(fd.name, 'r')
    g = fd['mantid_workspace_1']
    y = g['workspace']['axis1']
    x = g['workspace']['axis2']
    values = g['workspace']['values']
    z_max = numpy.amax(values)
    numpy.set_string_function( lambda x: '['+','.join(map(lambda y:'['+','.join(map(lambda z: "%.4g" % z,y))+']',x))+']' )
    data_str_2d = values[:].__repr__()
    numpy.set_string_function( lambda x: '['+','.join(map(lambda z: "%.4g" % z,x))+']' )

    y_str = y[:].__repr__()
    x_str = x[:].__repr__()
    return data_str_2d, x_str, y_str, 0.0, z_max
        
开发者ID:serena617,项目名称:reduction_service,代码行数:24,代码来源:view_util.py

示例2: DisplaySkillScores

def DisplaySkillScores(skillScores, skillScoreName) :
    """
    Display the skill score results in a neat manner.

    Note, this function messes around with the formatting options
    of printing numpy arrays.  It does restore the settings back to
    the numpy defaults, but if you had your own formatting specified
    before calling this function, you will need to reset it.
    """

    np.set_string_function(
            lambda x: '\n'.join(['  '.join(["% 11.8f" % val for val in row])
                                                            for row in x]),
            repr=True)

    # Print the last eleven characters of each trackrun name for
    # the column labels.
    print '  '.join(["%11.11s" % tracker[-11:] for
                     tracker in skillScores.label[-1]])

    print repr(skillScores.x)

    print "-" * (11*skillScores.shape[1] + 2*(skillScores.shape[1] - 1))

    # Resetting back to how it was
    np.set_string_function(None, repr=True)
开发者ID:BVRoot,项目名称:ZigZag,代码行数:26,代码来源:AnalyzeTracking.py

示例3: simulation

  def simulation(self, N = 50000):
    import pandas
    import scikits.statsmodels.tsa.api
    np.set_string_function(None)
     
    nSims = 1
    
    logger.debug('\n\n--------- SIMULATION---------\n\n')
    
    logger.debug('T = %d\n' % N)
    
    cumTransMatrix = np.cumsum(self.T, 1)
    
    varSim = np.zeros( (N, self.vars ) )
    shocks = np.zeros( (N), dtype = int )
    
    shocks[0] = 1
    
    varSim[0, :] = self.S[shocks[0], :]
    
    lastShock = 1
    for t in range(1, N):
      shockR = np.random.random_sample()
      itemindex = np.where(shockR < cumTransMatrix[lastShock, :])
      shock = itemindex[0][0]
      shocks[t] = shock
      for ixVar in range(self.vars):
        varSim[t, ixVar] = self.S[shock, ixVar]
      lastShock = shock
      
    index = np.arange(N)
    varSim = pandas.DataFrame(data = varSim, index = index, columns = map(str, range(self.vars)))
    logger.debug(varSim)
    
    logger.debug('\nUnconditional means(E)')
    logger.debug(varSim.mean())
    logger.debug('\nUnconditional std')
    logger.debug(varSim.std())
    logger.debug('\nUnconditional skewness')
    logger.debug(varSim.skew())
    try: 
      logger.debug('\nUnconditional correlation')
      logger.debug(varSim.corr())
    except: 
      pass
    
    model = scikits.statsmodels.tsa.api.VAR(varSim)
#    model = scikits.statsmodels.tsa.vector_ar.var_model.VAR(varSim)
    results = model.fit(1)
    Theta = results.params[1:,:]
    logger.debug('\n Persistence')
    logger.debug(Theta)
    
    logger.debug('done with simulation')
    
    return varSim, Theta
开发者ID:TissueMAPS,项目名称:gc3pie,代码行数:56,代码来源:MkovM.py

示例4: _install

def _install():
    import io
    import numpy as np
    from IPython import get_ipython
    from IPython.core import magic
    from highlighter import HighlightTextFormatter
    ip = get_ipython()

    ip.display_formatter.formatters[
        'text/plain'] = HighlightTextFormatter(config=ip.config)

    import ipython_autocd
    ipython_autocd.register()

    import lambda_filter
    lambda_filter.register()

    @magic.register_line_magic
    def run_cython(args):
        """Run a Cython file using %%cython magic."""
        args = magic.arg_split(args, posix=True)
        filename = args.pop()
        if '--force' not in args:
            args.append('--force')
        ip = get_ipython()
        ip.extension_manager.load_extension('cython')
        with io.open(filename, 'r', encoding='utf-8') as f:
            ip.run_cell_magic('cython', ' '.join(args), f.read())

    @magic.register_line_cell_magic
    def create(line='', cell=None):
        """Start a plotinteract session from user namespace data."""
        from plottools import create, dataobj
        ip = get_ipython()
        if not cell:
            cell = line
            line = ''
        args = ip.ev('dict({})'.format(line))
        objs = (eval('dataobj({})'.format(line),
                     ip.user_global_ns, dict(dataobj=dataobj))
                for line in cell.splitlines())
        create(*objs, **args)

    def arraystr(a, max_line_width=None, precision=None, suppress_small=None):
        """Separate values with a comma in array2string."""
        return np.array2string(a, max_line_width,
                               precision, suppress_small,
                               separator=', ', prefix="", style=str)\
            .replace('..., ', '..., ' if PY3 else 'Ellipsis, ')

    np.set_string_function(arraystr, repr=False)
    if not PY3:
        np.set_string_function(arraystr)
    np.ma.masked_print_option.set_display("masked")
开发者ID:pbiczo,项目名称:vimconfig,代码行数:54,代码来源:ipython_config.py

示例5: __str__

 def __str__(self):
     np.set_string_function(format_array, repr=False)
     s = '{'
     for k in sorted(self.keys()):
         v = self[k]
         if v.ndim > 1:
             v = v.ravel()
         if s == '{':
             s += '{}: {}'.format(k, v)
         else:
             s += ', {}: {}'.format(k, v)
     s += '}'
     np.set_string_function(None, repr=False)
     return s
开发者ID:JuliaBru,项目名称:pymor,代码行数:14,代码来源:base.py

示例6: __str__

    def __str__(self):

        def format_array(array):
            def format_element(e):
                if e > 1e15:
                    return '%(n).2e' % {'n': e}
                elif e == np.floor(e):
                    return '%(n).0f' % {'n': e}
                elif e - np.floor(e) > 0.01 or e < 1000:
                    return '%(n).2f' % {'n': e}
                else:
                    return '%(n).2e' % {'n': e}

            if array.ndim == 0:
                return str(array.item())
            elif len(array) == 0:
                return ''
            elif len(array) == 1:
                if defaults.compact_print:
                    return '[' + format_element(array[0]) + ']'
                else:
                    return '[{}]'.format(array[0])
            s = '['
            for ii in np.arange(len(array) - 1):
                if defaults.compact_print:
                    s += format_element(array[ii]) + ', '
                else:
                    s += '{}, '.format(array[ii])
            if defaults.compact_print:
                s += format_element(array[-1]) + ']'
            else:
                s += '{}]'.format(array[-1])
            return s

        np.set_string_function(format_array, repr=False)
        if self.__keys is None:
            self.__keys = sorted(self.keys())
        s = '{'
        for k in self.__keys:
            v = self[k]
            if v.ndim > 1:
                v = v.ravel()
            if s == '{':
                s += '{}: {}'.format(k, v)
            else:
                s += ', {}: {}'.format(k, v)
        s += '}'
        np.set_string_function(None, repr=False)
        return s
开发者ID:BarbaraV,项目名称:pymor,代码行数:49,代码来源:base.py

示例7: test_set_string_function

    def test_set_string_function(self):
        a = np.array([1])
        np.set_string_function(lambda x: "FOO", repr=True)
        assert_equal(repr(a), "FOO")
        np.set_string_function(None, repr=True)
        assert_equal(repr(a), "array([1])")

        np.set_string_function(lambda x: "FOO", repr=False)
        assert_equal(str(a), "FOO")
        np.set_string_function(None, repr=False)
        assert_equal(str(a), "[1]")
开发者ID:bogdangherca,项目名称:numpy,代码行数:11,代码来源:test_numeric.py

示例8: html

    def html(self,css=None) :
        """Create an HTML representation of the table

           Parameters
           ----------
           css : str
               A string that may refer to a CSS or style parameter. This can be used for special
               formatting of the table, e.g. striping. Default: No extra formatting.


           Returns
           -------
           string
               HTML <table> representation.
        """
        if css:
            tablestr = '<h3>%s</h3>\n<table %s><thead><tr>' % (self.description,css)
        else:
            tablestr = '<h3>%s</h3>\n<table><thead><tr>' % self.description

        for h in self.columns:
            tablestr = tablestr + '<th>%s</th>' % h
        tablestr = tablestr + '</tr>\n'
        for u in self.units:
            tablestr = tablestr + '<th>[%s]</th>' % u
        tablestr = tablestr + '</tr></thead>\n<tbody>'
        np.set_string_function(None)
        np.set_printoptions(
              threshold = None,
              nanstr = 'NaN',
              infstr = 'Inf',
              formatter={'float' : '<td>{:.3E}</td>'.format,
                         #'str_kind'   : '<td>{}</td>'.format
                         'str_kind'   : lambda x: self._formatcell(x)
                        })
        for row in self.data:
            #strip beginning and ending [,] from string.
            rowstr = str(row)[1:-1]
            tablestr = tablestr + '<tr>'+rowstr+'</tr>\n'
        tablestr = tablestr + '</tbody></table>\n'
        np.set_printoptions(formatter=None)
        return tablestr
开发者ID:teuben,项目名称:admit,代码行数:42,代码来源:Table.py

示例9: DisplayTableAnalysis

def DisplayTableAnalysis(figTitles, plotLabels, tickLabels,
                         meanSkills, skills_ci_upper, skills_ci_lower) :
    np.set_string_function(
            lambda x: '  '.join(["% 8.4f" % val for val in x]),
            repr=True)

    for figIndex, title in enumerate(figTitles) :
        print "%50s" % title

        print " " * 10,
        print " ".join(["%9s"] * len(tickLabels)) % tuple(tickLabels)
        print "-" * (11 + 10 * len(tickLabels))

        for plotIndex, label in enumerate(plotLabels) :
            print ("%10s|" % label),
            print repr(meanSkills[:, figIndex, plotIndex])


    # Restore the formatting state to the default
    np.set_string_function(None, repr=True)
开发者ID:BVRoot,项目名称:ZigZag,代码行数:20,代码来源:MultiScenarioAnalysis.py

示例10: __init__

    def __init__(self, *args, **kwargs):
        super(AD, self).__init__(*args, **kwargs)
        self.__dict__ = self

# ipshell = InteractiveShellEmbed()
# ipshell.magic('%load_ext autoreload')

# Add array shape to Numpy's repr


def my_array_repr(arr):
    orig_str = array_repr(arr)
    return orig_str + '\n\nShape: ' + str(arr.shape) + '\n\n\n'


np.set_string_function(my_array_repr)


def fromfile(filename):
    return np.fromfile(filename, '>d')


def equal(ax=None):
    ax = plt.gca() if ax is None else ax
    ax.set_aspect('equal', 'box-forced')


def doc(fn):
    oinfo = Inspector().info(fn)
    url = sphinxify.rich_repr(oinfo)
    try:
开发者ID:hugke729,项目名称:dotfiles,代码行数:31,代码来源:ipython_startup.py

示例11: map

import Sofa
from SofaPython import Quaternion as quat

import numpy as np

np.set_string_function( lambda x: ' '.join( map(str, x)), repr = False )

import path
import tool

# rigid body operations
def id():
    res = np.zeros(7)
    res[-1] = 1
    return res

def inv(x):
    res = np.zeros(7)

    res[3:] = quat.conj(x[3:])
    res[:3] = -quat.rotate(res[3:], x[:3])
    
    return res

def prod(x, y):
    print x.inv()
    res = np.zeros(7)

    res[:3] = x[:3] + quat.rotate(x[3:], y[:3])
    res[3:] = quat.prod(x[3:], y[3:])
开发者ID:151706061,项目名称:sofa,代码行数:30,代码来源:rigid.py

示例12: get_dummy_data

def get_dummy_data(request, job_id):
    """
        Create a dummy job and plot data
        @param request: request object
        @param job_id: RemoteJob pk
    """
    try:
        remote_job = RemoteJob.objects.get(remote_id=job_id)
    except:
        eqsans = Instrument.objects.get(name='eqsans')
        reduction = ReductionProcess(instrument=eqsans,
                                     name='Dummy job',
                                     owner=request.user,
                                     data_file='/tmp/dummy.nxs')
        reduction.save()
        try:
            transaction = Transaction.objects.get(trans_id=-1)
        except:
            transaction = Transaction(trans_id=-1,
                                      owner=request.user,
                                      directory='/tmp')
            transaction.save()
        remote_job = RemoteJob(reduction=reduction,
                              remote_id='-1',
                              transaction=transaction)
        remote_job.save()
        
    breadcrumbs = "<a href='%s'>home</a>" % reverse(settings.LANDING_VIEW)
    breadcrumbs += " &rsaquo; <a href='%s'>eqsans reduction</a>" % reverse('eqsans.views.reduction_home')
    breadcrumbs += " &rsaquo; <a href='%s'>jobs</a>" % reverse('eqsans.views.reduction_jobs')
    breadcrumbs += " &rsaquo; dummy job"

    template_values = {'remote_job': remote_job,
                       'parameters': remote_job.reduction.get_data_dict(),
                       'reduction_id': remote_job.reduction.id,
                       'breadcrumbs': breadcrumbs,
                       'back_url': request.path}
    template_values = remote.view_util.fill_job_dictionary(request, job_id, **template_values)
    template_values = users.view_util.fill_template_values(request, **template_values)
    template_values = remote.view_util.fill_template_values(request, **template_values)
    
    # Go through the files and find data to plot
    f = os.path.join(os.path.split(__file__)[0],'..','plotting','data','4065_Iq.txt')
                
    # Do we read this data already?
    plot_object = remote_job.get_first_plot(filename='4065_Iq.txt', owner=request.user)
    if plot_object is not None and plot_object.first_data_layout() is not None:
        data_str = plot_object.first_data_layout().dataset.data
    else:
        # If we don't have data stored, read it from file
        file_content = open(f,'r').read()
        data_str = view_util.process_Iq_data(file_content)
        plot_object = Plot1D.objects.create_plot(request.user,
                                                 data=data_str,
                                                 filename='4065_Iq.txt')
        remote_job.plots.add(plot_object)
    
    template_values['plot_1d'] = data_str
    template_values['plot_object'] = plot_object
    template_values['plot_1d_id'] = plot_object.id if plot_object is not None else None
    
    # Now the 2D data
    f = os.path.join(os.path.split(__file__)[0],'..','plotting','data','4065_Iqxy.nxs')
    plot_object2d = remote_job.get_plot_2d(filename='4065_Iqxy.nxs', owner=request.user)
    if plot_object2d is None:
        numpy.set_printoptions(threshold='nan', nanstr='0', infstr='0')
        fd = h5py.File(f, 'r')
        g = fd['mantid_workspace_1']
        y = g['workspace']['axis1']
        x = g['workspace']['axis2']
        values = g['workspace']['values']
        z_max = numpy.amax(values)
        numpy.set_string_function( lambda x: '['+','.join(map(lambda y:'['+','.join(map(lambda z: "%.4g" % z,y))+']',x))+']' )
        data_str_2d = values[:].__repr__()
        numpy.set_string_function( lambda x: '['+','.join(map(lambda z: "%.4g" % z,x))+']' )

        y_str = y[:].__repr__()
        x_str = x[:].__repr__()
        plot_object2d = Plot2D.objects.create_plot(user=request.user, data=data_str_2d,
                                                   x_axis=x_str, y_axis=y_str,
                                                   z_min=0.0, z_max=z_max, filename='4065_Iqxy.nxs')
        remote_job.plots2d.add(plot_object2d)

    template_values['plot_2d'] = plot_object2d

    return template_values
开发者ID:serena617,项目名称:reduction_service,代码行数:86,代码来源:test_util.py

示例13: pprint

import numpy as np


# noinspection PyUnusedLocal
def pprint(arr):
    return 'HA! - What are you going to do now?'


np.set_string_function(pprint)
a = np.arange(10)
a
print
a
np.set_string_function(None)
a
x = np.arange(4)
np.set_string_function(lambda x_: 'random', repr=False)
x.__str__()
x.__repr__()
开发者ID:yzozulya,项目名称:numpy_test_examples,代码行数:19,代码来源:numpy.set_string_function.py

示例14: set_array_layout

def set_array_layout():
    numpy.set_printoptions(linewidth=300, suppress=True)
    numpy.set_string_function(f=format_d2)
开发者ID:ingmarschuster,项目名称:smcdss,代码行数:3,代码来源:auxi.py

示例15: string_func

DIM_NETHER = -1
DIM_END = 1

_zeros = {}


def string_func(array):
    numpy.set_string_function(None)
    string = repr(array)
    string = string[:-1] + ", shape=%s)" % (array.shape,)
    numpy.set_string_function(string_func)
    return string


numpy.set_string_function(string_func)


class EntityListProxy(collections.MutableSequence):
    """
    A proxy for the Entities and TileEntities lists of a WorldEditorChunk. Accessing an element returns an EntityRef
    or TileEntityRef wrapping the element of the underlying NBT compound, with a reference to the WorldEditorChunk.

    These Refs cannot be created at load time as they hold a reference to the chunk, preventing the chunk from being
    unloaded when its refcount reaches zero.
    """

    chunk = weakrefprop()

    def __init__(self, chunk, attrName, refClass):
        self.attrName = attrName
开发者ID:pamunoz,项目名称:mcedit2,代码行数:30,代码来源:worldeditor.py


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