コード例 #1
0
def bmat(obj, ldict=None, gdict=None):
    """Build a matrix object from string, nested sequence, or array.

    Ex:  F = bmat('A, B; C, D')
         F = bmat([[A,B],[C,D]])
         F = bmat(r_[c_[A,B],c_[C,D]])

        all produce the same Matrix Object    [ A  B ]
                                              [ C  D ]

        if A, B, C, and D are appropriately shaped 2-d arrays.
    """
    if isinstance(obj, str):
        if gdict is None:
            # get previous frame
            frame = sys._getframe().f_back
            glob_dict = frame.f_globals
            loc_dict = frame.f_locals
        else:
            glob_dict = gdict
            loc_dict = ldict

        return matrix(_from_string(obj, glob_dict, loc_dict))

    if isinstance(obj, (tuple, list)):
        # [[A,B],[C,D]]
        arr_rows = []
        for row in obj:
            if isinstance(row, N.ndarray):  # not 2-d
                return matrix(concatenate(obj,axis=-1))
            else:
                arr_rows.append(concatenate(row,axis=-1))
        return matrix(concatenate(arr_rows,axis=0))
    if isinstance(obj, N.ndarray):
        return matrix(obj)
コード例 #2
0
ファイル: shape_base.py プロジェクト: ArneBab/pypyjs
def hstack(tup):
    """
    Stack arrays in sequence horizontally (column wise).

    Take a sequence of arrays and stack them horizontally to make
    a single array. Rebuild arrays divided by `hsplit`.

    Parameters
    ----------
    tup : sequence of ndarrays
        All arrays must have the same shape along all but the second axis.

    Returns
    -------
    stacked : ndarray
        The array formed by stacking the given arrays.

    See Also
    --------
    vstack : Stack arrays in sequence vertically (row wise).
    dstack : Stack arrays in sequence depth wise (along third axis).
    concatenate : Join a sequence of arrays together.
    hsplit : Split array along second axis.

    Notes
    -----
    Equivalent to ``np.concatenate(tup, axis=1)``

    Examples
    --------
    >>> a = np.array((1,2,3))
    >>> b = np.array((2,3,4))
    >>> np.hstack((a,b))
    array([1, 2, 3, 2, 3, 4])
    >>> a = np.array([[1],[2],[3]])
    >>> b = np.array([[2],[3],[4]])
    >>> np.hstack((a,b))
    array([[1, 2],
           [2, 3],
           [3, 4]])

    """
    arrs = map(atleast_1d,tup)
    # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    if arrs[0].ndim == 1:
        return _nx.concatenate(arrs, 0)
    else:
        return _nx.concatenate(arrs, 1)
コード例 #3
0
ファイル: shape_base.py プロジェクト: sota/pypy-old
def hstack(tup):
    """
    Stack arrays in sequence horizontally (column wise).

    Take a sequence of arrays and stack them horizontally to make
    a single array. Rebuild arrays divided by `hsplit`.

    Parameters
    ----------
    tup : sequence of ndarrays
        All arrays must have the same shape along all but the second axis.

    Returns
    -------
    stacked : ndarray
        The array formed by stacking the given arrays.

    See Also
    --------
    vstack : Stack arrays in sequence vertically (row wise).
    dstack : Stack arrays in sequence depth wise (along third axis).
    concatenate : Join a sequence of arrays together.
    hsplit : Split array along second axis.

    Notes
    -----
    Equivalent to ``np.concatenate(tup, axis=1)``

    Examples
    --------
    >>> a = np.array((1,2,3))
    >>> b = np.array((2,3,4))
    >>> np.hstack((a,b))
    array([1, 2, 3, 2, 3, 4])
    >>> a = np.array([[1],[2],[3]])
    >>> b = np.array([[2],[3],[4]])
    >>> np.hstack((a,b))
    array([[1, 2],
           [2, 3],
           [3, 4]])

    """
    arrs = map(atleast_1d, tup)
    # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    if arrs[0].ndim == 1:
        return _nx.concatenate(arrs, 0)
    else:
        return _nx.concatenate(arrs, 1)
