Example #1
0
def multi_intersect (input):

    """ A function for finding the intersection of several different arrays

    Parameters
    ----------
    input is a tuple of arrays, with all the different arrays 

    Returns
    -------
    array - the intersection of the inputs

    Notes
    -----
    Simply runs intersect1d_nu iteratively on the inputs

    
    """
    
    output = np.intersect1d_nu(input[0], input[1])

    for i in input:

        output = np.intersect1d_nu(output,i)

    return output
Example #2
0
 def _get_dofs_for_nodes( self, nodes ):
     '''Get the dof numbers and associated coordinates
     given the array of nodes.
     '''
     doffed_nodes = self._get_doffed_nodes()
     intersect_nodes = intersect1d_nu( nodes, doffed_nodes )
     return ( self.dofs[ index_exp[ intersect_nodes ] ],
             self.cell_grid.point_X_arr[  index_exp[ intersect_nodes] ] )
Example #3
0
def triangulate(G, order):
    """
    This function ensures that the input graph is triangulated (chordal),
    i.e., every cycle of length > 3 has a chord. To find the maximal
    cliques, we save each induced cluster (created by adding connecting
    neighbors) that is not a subset of any previously saved cluster. (A
    cluster is a complete, but not necessarily maximal, set of nodes.)

    Parameters
    ----------
    G: Numpy ndarray
        G[i,j] = 1 iff there is an edge between node i and node j.

    order: List
        The order in which to eliminate the nodes.
    """
    MG = G.copy()
    
    """Obtain the the number of nodes in the graph"""
    n = G.shape[0]
    eliminated = np.zeros((1,n))
    cliques = []
    for i in range(0,n):
        """Obtain the index of the next node to be eliminated"""
        u = order[0,i]
        U = find(eliminated == 0)
        nodes = np.intersect1d_nu(neighbours(G, u), U)
        nodes = np.union1d(nodes, np.array([u]))
        """
        Connect all uneliminated neighbours of the node to be eliminated
        together.
        """
        for i in nodes:
            for j in nodes:
                G[i, j] = 1
        G = setdiag(G, 0)

        """Mark the node as 'eliminated'"""
        eliminated[0, u] = 1

        """
        If the generated clique is a subset of an existing clique, then it is
        not a maximal clique, so it is excluded from the list if cliques.
        """
        exclude = False
        for c in range(0, len(cliques)):
            if issubset(nodes, np.array(cliques[c])):
                exclude = True
                break

        if not exclude:
            cliques.append(nodes)

    return [G, cliques]
Example #4
0
def triangulate(G, order):
    """
    This function ensures that the input graph is triangulated (chordal),
    i.e., every cycle of length > 3 has a chord. To find the maximal
    cliques, we save each induced cluster (created by adding connecting
    neighbors) that is not a subset of any previously saved cluster. (A
    cluster is a complete, but not necessarily maximal, set of nodes.)

    Parameters
    ----------
    G: Numpy ndarray
        G[i,j] = 1 iff there is an edge between node i and node j.

    order: List
        The order in which to eliminate the nodes.
    """
    MG = G.copy()
    """Obtain the the number of nodes in the graph"""
    n = G.shape[0]
    eliminated = np.zeros((1, n))
    cliques = []
    for i in range(0, n):
        """Obtain the index of the next node to be eliminated"""
        u = order[0, i]
        U = find(eliminated == 0)
        nodes = np.intersect1d_nu(neighbours(G, u), U)
        nodes = np.union1d(nodes, np.array([u]))
        """
        Connect all uneliminated neighbours of the node to be eliminated
        together.
        """
        for i in nodes:
            for j in nodes:
                G[i, j] = 1
        G = setdiag(G, 0)
        """Mark the node as 'eliminated'"""
        eliminated[0, u] = 1
        """
        If the generated clique is a subset of an existing clique, then it is
        not a maximal clique, so it is excluded from the list if cliques.
        """
        exclude = False
        for c in range(0, len(cliques)):
            if issubset(nodes, np.array(cliques[c])):
                exclude = True
                break

        if not exclude:
            cliques.append(nodes)

    return [G, cliques]
Example #5
0
    def _find_EF(self, vlist, E):
        for i in range(0, E.shape[0]):
            enodes = E[i, :]
            if len(numpy.intersect1d_nu(vlist, enodes)) == len(vlist):
                # found element.  now the face
                missing_node = numpy.setdiff1d(enodes, vlist)
                loc = numpy.where(enodes == missing_node)[0][0]

                # determine face from missing id
                if len(enodes) == 3:  # tri
                    face_map = {0: 1, 1: 2, 2: 0}
                if len(enodes) == 4:  # tet
                    face_map = {0: 2, 1: 3, 2: 1, 3: 0}

                return i, face_map[loc]
Example #6
0
def invoke(combinations, opposed, invoked):

    elem = []
    for c in invoked:
        if not len(elem):
            elem.append(c)
        else:
            comb = elem[-1] + c
            if comb in combinations:
                elem[-1] = combinations[comb]
            else:
                elem.append(c)

            newcombs = [elem[-1] + e for e in elem[:-1]]
            if len(np.intersect1d_nu(newcombs, opposed)):
                elem = []

    return elem
