Example #1
0
def adjacency(img_brightness, radius = 5.0, sigma_I = .15, sigma_d = 1.7):
    '''
    Compute the weighted adjacency matrix for
    the image given the radius. Do all computations with sparse matrices.
    Also, return an array giving the main diagonal of the degree matrix.
    
    Inputs:
        img_brightness (array): array of brightnesses given by the function getImage()
        radius (float): maximum distance where the weight isn't 0
        sigma_I (float): some constant to help define the weight
        sigma_d (float): some constant to help define the weight
    Returns:
        W (sparse array(csc)): the weighted adjacency matrix of img_brightness,
            in sparse form.
        D (array): 1D array representing the main diagonal of the degree matrix.
    '''
    n,m = img_brightness.shape
    flat_bright = img_brightness.flatten() 
    W = lil((len(flat_bright),len(flat_bright)))
    for pixel in xrange(len(flat_bright)):
        index, distance = getNeighbors(pixel, radius, n,m)
        for j in xrange(len(index)):
            W[pixel,index[j]] = np.e**(-np.absolute(flat_bright[pixel]-flat_bright[index[j]])/sigma_I**2 - (distance[j]/sigma_d**2))
    W = W.tocsc()
    D = W.sum(axis=0)
    return W, D
Example #2
0
def adjacency(img_brightness, radius=5.0, sigma_I=.15, sigma_d=1.7):
    '''
    Compute the weighted adjacency matrix for
    the image given the radius. Do all computations with sparse matrices.
    Also, return an array giving the main diagonal of the degree matrix.
    
    Inputs:
        img_brightness (array): array of brightnesses given by the function getImage()
        radius (float): maximum distance where the weight isn't 0
        sigma_I (float): some constant to help define the weight
        sigma_d (float): some constant to help define the weight
    Returns:
        W (sparse array(csc)): the weighted adjacency matrix of img_brightness,
            in sparse form.
        D (array): 1D array representing the main diagonal of the degree matrix.
    '''
    n, m = img_brightness.shape
    flat_bright = img_brightness.flatten()
    W = lil((len(flat_bright), len(flat_bright)))
    for pixel in xrange(len(flat_bright)):
        index, distance = getNeighbors(pixel, radius, n, m)
        for j in xrange(len(index)):
            W[pixel, index[j]] = np.e**(
                -np.absolute(flat_bright[pixel] - flat_bright[index[j]]) /
                sigma_I**2 - (distance[j] / sigma_d**2))
    W = W.tocsc()
    D = W.sum(axis=0)
    return W, D
    def check_size(flds, W, H, min_size, mesh_p=None, fields_dat=None):
        """ Returns the number of fields that are above the minimum size
            as well as a layout indicating the positions and identities
            of the fields and the sizes of the fields. 
            
            Finds fields by generating a 'connections' matrix that
            indicates adjacencies for active cells. 
            We call a 'connected-components' algorithm on the matrix."""

        side = flds.shape[0]
        nodes = flds.shape[0] * flds.shape[1]

        # Create connection matrix
        connections = lil((nodes, nodes))

        for i in range(len(flds)):
            for j in range(len(flds[i])):
                if flds[i, j] != 1:
                    continue
                for xd in [0, 1]:  # This also does -1, implicitly
                    for yd in [0, 1]:  # This also does -1, implicitly
                        if i + xd < side and i + xd >= 0 and j + yd < side and j + yd >= 0:
                            if flds[i + xd, j + yd] == 1:
                                connections[i * side + j, (i + xd) * side + (j + yd)] = 1
                                connections[(i + xd) * side + (j + yd), i * side + j] = 1

        # Determine connected components
        _, labels = cs.cs_graph_components(connections)

        one_node = 1.0 * W * H / (mesh_p ** 2)  # area of one node (m)
        nodes_required_for_fld = min_size / one_node

        # Find labels with min size
        fld_areas = []
        large_enough_flds = []
        for node_num in range(np.amax(labels) + 1):
            if node_num < 0:
                break
            if (labels == node_num).sum() >= nodes_required_for_fld:
                large_enough_flds.append(node_num)
                fld_areas.append((labels == node_num).sum() * one_node)

        # Remap labels back to graph
        labels = labels.reshape([side, side])

        if large_enough_flds == []:
            fld_layout = np.zeros([side, side])
        else:
            fld_layout = sum([labels == component for component in large_enough_flds])

        return len(large_enough_flds), fld_layout, fld_areas