コード例 #4
0
ファイル: hrrgraph.py プロジェクト: Elhamahm/nengo_1.4
    def post_process(self, data, start, dt_tau):
        if dt_tau != self.cache_dt_tau or self.cache_tick_count > self.view.watcher.timelog.tick_count:
            self.cache_dt_tau = dt_tau
            self.clear_cache()

        self.cache_tick_count = self.view.watcher.timelog.tick_count

        forget = self.cache_tick_count - self.view.watcher.timelog.tick_limit
        if forget in self.cache:
            del self.cache[forget]

        if not hasattr(self, 'vocab'):
            return []

        if len(self.vocab.keys) == 0:
            return []

        d = []
        for i, dd in enumerate(data):
            if dd is None:
                d.append(None)
            else:
                index = i + start
                v = self.cache.get((index, dt_tau), None)
                if v is None:
                    if self.normalize or self.smooth_normalize:
                        dd = self.calc_normal(dd)
                    v = self.vocab.dot(dd)
                    if self.show_pairs:
                        v2 = self.vocab.dot_pairs(dd)
                        if v2 is not None:
                            v = numeric.concatenate((v, v2), 0)
                    self.cache[(index, dt_tau)] = v
                d.append(v)
        return d
コード例 #5
0
    def post_process(self, data, start, dt_tau):
        if dt_tau != self.cache_dt_tau or self.cache_tick_count > self.view.watcher.timelog.tick_count:
            self.cache_dt_tau = dt_tau
            self.clear_cache()

        self.cache_tick_count = self.view.watcher.timelog.tick_count

        forget = self.cache_tick_count - self.view.watcher.timelog.tick_limit
        if forget in self.cache:
            del self.cache[forget]

        if len(self.vocab.keys) == 0:
            return []

        d = []
        for i, dd in enumerate(data):
            if dd is None:
                d.append(None)
            else:
                index = i + start
                v = self.cache.get((index, dt_tau), None)
                if v is None:
                    if self.normalize or self.smooth_normalize:
                        dd = self.calc_normal(dd)
                    v = self.vocab.dot(dd)
                    if self.show_pairs:
                        v2 = self.vocab.dot_pairs(dd)
                        if v2 is not None:
                            v = numeric.concatenate((v, v2), 0)
                    self.cache[(index, dt_tau)] = v
                d.append(v)
        return d
コード例 #6
0
def resize(a, new_shape):
    """resize(a,new_shape) returns a new array with the specified shape.
    The original array's total size can be any size. It
    fills the new array with repeated copies of a.

    Note that a.resize(new_shape) will fill array with 0's
    beyond current definition of a.
    """

    if isinstance(new_shape, (int, nt.integer)):
        new_shape = (new_shape,)
    a = ravel(a)
    Na = len(a)
    if not Na: return mu.zeros(new_shape, a.dtype.char)
    total_size = um.multiply.reduce(new_shape)
    n_copies = int(total_size / Na)
    extra = total_size % Na

    if total_size == 0:
        return a[:0]

    if extra != 0:
        n_copies = n_copies+1
        extra = Na-extra

    a = concatenate( (a,)*n_copies)
    if extra > 0:
        a = a[:-extra]

    return reshape(a, new_shape)
コード例 #7
0
ファイル: arrayprint.py プロジェクト: lisarosalina/App
def _leading_trailing(a):
    if a.ndim == 1:
        if len(a) > 2*_summaryEdgeItems:
            b = _nc.concatenate((a[:_summaryEdgeItems],
                                     a[-_summaryEdgeItems:]))
        else:
            b = a
    else:
        if len(a) > 2*_summaryEdgeItems:
            l = [_leading_trailing(a[i]) for i in range(
                min(len(a), _summaryEdgeItems))]
            l.extend([_leading_trailing(a[-i]) for i in range(
                min(len(a), _summaryEdgeItems),0,-1)])
        else:
            l = [_leading_trailing(a[i]) for i in range(0, len(a))]
        b = _nc.concatenate(tuple(l))
    return b
コード例 #8
0
ファイル: defmatrix.py プロジェクト: 8848/Pymol-script-repo
def _from_string(str,gdict,ldict):
    rows = str.split(';')
    rowtup = []
    for row in rows:
        trow = row.split(',')
        newrow = []
        for x in trow:
            newrow.extend(x.split())
        trow = newrow
        coltup = []
        for col in trow:
            col = col.strip()
            try:
                thismat = ldict[col]
            except KeyError:
                try:
                    thismat = gdict[col]
                except KeyError:
                    raise KeyError, "%s not found" % (col,)

            coltup.append(thismat)
        rowtup.append(concatenate(coltup,axis=-1))
    return concatenate(rowtup,axis=0)
