Example #1
0
def least_factorization( x, basis, domain, basis_indices = None ):
    assert x.ndim == 2, 'x must be a 2d array (num_dims x num_pts)'
    num_dims, num_pts = x.shape
    numpy.set_printoptions(precision=17)
    basis_indices_list = []

    l = numpy.eye( num_pts )
    u = numpy.eye( num_pts )
    p = numpy.eye( num_pts )

    # This is just a guess: this vector could be much larger, or much smaller
    v = numpy.zeros( ( 1000, 1 ) )
    v_index = 0;

    # Current polynomial degree
    k_counter = 0
    # k(q) gives the degree used to eliminate the q'th point
    k = numpy.zeros( ( num_pts , 1 ) )

    # The current LU row to factor out:
    lu_row = 0

    index_generator = IndexGenerator()

    # Current degree is k_counter, and we iterate on this
    while ( lu_row < num_pts ):
        # We are going to generate the appropriate columns of W -- 
        # these are polynomial indices for degree k of the basis.

        # Get the current size of k-vectors
        if basis_indices is None:

            poly_indices = index_generator.get_isotropic_level_indices(num_dims,
                                                                       k_counter,
                                                                       1. )
            n = len( basis_indices_list )
            for i in xrange( len ( poly_indices ) ):
                poly_indices[i].set_array_index( n + i )

        else:
            n = len( basis_indices_list )
            poly_indices = []
            for index in basis_indices:
                if index.level_sum() == k_counter:
                     poly_indices.append( index )
                     index.set_array_index( n )
                     n += 1

        basis_indices_list += poly_indices

        current_dim = len( poly_indices )

        W = numpy.empty( ( current_dim, num_pts ), numpy.double )
        for i, index in enumerate( poly_indices ):
            W[i,:] = basis.value( x, index, domain )
            #tmp to match akils polynomials
            #W[i,:] /= numpy.sqrt(basis.l2_norm(index))*2
        W = dot( p, W.T )
        #print '##############'
        #print lu_row
        #print W[lu_row:num_pts,:]
        #print 'p',numpy.nonzero(p)[1]


        # Row-reduce W according to previous elimination steps
        end = W.shape[0]
        for q in range( lu_row ):
            W[q,:] = W[q,:] / l[q,q];
            W[q+1:end,:] -= dot( l[q+1:end,q].reshape( ( end-q-1, 1) ) , 
                                 W[q,:].reshape( (1, W.shape[1] ) ) );
        #print 'W',W
        #print 'l', l

        # The mass matrix defining the inner product for this degree
        M = numpy.eye( current_dim )
        #M = numpy.zeros( ( poly_indices.shape[0], poly_indices.shape[0] ),
        #                 numpy.double );
        #for i, index in enumerate( poly_indices ):
        #    M[i,i] = basis.l2_norm( index )

        # Get upper triangular factorization of mass matrix
        # M = numpy.linalg.cholesky( M )

        # lapack function for qr DGEQP3
        wm =  dot(W[lu_row:num_pts,:] , M ).T
        Q, R, evec = qr( wm, pivoting = True, 
                         mode = 'economic' )

        #print 'wm', wm
        #print 'Q',Q
        #print 'R',R
        #print 'e', evec
        
        #rnk = matrix_rank( R )
        rnk = 0
        for i in xrange( R.shape[0] ):
            # If RHS is too large then if basis is fixed on entry
            # then an error may be thrown by Python
            if abs( R[i,i] ) < 0.001 * abs( R[0,0] ):
                break
            rnk += 1

        #print 'rnk',rnk

        NN = num_pts - lu_row
        e = numpy.zeros( ( NN, NN ), numpy.double )
        for qq in xrange( NN ):
            e[evec[qq],qq] = 1.;
        
        # Now first we must permute the rows by e
        #print  numpy.nonzero(p[lu_row:num_pts,:])[1]
        p[lu_row:num_pts,:] = dot( e.T, p[lu_row:num_pts,:] );
        # And correct by permuting l as well:
        #print 'l_sub', l[lu_row:num_pts,:lu_row]
        #print 'l_sub', l[lu_row:num_pts,:lu_row].shape
        l[lu_row:num_pts,:lu_row] = dot( e.T, l[lu_row:num_pts,:lu_row] );

        #print 'p', numpy.nonzero(p)[1]
        #print 'l', l


        # The matrix r gives us inner product information for all rows below 
        # these in W
        l[lu_row:num_pts,lu_row:lu_row+rnk] = R[:rnk,:].T;

        #print 'l', l
        
        #print 'usub', u[:lu_row,lu_row:lu_row+rnk]
        #print 'wusb',  W[:lu_row,:]
        #print  'qsub', Q[:,:rnk]
        # Now we must find inner products of all the other rows above these in W
        u[:lu_row,lu_row:lu_row+rnk] = dot( dot( W[:lu_row,:], M ), 
                                            Q[:,:rnk] );

        #print 'u', u
        #print Q
        if ( v_index+(current_dim*rnk) > v.shape[0] ):
            v.resize( (v.shape[0] + max(1000,current_dim*rnk), 1 ) )
        # The matrix q must be saved in order to characterize basis
        # order = 'F' is used to reshape using column major 
        # order (used in fortran/matlab) this makes code consisten with matlab
        v[v_index:v_index+(current_dim*rnk)] = numpy.reshape( Q[:,:rnk], 
                                          (rnk*current_dim,1),order='F').copy();
        v_index = v_index+(current_dim*rnk);
        #print Q[:,:rnk]
        #print 'v',v[:v_index]
     
        # Update degree markers, and node and degree count
        k[lu_row:(lu_row+rnk)] = k_counter;
        lu_row = lu_row + rnk;
        k_counter = k_counter + 1;
     
    # Chop off parts of unnecessarily allocated vector v
    v = numpy.resize( v, ( v_index ) );

    # Make matrix H:
    H = get_least_polynomial_coefficients( v, num_dims, num_pts, k,
                                           #basis_indices ) 
                                           basis_indices_list )


    return l,u,p,H,v,k,basis_indices_list