Example #7
0
    def _surf_match_area_quant(self,surfs_request,next_surfs):
        nextsurfs_quant = self._quantify(next_surfs)
        surfs_request_quant = self._quantify(surfs_request)

        corresponding_surf = len(numpy.intersect1d_nu(surfs_request_quant,nextsurfs_quant))
        return corresponding_surf,len(surfs_request)
Example #8
0
    print '====== Parsing RDF entries from ', begin_line, ' to ', end_line, '======'
    #====== Begin Parsing RDF ================
    for line in fread:
	#Making sure of RDF range
	cur_line +=1
	if cur_line < begin_line:
	    continue
	if cur_line > end_line:
	    break
        
        n=makeNode()     
        if lastresource != n[0]:
        #time to make the previous node, check first if a previous node needs to be made
            if lastresource!="":
                #have we met this category before ?
                match = np.intersect1d_nu([lastresource], node_list) 
                if len(match)<1:
                    # this is a new category, make primary node
                    unode+=1
		    temp1 = 'cat_'+ str(unode)
                    sgraph.add_node(lastresource,  nodeid=temp1, resource=lastresource,  category=lastresource)
                    node_list.append(lastresource)
                    # make secondary nodes
                    try:
			basic_wt = 1.0/len(subcatlist)
		    except ZeroDivisionError:
			#print 'trying to divide by zero at: ', lastresource, 'with subcatlist', subcatlist 
      			nosubcatlist.append(lastresource)              	
		    # Adding subcat nodes to main cat node (should make a function in the future) 
		    for subcat in subcatlist:
                        u2node+=1
Example #9
0
def best_first_elim_order(G, node_sizes, stage=[]):
    """
    This function greedily searches for an optimal elimination order.

    Find an order in which to eliminate nodes from the graph in such a way
    as to try and minimize the weight of the resulting triangulated graph.
    The weight of a graph is the sum of the weights of each of its cliques;
    the weight of a clique is the product of the weights of each of its
    members; the weight of a node is the number of values it can take on.

    Since this is an NP-hard problem, we use the following greedy heuristic:
    At each step, eliminate that node which will result in the addition of
    the least number of fill-in edges, breaking ties by choosing the node
    that induces the lighest clique.

    For details, see
    - Kjaerulff, "Triangulation of graphs -- algorithms giving small total
        state space", Univ. Aalborg tech report, 1990 (www.cs.auc.dk/~uk)
    - C. Huang and A. Darwiche, "Inference in Belief Networks: A procedural
        guide", Intl. J. Approx. Reasoning, 11, 1994

    Parameters
    ----------
    G: Numpy ndarray
        G[i,j] = 1 iff there is an edge between node i and node j.

    node_sizes: List
        The node sizes, where ns[i] = the number of discrete values
        node i can take on [1 if observed].

    stage: List
        stage[i] is a list of the nodes that must be eliminated at i'th
        stage.
    """
    """Obtain the number of nodes in the graph"""
    n = G.shape[0]
    if stage == []:
        stage = [range(0, n)]
    MG = G.copy()
    uneliminated = np.ones((1, n))
    order = np.zeros((1, n))
    t = 0

    """For each node in the graph"""
    for i in range(0, n):
        """Find the indices of the unelminated elements"""
        U = find(uneliminated == 1)

        """Find which nodes can be removed in this stage."""
        valid = np.intersect1d_nu(np.array(U), np.array([stage[t]]))

        """
        Determine which of the valid nodes will add the least number of fill in
        edges once eliminated. If 2 or more nodes add the same least number of
        fill in edges, then choose the one that results in the lightest clique.
        """
        min_fill = np.zeros((1, len(valid)))
        min_weight = np.zeros((1, len(valid)))
        """For each node that is valid for elimination"""
        for j in range(0, len(valid)):
            k = valid[j]
            
            """Obtain the uneliminated neighbours of the node to be eliminated"""
            nbrs = neighbours(G, k)
            nbrs = np.intersect1d_nu(np.array([nbrs]), np.array(U))
            l = len(nbrs)
            M = np.zeros((l, l))
            count = 0
            for x in nbrs:
                for y in range(0, len(nbrs)):
                    M[count, y] = MG[x, nbrs[y]]
                count = count + 1

            """Save the number of fill-in edges required to eliminate node j"""
            min_fill[0, j] = l**2 - np.sum(M)
            nbrs = nbrs.tolist()
            nbrs.insert(0, k)
            """Save the clique weight obtained by eliminating node j"""
            min_weight[0, j] = np.prod(node_sizes[nbrs])

        """Determine which of the nodes create the lightest clique."""
        lightest_nbrs = find(min_weight == np.min(min_weight))
        
        """
        Determine which of nodes found in the step above, require the least
        number of fill-in edges to eliminate.
        """
        best_nbr_ndx = np.argmin(min_fill[0, lightest_nbrs.tolist()])
        j = lightest_nbrs[0, best_nbr_ndx]
        
        """
        Determine which of the nodes found in the step above are valid for
        elimination, these are the nodes to be eliminated.
        """
        k = valid[j]
        uneliminated[0, k] = 0
        
        """Add the nodes to be eliminated to the elimination order"""
        order[0, i] = k
        
        """Determine the nieghbours of the nodes to be eliminated"""
        ns = neighbours(G, k)
        ns = np.intersect1d_nu(np.array([ns]), np.array(U))
        
        """Eliminate the nodes"""
        if len(ns) != 0:
            for x in ns:
                for y in ns:
                    G[x, y] = 1
            G = setdiag(G, 0)

        """
        If all the nodes valid for elimination in this stage have been
        eliminated, then advance to the next stage.
        """
        if np.sum(np.abs(uneliminated[0, stage[t]])) == 0:
            t = t + 1
    return order