コード例 #9
0
def _from_string(str,gdict,ldict):
    rows = str.split(';')
    rowtup = []
    for row in rows:
        trow = row.split(',')
        newrow = []
        for x in trow:
            newrow.extend(x.split())
        trow = newrow
        coltup = []
        for col in trow:
            col = col.strip()
            try:
                thismat = ldict[col]
            except KeyError:
                try:
                    thismat = gdict[col]
                except KeyError:
                    raise KeyError, "%s not found" % (col,)

            coltup.append(thismat)
        rowtup.append(concatenate(coltup,axis=-1))
    return concatenate(rowtup,axis=0)
コード例 #10
0
ファイル: shape_base.py プロジェクト: ArneBab/pypyjs
def vstack(tup):
    """
    Stack arrays in sequence vertically (row wise).

    Take a sequence of arrays and stack them vertically to make a single
    array. Rebuild arrays divided by `vsplit`.

    Parameters
    ----------
    tup : sequence of ndarrays
        Tuple containing arrays to be stacked. The arrays must have the same
        shape along all but the first axis.

    Returns
    -------
    stacked : ndarray
        The array formed by stacking the given arrays.

    See Also
    --------
    hstack : Stack arrays in sequence horizontally (column wise).
    dstack : Stack arrays in sequence depth wise (along third dimension).
    concatenate : Join a sequence of arrays together.
    vsplit : Split array into a list of multiple sub-arrays vertically.

    Notes
    -----
    Equivalent to ``np.concatenate(tup, axis=0)`` if `tup` contains arrays that
    are at least 2-dimensional.

    Examples
    --------
    >>> a = np.array([1, 2, 3])
    >>> b = np.array([2, 3, 4])
    >>> np.vstack((a,b))
    array([[1, 2, 3],
           [2, 3, 4]])

    >>> a = np.array([[1], [2], [3]])
    >>> b = np.array([[2], [3], [4]])
    >>> np.vstack((a,b))
    array([[1],
           [2],
           [3],
           [2],
           [3],
           [4]])

    """
    return _nx.concatenate(map(atleast_2d,tup),0)
コード例 #11
0
ファイル: shape_base.py プロジェクト: sota/pypy-old
def vstack(tup):
    """
    Stack arrays in sequence vertically (row wise).

    Take a sequence of arrays and stack them vertically to make a single
    array. Rebuild arrays divided by `vsplit`.

    Parameters
    ----------
    tup : sequence of ndarrays
        Tuple containing arrays to be stacked. The arrays must have the same
        shape along all but the first axis.

    Returns
    -------
    stacked : ndarray
        The array formed by stacking the given arrays.

    See Also
    --------
    hstack : Stack arrays in sequence horizontally (column wise).
    dstack : Stack arrays in sequence depth wise (along third dimension).
    concatenate : Join a sequence of arrays together.
    vsplit : Split array into a list of multiple sub-arrays vertically.

    Notes
    -----
    Equivalent to ``np.concatenate(tup, axis=0)`` if `tup` contains arrays that
    are at least 2-dimensional.

    Examples
    --------
    >>> a = np.array([1, 2, 3])
    >>> b = np.array([2, 3, 4])
    >>> np.vstack((a,b))
    array([[1, 2, 3],
           [2, 3, 4]])

    >>> a = np.array([[1], [2], [3]])
    >>> b = np.array([[2], [3], [4]])
    >>> np.vstack((a,b))
    array([[1],
           [2],
           [3],
           [2],
           [3],
           [4]])

    """
    return _nx.concatenate(map(atleast_2d, tup), 0)
コード例 #12
0
ファイル: fromnumeric.py プロジェクト: alexxpan/python-art
def resize(a, new_shape):
    """Return a new array with the specified shape.

    The original array's total size can be any size.  The new array is
    filled with repeated copies of a.

    Note that a.resize(new_shape) will fill the array with 0's beyond
    current definition of a.

    *Parameters*:

        a : {array_like}
            Array to be reshaped.

        new_shape : {tuple}
            Shape of reshaped array.

    *Returns*:

        reshaped_array : {array}
            The new array is formed from the data in the old array, repeated if
            necessary to fill out the required number of elements, with the new
            shape.

    """
    if isinstance(new_shape, (int, nt.integer)):
        new_shape = (new_shape,)
    a = ravel(a)
    Na = len(a)
    if not Na: return mu.zeros(new_shape, a.dtype.char)
    total_size = um.multiply.reduce(new_shape)
    n_copies = int(total_size / Na)
    extra = total_size % Na

    if total_size == 0:
        return a[:0]

    if extra != 0:
        n_copies = n_copies+1
        extra = Na-extra

    a = concatenate( (a,)*n_copies)
    if extra > 0:
        a = a[:-extra]

    return reshape(a, new_shape)
