示例#1
0
def ndarray_header(A):
    header = ArrayHeader()
    header['type'] = 'ndarray'
    header['rank'] = rank(A)
    header['dims'] = ','.join(map(str,A.shape))
    header['dtype'] = A.dtype.name
    return header
示例#2
0
def write_array(fid,A,format='binary'):
    """
    Write an ndarray or sparse matrix to a file
    
        format may be one of ['basic','ascii','binary']
        
        basic
            - Most human readable
            - Only works for arrays of rank 1 and 2
            - Does not work for sparse matrices
        ascii
            - Somewhat human readable
            - Works for ndarrays and sparse matrices
        binary
            - Fastest format
            - Works for ndarrays and sparse matrices
            - Data stored in LittleEndian
    """   
        
    if format not in ['basic','ascii','binary']: raise ArrayIOException('Unknown format: ['+format+']')
   
    if type(fid) is not file: fid = open(fid,'wb')
    
    if type(A) is numpy.ndarray:
        A = numpy.ascontiguousarray(A)  #strided arrays break in write
        if format == 'basic':
            if rank(A) > 2: raise ArrayIOException('basic format only works for rank 1 or 2 arrays')
            write_basic(fid,A)
        else:            
            write_ndarray(fid,A,format)
    elif scipy.sparse.isspmatrix(A):
        if format not in ['ascii','binary']: raise ArrayIOException('sparse matrices require ascii or binary format')
        write_sparse(fid,A,format)
    else:
        try:
            A = asarray(A)
            if format == 'basic':
                if rank(A) > 2: raise ArrayIOException('basic format only works for rank 1 or 2 arrays')
                write_basic(fid,A)
            else:            
                write_ndarray(fid,A,format)
        except:
            raise ArrayIOException('Unknown data type and unable to convert to numpy.ndarray')
示例#3
0
 def test_dense(self):
     sizes = [(2,2),(3,3),(5,1),(1,5)]
     sizes += [(2,2,2),(4,3,2),(1,1,5),(1,5,1),(5,1,1)]
     for dims in sizes:
         mats = [arange(prod(dims)).reshape(dims),rand(*dims)]    
         for A in mats:
             formats = ['binary','ascii']
             if rank(A) <= 2: formats.append('basic') #use basic when possible
             for format in formats:
                 write_array(filename,A,format=format)
                 
                 B = read_array(filename)
                 assert_almost_equal(A,B,decimal=12)
示例#4
0
def triangulate_ncube(vertices,indices):
    n_dims  = rank(indices) - 1
    n_cubes = indices.shape[0]
    n_verts = vertices.shape[0]
    
    if n_dims <= 1:
        #cube mesh only contains edges
        return vertices,indices





    if n_dims > 2:
        raise NotImplementedError,'nCube meshes with n > 2 not supported'

    cell_centers = vertices[indices.reshape(n_cubes,-1)].mean(axis=1)

    n_faces = 2*n_dims*n_cubes

    faces = zeros((n_faces,) + (2,)*(n_dims-1),dtype=indices.dtype)

    for i in range(n_dims):
        s0 = [slice(None,None,None)]*(i+1) + [0] + [slice(None,None,None)]*(n_dims-i-1)
        s1 = [slice(None,None,None)]*(i+1) + [1] + [slice(None,None,None)]*(n_dims-i-1)

        faces[(2*i+0)*n_cubes:(2*i+1)*n_cubes] = indices[s0]
        faces[(2*i+1)*n_cubes:(2*i+2)*n_cubes] = indices[s1]

        #this seems to be the correct pattern
        if (n_dims-1-i) % 2 == n_dims % 2:
            #flip 1
            temp = faces[(2*i+1)*n_cubes:(2*i+2)*n_cubes,0].copy()
            faces[(2*i+1)*n_cubes:(2*i+2)*n_cubes,0] = faces[(2*i+1)*n_cubes:(2*i+2)*n_cubes,1]
            faces[(2*i+1)*n_cubes:(2*i+2)*n_cubes,1] = temp
        else:
            #flip 0
            temp = faces[(2*i+0)*n_cubes:(2*i+1)*n_cubes,0].copy()
            faces[(2*i+0)*n_cubes:(2*i+1)*n_cubes,0] = faces[(2*i+0)*n_cubes:(2*i+1)*n_cubes,1]
            faces[(2*i+0)*n_cubes:(2*i+1)*n_cubes,1] = temp


    face_vertices,face_indices = triangulate_ncube(vertices,faces)

    center_indices = (arange(n_cubes) + face_vertices.shape[0]).reshape((n_cubes,1))
    center_indices = tile(center_indices,(face_indices.shape[0]/n_cubes,1))

    new_vertices = vstack((face_vertices,cell_centers))
    new_indices  = hstack((center_indices,face_indices))

    return new_vertices,new_indices
示例#5
0
def simplex_array_searchsorted(s, v):
    """Find the row indices (of s) corresponding to the simplices stored 
    in the rows of simplex array v.  The rows of s must be stored in 
    lexicographical order.

    Example
    -------

    >>> from numpy import array
    >>> s = array([[0,1],[0,2],[1,2],[1,3]])
    >>> v = array([[1,2],[0,2]])
    >>> simplex_array_searchsorted(s,v)
    array([2, 1])

    """

    s = asarray(s)
    v = asarray(v)

    if rank(s) != 2 or rank(v) != 2:
        raise ValueError('expected rank 2 arrays')

    if s.shape[1] != v.shape[1]:
        raise ValueError('number of columns must agree')
   
    # compute row indices by sorting both arrays together
    Ns = s.shape[0]
    Nv = v.shape[0]
    
    perm = lexsort(vstack((s,v))[:,::-1].T)
    
    flags = concatenate( (ones(Ns,dtype=int),zeros(Nv,dtype=int)) )
    indices = empty(Ns+Nv, dtype=int)
    indices[perm] = cumsum(flags[perm])
    indices = indices[Ns:].copy()
    indices -= 1

    return indices