Example #2
0
def sequential_least_factorization( x, basis, domain, N = None, 
                                    basis_indices = None ):
    assert x.ndim == 2, 'x must be a 2d array (num_dims x num_pts)'
    num_dims, num_pts = x.shape

    if N is None:
        N = num_pts
    else:
        assert N <= num_pts

    basis_indices_list = []

    l = numpy.eye( N )
    u = numpy.eye( N )
    p = numpy.eye( N )

    # This is just a guess: this vector could be much larger, or much smaller
    v = numpy.zeros( ( 1000, 1 ) )
    v_index = 0;
    
    # Current polynomial degree
    k_counter = 0
    # k(q) gives the degree used to eliminate the q'th point
    k = numpy.zeros( ( N , 1 ) )

    # The current LU row to factor out:
    lu_row = 0

    # Every time the basis degree is increased compute the rank
    # of the matrix formed using the new basis terms
    find_rank = True

    index_generator = IndexGenerator()

    while ( lu_row < N ):

        # Get the current size of k-vectors
        if find_rank:
            if basis_indices is None:
                poly_indices = \
                    index_generator.get_isotropic_level_indices(num_dims,
                                                                k_counter,
                                                                1. )
                n = len( basis_indices_list )
                for i in xrange( len ( poly_indices ) ):
                    poly_indices[i].set_array_index( n + i )

            else:
                print '###############', k_counter
                poly_indices = []
                for index in basis_indices:
                    if index.level_sum() == k_counter:
                         poly_indices.append( index )

            basis_indices_list += poly_indices

        current_dim = len( poly_indices )

        W = numpy.empty( ( current_dim, num_pts ), numpy.double )
        for i, index in enumerate( poly_indices ):
            W[i,:] = basis.value( x, index, domain )
            #tmp to match akils polynomials
            #W[i,:] /= numpy.sqrt(basis.l2_norm(index))*2
        W = dot( p, W.T )

        # Row-reduce W according to previous elimination steps
        end = W.shape[0]
        for q in range( lu_row ):
            W[q,:] = W[q,:] / l[q,q];
            W[q+1:end,:] -= dot( l[q+1:end,q].reshape( ( end-q-1, 1) ) , 
                                 W[q,:].reshape( (1, W.shape[1] ) ) );

        #wm =  dot(W[lu_row:N,:] , M ).T
        wm = W[lu_row:N,:].T

        #print 'W', numpy.sqrt( numpy.sum( wm**2, axis = 0 ) )

        if find_rank:
            #rnk = numpy.linalg.matrix_rank( wm )
            Q, R, evec = qr( wm, pivoting = True, 
                             mode = 'economic' )
            rnk = 0
            for i in range(R.shape[0] ):
                # If RHS is too large then if basis is fixed on entry
                # then an error may be thrown by Python
                if abs( R[i,i] ) < 0.001 * abs( R[0,0] ):
                    break
                rnk += 1
            find_rank = False

        # Find the column with the largest inner norm and compute inner products
        column_norms = numpy.sqrt( numpy.sum( wm**2, axis = 0 ) )
        next_index = column_norms.argmax()

        row = wm[:,next_index] / column_norms[next_index]
        tmp = numpy.dot( row, wm )
        inner_products = numpy.empty( ( tmp.shape[0] ), numpy.double )
        inner_products[0] = column_norms[next_index]
        if ( next_index > 0 ):
            inner_products[1:next_index+1] = tmp[:next_index]
        if ( next_index < tmp.shape[0]-1 ):
            inner_products[next_index+1:] = tmp[next_index+1:]

        # Determine LU permutations. 
        # Generate permutation indices I
        I = numpy.empty( ( inner_products.shape[0] ), numpy.int32 )
        j = 0;
        I[j] = next_index; j += 1;
        for i in xrange( I.shape[0] ):
            if ( i != next_index ):
                I[j] = i
                j += 1

        p[lu_row:N,:] = permute_matrix_rows( p[lu_row:N,:], I )

        # Permute rows of l
        l[lu_row:N,:lu_row] = \
            permute_matrix_rows( l[lu_row:N,:lu_row], I )
        
        # Update l with inner product information
        l[lu_row:N,lu_row] = inner_products;

        # Compute inner products with rows above
        u[:lu_row,lu_row] = dot( W[:lu_row,:], row );

        # allocate enough memory to store new information
        if v.shape[0] < v_index+current_dim:
            v.resize( v.shape[0]+1000, 1 )
        
        # Save current information
        v[v_index:v_index+current_dim,0] = row

        # Update counters
        v_index = v_index + current_dim;
        k[lu_row] = k_counter
        lu_row += 1

        if rnk < 2:
            k_counter += 1
            find_rank = True
        else:
            rnk -= 1

    # Chop off parts of unnecessarily allocated vector v
    v = numpy.resize( v, ( v_index ) );
        
    # Make matrix H:
    H = get_least_polynomial_coefficients( v, num_dims, num_pts, k, 
                                           basis_indices )

    return l,u,p,H,v,k,basis_indices_list