コード例 #13
0
    def __init__(self,view,name,config,func,args=(),label=None):
        core.DataViewComponent.__init__(self,label)
        self.view=view
        self.name=name
        self.func=func
        self.data=self.view.watcher.watch(name,func,args=args)

        self.border_top=20
        self.border_left=20
        self.border_right=20
        self.border_bottom=20
        self.config=config
        self.start = 0

        # self.setSize(440,440+self.label_offset)
        self.setSize(240,240+self.label_offset)

        self.max = 0.0001
        self.min = -0.0001
        self.grid_size = 50
        self.image = None
        self.counter = 0
        
        ######################################
        ## initialize function input grid
        
        grid_size = self.grid_size
                
        # construct input grid
        row = array([map(float,range(grid_size))])
        row = row / (self.grid_size-1) * 2 - 2  # normalized to [-1, 1]
        gridX = dot(ones([grid_size,1]), row)
        gridY = transpose(gridX)
        
        # get function value
        x1 = reshape(gridX,[1, grid_size*grid_size])
        x2 = reshape(gridY,[1, grid_size*grid_size])
        self.func_input = concatenate([x1, x2], 0)
コード例 #14
0
def bmat(obj, ldict=None, gdict=None):
    """
    Build a matrix object from a string, nested sequence, or array.

    Parameters
    ----------
    obj : string, sequence or array
        Input data.  Variables names in the current scope may
        be referenced, even if `obj` is a string.

    Returns
    -------
    out : matrix
        Returns a matrix object, which is a specialized 2-D array.

    See Also
    --------
    matrix

    Examples
    --------
    >>> A = np.mat('1 1; 1 1')
    >>> B = np.mat('2 2; 2 2')
    >>> C = np.mat('3 4; 5 6')
    >>> D = np.mat('7 8; 9 0')

    All the following expressions construct the same block matrix:

    >>> np.bmat([[A, B], [C, D]])
    matrix([[1, 1, 2, 2],
            [1, 1, 2, 2],
            [3, 4, 7, 8],
            [5, 6, 9, 0]])
    >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
    matrix([[1, 1, 2, 2],
            [1, 1, 2, 2],
            [3, 4, 7, 8],
            [5, 6, 9, 0]])
    >>> np.bmat('A,B; C,D')
    matrix([[1, 1, 2, 2],
            [1, 1, 2, 2],
            [3, 4, 7, 8],
            [5, 6, 9, 0]])

    """
    if isinstance(obj, str):
        if gdict is None:
            # get previous frame
            frame = sys._getframe().f_back
            glob_dict = frame.f_globals
            loc_dict = frame.f_locals
        else:
            glob_dict = gdict
            loc_dict = ldict

        return matrix(_from_string(obj, glob_dict, loc_dict))

    if isinstance(obj, (tuple, list)):
        # [[A,B],[C,D]]
        arr_rows = []
        for row in obj:
            if isinstance(row, N.ndarray):  # not 2-d
                return matrix(concatenate(obj,axis=-1))
            else:
                arr_rows.append(concatenate(row,axis=-1))
        return matrix(concatenate(arr_rows,axis=0))
    if isinstance(obj, N.ndarray):
        return matrix(obj)