Example #10
0
def best_first_elim_order(G, node_sizes, stage=[]):
    """
    This function greedily searches for an optimal elimination order.

    Find an order in which to eliminate nodes from the graph in such a way
    as to try and minimize the weight of the resulting triangulated graph.
    The weight of a graph is the sum of the weights of each of its cliques;
    the weight of a clique is the product of the weights of each of its
    members; the weight of a node is the number of values it can take on.

    Since this is an NP-hard problem, we use the following greedy heuristic:
    At each step, eliminate that node which will result in the addition of
    the least number of fill-in edges, breaking ties by choosing the node
    that induces the lighest clique.

    For details, see
    - Kjaerulff, "Triangulation of graphs -- algorithms giving small total
        state space", Univ. Aalborg tech report, 1990 (www.cs.auc.dk/~uk)
    - C. Huang and A. Darwiche, "Inference in Belief Networks: A procedural
        guide", Intl. J. Approx. Reasoning, 11, 1994

    Parameters
    ----------
    G: Numpy ndarray
        G[i,j] = 1 iff there is an edge between node i and node j.

    node_sizes: List
        The node sizes, where ns[i] = the number of discrete values
        node i can take on [1 if observed].

    stage: List
        stage[i] is a list of the nodes that must be eliminated at i'th
        stage.
    """
    """Obtain the number of nodes in the graph"""
    n = G.shape[0]
    if stage == []:
        stage = [range(0, n)]
    MG = G.copy()
    uneliminated = np.ones((1, n))
    order = np.zeros((1, n))
    t = 0
    """For each node in the graph"""
    for i in range(0, n):
        """Find the indices of the unelminated elements"""
        U = find(uneliminated == 1)
        """Find which nodes can be removed in this stage."""
        valid = np.intersect1d_nu(np.array(U), np.array([stage[t]]))
        """
        Determine which of the valid nodes will add the least number of fill in
        edges once eliminated. If 2 or more nodes add the same least number of
        fill in edges, then choose the one that results in the lightest clique.
        """
        min_fill = np.zeros((1, len(valid)))
        min_weight = np.zeros((1, len(valid)))
        """For each node that is valid for elimination"""
        for j in range(0, len(valid)):
            k = valid[j]
            """Obtain the uneliminated neighbours of the node to be eliminated"""
            nbrs = neighbours(G, k)
            nbrs = np.intersect1d_nu(np.array([nbrs]), np.array(U))
            l = len(nbrs)
            M = np.zeros((l, l))
            count = 0
            for x in nbrs:
                for y in range(0, len(nbrs)):
                    M[count, y] = MG[x, nbrs[y]]
                count = count + 1
            """Save the number of fill-in edges required to eliminate node j"""
            min_fill[0, j] = l**2 - np.sum(M)
            nbrs = nbrs.tolist()
            nbrs.insert(0, k)
            """Save the clique weight obtained by eliminating node j"""
            min_weight[0, j] = np.prod(node_sizes[nbrs])
        """Determine which of the nodes create the lightest clique."""
        lightest_nbrs = find(min_weight == np.min(min_weight))
        """
        Determine which of nodes found in the step above, require the least
        number of fill-in edges to eliminate.
        """
        best_nbr_ndx = np.argmin(min_fill[0, lightest_nbrs.tolist()])
        j = lightest_nbrs[0, best_nbr_ndx]
        """
        Determine which of the nodes found in the step above are valid for
        elimination, these are the nodes to be eliminated.
        """
        k = valid[j]
        uneliminated[0, k] = 0
        """Add the nodes to be eliminated to the elimination order"""
        order[0, i] = k
        """Determine the nieghbours of the nodes to be eliminated"""
        ns = neighbours(G, k)
        ns = np.intersect1d_nu(np.array([ns]), np.array(U))
        """Eliminate the nodes"""
        if len(ns) != 0:
            for x in ns:
                for y in ns:
                    G[x, y] = 1
            G = setdiag(G, 0)
        """
        If all the nodes valid for elimination in this stage have been
        eliminated, then advance to the next stage.
        """
        if np.sum(np.abs(uneliminated[0, stage[t]])) == 0:
            t = t + 1
    return order