Example #4
0
 def der_der_cost ( self, x, state_config, state, epsilon=None ):
     """ The Hessian for this cost function is determined analytically, but
     we need some additional parameters for consistency, and
     to work out the positioning of the Hessian elements. The returned
     matrix is LIL-sparse (Mostly, it's multidiagonal).
     
             
     Parameters
     -----------
     x_dict: ordered dict
         The state as a dictionary
     state_config: oredered dict
         The configuration dictionary
     state: State
         The state is required in some cases to gain access to parameter
         transformations.
     Returns
     ---------
     Hess: sparse matrix
         The hessian for the cost function at `x`
     """
     n = 0
     for param, typo in state_config.iteritems():
         if typo == CONSTANT:
             n += 1
         elif typo == VARIABLE:
             n_elems = x[param].size
             n += n_elems
     
     h = sp.lil ( (n ,n ) )
     i = 0
     isel_param = 0
     for param, typo in state_config.iteritems():
         
         if typo == FIXED: # Default value for all times
             # Doesn't do anything so we just skip
             pass
             
         elif typo == CONSTANT: # Constant value for all times
             # h[i, i ] = 0.0 Matrix is sparse now ;-)
             i += 1                
             
         elif typo == VARIABLE:
             if param in self.required_params:
                 hessian = sp.lil_matrix ( self.gamma[isel_param]*np.dot ( \
                      self.D1,np.eye( self.n_elems )).dot( self.D1.T ) )
                 h[i:(i+n_elems), i:(i+n_elems) ] = hessian
                 isel_param += 1
                 i += n_elems
     return h
Example #5
0
    def der_der_cost(self, x, state_config, state, epsilon=None):
        """ The Hessian for this cost function is determined analytically, but
        we need some additional parameters for consistency, and
        to work out the positioning of the Hessian elements. The returned
        matrix is LIL-sparse (Mostly, it's multidiagonal).
        
                
        Parameters
        -----------
        x_dict: ordered dict
            The state as a dictionary
        state_config: oredered dict
            The configuration dictionary
        state: State
            The state is required in some cases to gain access to parameter
            transformations.
        Returns
        ---------
        Hess: sparse matrix
            The hessian for the cost function at `x`
        """
        n = 0
        for param, typo in state_config.iteritems():
            if typo == CONSTANT:
                n += 1
            elif typo == VARIABLE:
                n_elems = x[param].size
                n += n_elems

        h = sp.lil((n, n))
        i = 0
        isel_param = 0
        for param, typo in state_config.iteritems():

            if typo == FIXED:  # Default value for all times
                # Doesn't do anything so we just skip
                pass

            elif typo == CONSTANT:  # Constant value for all times
                # h[i, i ] = 0.0 Matrix is sparse now ;-)
                i += 1

            elif typo == VARIABLE:
                if param in self.required_params:
                    hessian = sp.lil_matrix ( self.gamma[isel_param]*np.dot ( \
                         self.D1,np.eye( self.n_elems )).dot( self.D1.T ) )
                    h[i:(i + n_elems), i:(i + n_elems)] = hessian
                    isel_param += 1
                    i += n_elems
        return h
Example #6
0
def buildMatrices1(Nr,Nz,alpha_para,alpha_perp,deltar,deltat,deltaz):
    N=Nr*Nz;
    
    "step 1"
    B=lil((N,N));
    C=lil((N,N));
    "step2"
    D=lil((N,N));
    E=lil((N,N));
    
    "Coefficients"
    b = alpha_para/deltar**2
    d = alpha_perp/deltaz**2
    a = 2*((1/deltat) + b )
    c = 2*((1/deltat) - d )
    e = 2*((1/deltat) + d )
    f = 2*((1/deltat) - b )
    
    "Construction des Matrices de coefficients Step 1"
    
    for i in range(0,Nr):
        for j in range(0,Nz): 
    
            pl=i+j*Nr

            if (i==0) |  (i==Nr-1) |  (j==0) |  (j==Nz-1):
    
                pc=pl
                'Ces elements ne change pas au cours du temps'
                B[pl,pc]=1;
                C[pl,pc]=1;
            else :
    
                'indexe de colonne pour la matrice B'
                pc=pl;
                B[pl,pc]=a;
                pc=pl+1;
                B[pl,pc]=-b;
                pc=pl-1;
                B[pl,pc]=-b;
                'indexe de colonne pour la matrice C'
                pc=pl;
                C[pl,pc]=c;
                pc=i+(j-1)*Nr;
                C[pl,pc]=d;
                pc=i+(j+1)*Nr;
                C[pl,pc]=d;
        
    "Construction des Matrices de coefficients Step 2"
    
    "Afin que le systeme forme une matrice tridiagonale on doit changer "
    "l'indexation (pl change). Ainsi, les vecteurs solutions, et temperature "
    "initiale sont indexé differament aux Step1(on utilise alors les fonctions dans Utility "
    
   
    for i in range(0,Nr): 
        for j in range(0,Nz):
            pl=j+i*Nz
            
            if (i==0) |  (i==Nr-1) |  (j==0) |  (j==Nz-1):
    
                pc=pl
                'Ces elements ne change pas au cours du temps'
                D[pl,pc]=1;
                E[pl,pc]=1;
            else :
                'pc indexe de colonne pour la matrice D'
                pc=pl;
                D[pl,pc]=e;
                pc=pl+1;
                D[pl,pc]=-d;
                pc=pl-1;
                D[pl,pc]=-d;
                'pc indexe de colonne pour la matrice E'
                pc=pl;
                E[pl,pc]=f;
                pc=j+(i-1)*Nz;
                E[pl,pc]=b;
                pc=j+(i+1)*Nz;
                E[pl,pc]=b;
                
                
    B=B.tocsr()
    C=C.tocsr()
    D=D.tocsr()
    E=E.tocsr()
                
    return B,C,D,E