コード例 #15
0
    def paintComponent(self,g):
        
        f,dimension,minx,maxx,miny,maxy, params, color, time_step = self.config
        
        core.DataViewComponent.paintComponent(self,g)

        width=self.size.width-self.border_left-self.border_right
        height=self.size.height-self.border_top-self.border_bottom-self.label_offset
            
        if width<2: return

        dt_tau=None
        if self.view.tau_filter>0:
            dt_tau=self.view.dt/self.view.tau_filter
        try:    
            data=self.data.get(start=self.view.current_tick,count=1,dt_tau=dt_tau)[0]
        except:
            return
        
        if dimension == 2:   
            if self.image is None :
                self.image = BI(width, height, BI.TYPE_INT_ARGB)
            
            if self.counter != time_step:
                self.counter += 1
                g.drawImage( self.image, self.border_left, self.border_top, None)
            else:
                self.counter = 0
                # currently only for fixed grid
                grid_size = self.grid_size
                # step_size = width / grid_size
                
                coeffs=transpose(array([data]))
                basis = array(f(self.func_input, params))
                value = transpose(dot(transpose(basis),coeffs))
                maxv = max(value[0])
                minv = min(value[0])
                if maxv > self.max:
                    self.max = maxv
                if minv < self.min:
                    self.min = minv
        
                pvalue = (value - self.min) / (self.max - self.min) # normalized pixel value
                
                if color == 'g':
                    ## gray
                    pvalue = array(map(int, array(pvalue[0]) * 0xFF))
                    pvalue = pvalue * 0x10000 + pvalue * 0x100 + pvalue
                elif color == 'c':
                    ##color
                    pvalue = map(int, array(pvalue[0]) * 0xFF * 2) 
                    R = zeros(len(pvalue))
                    G = zeros(len(pvalue))
                    B = zeros(len(pvalue))
                    for i, v in enumerate(pvalue):
                        if v < 0xFF:
                            B[i] = 0xFF - v
                            G[i] = v
                        else:
                            G[i] = 2*0xFF - v
                            R[i] = v - 0xFF
                    pvalue = R * 0x10000 + G * 0x100 + B
                
                pvalue = reshape(pvalue,[grid_size, grid_size])
                rvalue = 0xFF000000 + pvalue
                
                # expand pixel value from grid to raster size
                # ratio = float(width) / grid_size
                # indeces = map(int, (floor(array(range(width)) / ratio)))
                ## Tooooooo slow here!
                # for i, ii in enumerate(indeces): 
                    # for j, jj in enumerate(indeces) :
                        # rvalue[i,j] = pvalue[ii,jj]
            
                for zoom in range(2):
                    zgrid_size = grid_size * (zoom + 1)
                    rvalue = reshape(rvalue, [zgrid_size * zgrid_size, 1])
                    rvalue = concatenate([rvalue, rvalue], 1)
                    rvalue = reshape(rvalue, [zgrid_size, zgrid_size* 2])
                    rvalue = repeat(rvalue, ones(zgrid_size) * 2)
                                
                # draw image
                rvalue = reshape(rvalue, [1, width * height])
                self.image.setRGB(0, 0, width, height, rvalue[0], 0, width)
                g.drawImage( self.image, self.border_left, self.border_top, None)
                
        elif dimension == 1: 
            g.color=Color(0.8,0.8,0.8)
            g.drawRect(self.border_left,self.border_top+self.label_offset,width,height)
            
            g.color=Color.black
            txt='%4g'%maxx
            bounds=g.font.getStringBounds(txt,g.fontRenderContext)
            g.drawString(txt,self.size.width-self.border_right-bounds.width/2,self.size.height-self.border_bottom+bounds.height)

            txt='%4g'%minx
            bounds=g.font.getStringBounds(txt,g.fontRenderContext)
            g.drawString(txt,self.border_left-bounds.width/2,self.size.height-self.border_bottom+bounds.height)

            g.drawString('%6g'%maxy,0,10+self.border_top+self.label_offset)
            g.drawString('%6g'%miny,0,self.size.height-self.border_bottom)

            g.color=Color.black
            
            pdftemplate=getattr(self.view.area,'pdftemplate',None)
            if pdftemplate is not None:
                pdf,scale=pdftemplate
                pdf.setLineWidth(0.5)

                steps=100

                dx=float(maxx-minx)/(width*steps)

                for i in range(width*steps):
                    x=minx+i*dx
                    value=sum([f(j,x)*d for j,d in enumerate(data)])
                    y=float((value-miny)*height/(maxy-miny))
                    
                    xx=self.border_left+i/float(steps)
                    yy=self.height-self.border_bottom-y

                    if i==0:
                        pdf.moveTo((self.x+xx)*scale,800-(self.y+yy)*scale)
                    else:
                        if 0<y<height:
                            pdf.lineTo((self.x+xx)*scale,800-(self.y+yy)*scale)
                pdf.setRGBColorStroke(g.color.red,g.color.green,g.color.blue)        
                pdf.stroke()        
            else:                
                dx=float(maxx-minx)/(width-1)
                px,py=None,None
                for i in range(width):
                    x=minx+i*dx
                    value=sum([f(j,x)*d for j,d in enumerate(data)])

                    y=int((value-miny)*height/(maxy-miny))

                    xx=self.border_left+i
                    yy=self.height-self.border_bottom-y

                    if px is not None and miny<value<maxy:
                        g.drawLine(px,py,xx,yy)
                    px,py=xx,yy