Example #7
0
def BuildMatrices2(Nr,Nz,alpha_para,alpha_perp,deltar,deltat,deltaz,source):
    N=Nr*Nz;
    
    "step 1"
    B=lil((N,N));
    C=lil((N,N));
    "step2"
    D=lil((N,N));
    E=lil((N,N));
    
    "Coefficients"
    b = alpha_para/deltar**2
    d = alpha_perp/deltaz**2
    a = 2*((1/deltat) + b )
    c = 2*((1/deltat) - d )
    e = 2*((1/deltat) + d )
    f = 2*((1/deltat) - b )
    
    "Construction des Matrices de coefficients Step 1"
    
    for i in range(0,Nr):
        for j in range(0,Nz): 
    
            pl=i+j*Nr

            if  (i==Nr-1) |  (j==Nz-1):
    
                pc=pl
                'Ces elements ne change pas au cours du temps'
                B[pl,pc]=1;
                C[pl,pc]=1;
                
            elif (i==0) :
                'indexe de colonne pour la matrice B'
                pc=pl;
                B[pl,pc]=-(1+deltaz*h/k);
                pc=pl+1;
                B[pl,pc]=-1;
                'indexe de colonne pour la matrice C, la temperature d''un noeud'
                'ayant la temperature exterieure. enbas a droite de la maille'
                pl=(Ni-1)+(Nz-1)*Nr;
                pc=pl;
                C[pl,pc]=deltaz*h/k;
                
            elif (j==0) :
                
                
            else :
                'indexe de colonne pour la matrice B'
                pc=pl;
                B[pl,pc]=a;
                pc=pl+1;
                B[pl,pc]=-b;
                pc=pl-1;
                B[pl,pc]=-b;
                'indexe de colonne pour la matrice C'
                pc=pl;
                C[pl,pc]=c;
                pc=i+(j-1)*Nr;
                C[pl,pc]=d;
                pc=i+(j+1)*Nr;
                C[pl,pc]=d;
        
    "Construction des Matrices de coefficients Step 2"
    
    "Afin que le systeme forme une matrice tridiagonale on doit changer "
    "l'indexation (pl change). Ainsi, les vecteurs solutions, et temperature "
    "initiale sont indexé differament aux Step1(on utilise alors les fonctions dans Utility "
    
   
    for i in range(0,Nr): 
        for j in range(0,Nz):
            pl=j+i*Nz
            
            if (i==0) |  (i==Nr-1) |  (j==0) |  (j==Nz-1):
    
                pc=pl
                'Ces elements ne change pas au cours du temps'
                D[pl,pc]=1;
                E[pl,pc]=1;
            else :
                'pc indexe de colonne pour la matrice D'
                pc=pl;
                D[pl,pc]=e;
                pc=pl+1;
                D[pl,pc]=-d;
                pc=pl-1;
                D[pl,pc]=-d;
                'pc indexe de colonne pour la matrice E'
                pc=pl;
                E[pl,pc]=f;
                pc=j+(i-1)*Nz;
                E[pl,pc]=b;
                pc=j+(i+1)*Nz;
                E[pl,pc]=b;
                
                
    B=B.tocsr()
    C=C.tocsr()
    D=D.tocsr()
    E=E.tocsr()
                
    return B,C,D,E

    "vecteur en step1 reordonée en step2"

    def from1to2(vector,Nr,Nz):
        a=vector.copy()
        newVector=np.zeros((Nr*Nz,1))
        
        for i in range(0,Nr):
            for j in range(0,Nz):
                pl1=i+j*Nr
                pl2=j+i*Nz
    
                newVector[pl2]=a[pl1]
        return newVector
    
    "step2 to step1"
    def from2to1(vector,Nr,Nz):
        a=vector.copy()
        newVector=np.zeros((Nr*Nz,1))
        
        for i in range(0,Nr):
            for j in range(0,Nz):
                pl1=i+j*Nr
                pl2=j+i*Nz
                newVector[pl1]=a[pl2]
        return newVector
Example #8
0
def buildMatrix(Nr, Nz, alpha_para, alpha_perp, deltar, deltat, deltaz, pC, h,
                Tp):
    N = Nr * Nz

    "B*T(n+1)=C*T+D"
    B = lil((N, N))
    C = lil((N, N))
    D = lil((N, 1))

    "Coefficients"
    b = alpha_perp * deltat / (2 * deltar**2)
    c = alpha_para * deltat / (2 * deltaz**2)
    a = 1 + 2 * b + 2 * c
    d = 1 - 2 * b - 2 * c
    "Construction des Matrices de coefficients Step 1"

    for i in range(0, Nr):
        for j in range(0, Nz):

            pl = i + j * Nr
            "T=Tp"
            if (i == Nr - 1) | (j == Nz - 1):

                pc = pl
                'Ces elements ne change pas au cours du temps'
                B[pl, pc] = 1

                D[pl, 0] = Tp

            elif (j == 0):

                'indexe de colonne pour la matrice B'
                pc = pl
                B[pl, pc] = -(3 + h * deltaz / (alpha_para * pC))
                pc = i + (j + 1) * Nr
                B[pl, pc] = 4
                pc = i + (j + 2) * Nr
                B[pl, pc] = -1

                D[pl, 0] = -deltaz * h * Tp / (alpha_para * pC)

            elif (i == 0):
                pc = pl
                B[pl, pc] = -3
                pc = pl + 1
                B[pl, pc] = 4
                pc = pl + 2
                B[pl, pc] = -1

                D[pl, 0] = 0

            elif (j != 0) and (j != Nz - 1) and (i != 0) and (i != Nr - 1):
                'indexe de colonne pour la matrice B'
                'termes en i'
                pc = pl
                B[pl, pc] = a
                pc = pl + 1
                B[pl, pc] = -b
                pc = pl - 1
                B[pl, pc] = -b
                'termes en j'
                pc = i + (j + 1) * Nr
                B[pl, pc] = -c
                pc = i + (j - 1) * Nr
                B[pl, pc] = -c
                'indexe de colonne pour la matrice C'
                'termes en i'
                pc = pl
                C[pl, pc] = d
                pc = pl + 1
                C[pl, pc] = b
                pc = pl - 1
                C[pl, pc] = b
                'termes en j'
                pc = i + (j + 1) * Nr
                C[pl, pc] = c
                pc = i + (j - 1) * Nr
                C[pl, pc] = c

            else:
                print("missing matrix coefficient")

    B = B.tocsr()
    C = C.tocsr()
    D = D.tocsr()

    return B, C, D
Example #9
0
def buildMatrix1(Nr, Nz, alpha_para, alpha_perp, deltar, deltat, deltaz, pC, h,
                 Tp):
    N = Nr * Nz

    "B*T(n+1)=C*T+D"
    B = lil((N, N))
    C = lil((N, N))
    D = lil((N, 1))

    "Coefficients"
    b = alpha_perp * deltat / (2 * deltar**2)
    c = alpha_para * deltat / (2 * deltaz**2)
    a = 1 + 2 * b + 2 * c
    d = 1 - 2 * b - 2 * c
    "Construction des Matrices de coefficients Step 1"

    for i in range(0, Nr):
        for j in range(0, Nz):

            pl = i + j * Nr
            "T=Tp"
            if (i == 0) | (i == Nr - 1) | (j == 0) | (j == Nz - 1):
                pc = pl
                'Ces elements ne change pas au cours du temps'
                B[pl, pc] = 1
                C[pl, pc] = 1

            else:
                'indexe de colonne pour la matrice B'
                'termes en i'
                pc = pl
                B[pl, pc] = a
                pc = pl + 1
                B[pl, pc] = -b
                pc = pl - 1
                B[pl, pc] = -b
                'termes en j'
                pc = i + (j + 1) * Nr
                B[pl, pc] = -c
                pc = i + (j - 1) * Nr
                B[pl, pc] = -c

                'indexe de colonne pour la matrice C'
                'termes en i'
                pc = pl
                C[pl, pc] = d
                pc = pl + 1
                C[pl, pc] = b
                pc = pl - 1
                C[pl, pc] = b
                'termes en j'
                pc = i + (j + 1) * Nr
                C[pl, pc] = c
                pc = i + (j - 1) * Nr
                C[pl, pc] = c

    B = B.tocsr()
    C = C.tocsr()
    D = D.tocsr()

    return B, C, D