Beispiel #1
0
    def addEdge(self, point):
        if (self.adding):
            self.adding = False
        else:
            for node in self.nodes:
                if (node.insideNode(point, self.padding)):

                    if (node in self.edge):
                        self.edge = []
                        node.color = Node.default_color
                    else:
                        self.edge.append(node)
                    self.edge_sound.play()

                    if len(self.edge) == 2:
                        if (Edge(self.edge[0], self.edge[1]) not in self.edges):
                            edge = Edge(self.edge[0], self.edge[1], self.directed,self.surface, self.screen)
                            self.edges.append(edge)
                            self.edge[0].addConnection(node, edge)
                            if not(self.directed):
                                self.edge[1].addConnection(self.edge[0], edge)
                        
                        self.edge[0].color = Node.default_color


                        self.edge = []
Beispiel #2
0
def test_graph():
    g1 = TermGraph()
    v1 = Vertex('vert1', 2)
    v2 = Vertex('vert2', 2)
    e1 = Edge(v1, v2)
    g1.add_edge(e1)

    v3 = Vertex('vert3', 3)
    v4 = Vertex('vert4', 4)
    e2 = Edge(v3, v4)
    g1.add_edge(e2)

    e3 = Edge(v1, v4)
    g1.add_edge(e3)
    g1.add_edge(e1)

    print g1._verticlesJoins
    print g1._verticles
    print g1._edges

    g1.recalc_edges()
    g1.recalc_vert_weights()
    g1.recalc_vert_weights()

    for x in xrange(0, 10):
        print '--------' + str(x) + '------'
        g1.recalc_vert_weights()
Beispiel #3
0
    def __init__(self, numInputNeurons, numHiddenLayers):

        # Create Layers
        self.inputLayer = [Neuron() for _ in range(numInputNeurons)]
        self.numHiddenLayers = numHiddenLayers
        self.hiddenLayers = [[Neuron() for _ in range(numInputNeurons)]
                             for _ in range(numHiddenLayers)]
        self.outputNeuron = Neuron()

        if numHiddenLayers > 0:
            # Create edges to connect input neurons to first hidden layer neurons (if exists)
            for i_neuron in self.inputLayer:
                for h_neuron in self.hiddenLayers[0]:
                    Edge(i_neuron, h_neuron)

            # Create edges to connect hidden layer neurons to each other
            for h_layer1, h_layer2 in [
                (self.hiddenLayers[i], self.hiddenLayers[i + 1])
                    for i in range(self.numHiddenLayers - 1)
            ]:
                for h_neuron1 in h_layer1:
                    for h_neuron2 in h_layer2:
                        Edge(h_neuron1, h_neuron2)

            # Create edges to connect last hidden layer neurons to output neuron
            for h_neuron in self.hiddenLayers[-1]:
                Edge(h_neuron, self.outputNeuron)

        else:
            # Create edges to connect input neurons to output neuron
            for i_neuron in self.inputLayer:
                Edge(i_neuron, self.outputNeuron)
Beispiel #4
0
    def create_edges(self):
        unused_edges = set(
            sum(
                map(lambda b: [Edge(a, b) for a in range(b + 1, self.n)],
                    range(self.n)), []))
        edge_set = set()
        #first connect the unconnected edges
        for node in range(1, self.n):
            rand = random.randint(0, node - 1)
            a = max(rand, node)
            b = min(rand, node)
            new_edge = Edge(a, b)
            edge_set.add(new_edge)
            unused_edges.remove(new_edge)

        while len(edge_set) < self.e:
            new_edge = random.sample(unused_edges, 1)[0]
            edge_set.add(new_edge)
            unused_edges.remove(new_edge)

        edges = [[0] * m for m in range(self.n)]

        for e in edge_set:
            edges[e.a][e.b] = 1

        return edges
Beispiel #5
0
    def create_simple(self):
        node_names = ['x', 'a', 's', 'b']
        node_pos = [(0, 10), (-10, 0), (0, 0), (10, 0)]
        nodes_dict = {}

        # Create nodes and add them to the dictionary
        for index in range(0, len(node_names)):
            key = node_names[index]
            value = Node(node_names[index], node_pos[index])
            nodes_dict[key] = value

        edges_dict = {}
        e1 = Edge( "e1", nodes_dict['s'], nodes_dict['x'], 90, 270)
        e2 = Edge( "e2", nodes_dict['a'], nodes_dict['s'], 0, 180)
        e3 = Edge( "e3", nodes_dict['b'], nodes_dict['s'], 180, 0)

        edges_dict['sx'] = e1
        edges_dict['as'] = e2
        edges_dict['bs'] = e3

        # add e1 to both vertices
        nodes_dict['s'].edges.append(e1)
        nodes_dict['x'].edges.append(e1)

        # add e2 to both vertices
        nodes_dict['a'].edges.append(e2)
        nodes_dict['s'].edges.append(e2)

        # add e3 to both vertices
        nodes_dict['b'].edges.append(e3)
        nodes_dict['s'].edges.append(e3)

        # set class vars
        self.nodes_dict = nodes_dict
        self.edges_dict = edges_dict
    def ClipWithBottomLeftCorner(self, dcel):

        # find clipping points
        x = dcel.lx
        y = dcel.GetYOfParabolaIntersectionGivenX(
            self.triplet.middle.siteEvent, self.triplet.middle.siteEvent, x)
        leftClip = Vertex(x, y)
        dcel.vertexList.Add(leftClip)

        y = dcel.ly
        x = dcel.GetXOfParabolaIntersectionGivenY(
            self.triplet.middle.siteEvent, self.triplet.left.siteEvent, y)
        bottomClip = Vertex(x, y)
        dcel.vertexList.Add(bottomClip)

        # create two pseudo edges for the clips for the middle face
        cornerLeft = Edge(True)
        cornerBottom = Edge(bottomClip, True)
        dcel.edgeList.Add(cornerLeft)
        dcel.edgeList.Add(cornerBottom)

        self.triplet.middle.siteEvent.face.AppendToForwardList(cornerBottom)
        self.triplet.middle.siteEvent.face.PrependToBackwardList(
            cornerLeft, leftClip)

        # create another bottom left vertex
        bottomLeftCorner = Vertex(dcel.lx, dcel.ly, True)
        dcel.vertexList.Add(bottomLeftCorner)
        self.triplet.middle.siteEvent.face.ConnectBackwardAndForwardListsAt(
            bottomLeftCorner)
    def test_scenario_03(self):
        graph = Graph(3)
        graph.add_edge(Edge("s1", "s2", 1))
        graph.add_edge(Edge("s2", "s3", 1))
        graph.add_edge(Edge("s3", "s4", 1))
        graph.add_edge(Edge("s4", "s5", 1))
        graph.add_edge(Edge("s3", "s6", 1))

        graph.partition(weight_criteria=3.0,
                        merge_criteria=0.0,
                        backwards=False)

        self.assertEqual(len(graph.partitions), 2,
                         "There should be 2 partitions")
        self.assertEqual(True, {'s1', 's2', 's3', 's4',
                                's6'} in graph.partitions,
                         "{'s1', 's2', 's3', 's4', 's6'} missing")
        self.assertEqual(True, {'s5'} in graph.partitions, "{'s5'} missing")

        max_node_weights = set(
            [graph.find_max_node_weight_in_partitions(i) for i in range(0, 2)])
        self.assertEqual(max_node_weights,
                         {0, 3.0}.intersection(max_node_weights),
                         "Partitions should have max node weight of {0, 3.0}")

        longest_paths = set(
            [graph.find_longest_path_in_partitions(i) for i in range(0, 2)])
        self.assertEqual(
            longest_paths, {0, 3.0}.intersection(longest_paths),
            "Partitions should have longest paths of size {0, 3.0}")
Beispiel #8
0
    def init_edge_list(self):
        area = self.num_cols * self.num_rows
        priority = PriorityQ()

        for row in range(self.num_rows):
            for col in range(self.num_cols):
                curr_node = self.grid[row][col]

                # if possible create a mock edge between current node add
                # node above
                if row > 0:
                    up_neighbor = self.grid[row - 1][col]
                    edge_1 = Edge(curr_node, up_neighbor, rand.randrange(area))
                    edge_2 = Edge(up_neighbor, curr_node, rand.randrange(area))
                    priority.insert(edge_1)
                    priority.insert(edge_2)

                # if possible create a mock edge between current node add
                # node to the right
                if col > 0:
                    left_neighbor = self.grid[row][col - 1]
                    edge_1 = Edge(curr_node, left_neighbor,
                                  rand.randrange(area))
                    edge_2 = Edge(left_neighbor, curr_node,
                                  rand.randrange(area))
                    priority.insert(edge_1)
                    priority.insert(edge_2)

        return priority
Beispiel #9
0
    def addEdge(self, origin, goal, value, double=False):

        new = Edge()
        new.origin = origin
        new.goal = goal
        new.value = value

        new.pX.append(origin.x)
        new.pY.append(origin.y)
        new.pX.append(goal.x)
        new.pY.append(goal.y)

        origin.edges.append(new)

        if (double):

            new.isDouble = True

            new = Edge()  # Create counter edge!
            new.origin = goal
            new.goal = origin
            new.value = value

            new.pX.append(goal.x)
            new.pY.append(goal.y)
            new.pX.append(origin.x)
            new.pY.append(origin.y)

            goal.edges.append(new)
            new.isDouble = True
Beispiel #10
0
    def __SetNodeNeighbors(self, node, data, i, j):
        # Pentru fiecare verific daca pozitia vecinului este un element din clasa sau nu este un loc liber
        if i - 1 >= 0 and data[i - 1][j] != "liber":
            node2 = Node(data[i - 1][j])
            edge = Edge(node, node2, 1)
            self.edges.append(edge)

        if i + 1 < len(data) and data[i + 1][j] != "liber":
            node2 = Node(data[i + 1][j])
            edge = Edge(node, node2, 1)
            self.edges.append(edge)
        #cand schimba coloana verific daca are coleg de banca in dreapta sau daca este in ultimele doua bangi
        if j - 1 >= 0 and data[i][j - 1] != "liber":
            if j % 2 != 0 or i > len(
                    data[i]
            ) - 2:  #daca sunt in ultimele 2 randuri sau au coleg de banca in dreapta
                node2 = Node(data[i][j - 1])
                edge = Edge(node, node2, 1)
                self.edges.append(edge)
        if j + 1 < len(data[i]) and data[i][j + 1] != "liber":
            if j % 2 == 0 or i > len(
                    data[i]
            ) - 2:  #daca sunt in ultimele 2 randuri sau au coleg de banca in dreapta
                node2 = Node(data[i][j + 1])
                edge = Edge(node, node2, 1)
                self.edges.append(edge)
    def addNode(self, node, friendNodes): # friendNodes er en liste med Node-objekter som allerede eksisterer

        if node in self.nodes.values():
            if not friendNodes:
                print("The node '" + node.getName() + "' already exists.")
            else:
                for friend in friendNodes:
                    if self.edgeExist(node, friend):
                        continue
                    else:
                        if friend not in self.nodes.values():
                            self.nodes[friend.getName()] = friend
                        newEdge = Edge(node, friend)
                        node.addEdge(newEdge)
                        friend.addEdge(newEdge)
                        self.edges.append(newEdge)
        else:
            if not friendNodes:
                self.nodes[node.getName()] = node
            else:
                self.nodes[node.getName()] = node
                for friend in friendNodes:
                    if self.edgeExist(node, friend):
                        continue
                    else:
                        newEdge = Edge(node, friend)
                        node.addEdge(newEdge)
                        friend.addEdge(newEdge)
                        self.edges.append(newEdge)
Beispiel #12
0
    def __init__(self, numpoints, dimension, k_n):

        self.Dimension = dimension  # dimension of vertex

        self.V = [Vertex(dimension, i)
                  for i in range(numpoints)]  # index range {0,1,2,...,V-1}

        self.num_V = numpoints
        self.num_E = 0  # number of edges in graph

        self.adj = {}  # adjacent list

        # initialize adjacent dictionary
        for i in range(self.num_V):
            self.adj[i] = []

        # if dimension = 0 -> assign weights randomly
        if self.Dimension == 0:
            for i in range(numpoints - 1):
                for j in range(i + 1, numpoints):
                    new_edge = Edge(self.V[i], self.V[j], 'random')
                    if new_edge.weight <= k_n:
                        self.adj[i].append(new_edge)
                        self.adj[j].append(new_edge)
                        self.num_E += 1

        else:
            # initialize edge for complete undirected graph
            for i in range(numpoints - 1):
                for j in range(i + 1, numpoints):
                    if Vertex.Euclidean_distance(self.V[i], self.V[j]) < k_n:
                        new_edge = Edge(self.V[i], self.V[j], 'Euclidean')
                        self.adj[i].append(new_edge)
                        self.adj[j].append(new_edge)
                        self.num_E += 1
Beispiel #13
0
 def DrawEdges(self, NewAnt: Ant):
     for CurrentAnt in self.Ants:
         if CurrentAnt.Address != NewAnt.Address:
             NewEdge = Edge(NewAnt.Address, CurrentAnt.Address, 0, 0, 0)
             self.Network.AddEdge(NewEdge)
             NewEdge = Edge(CurrentAnt.Address, NewAnt.Address, 0, 0, 0)
             self.Network.AddEdge(NewEdge)
Beispiel #14
0
def construct_graph(reads, k=5):
    """ Construct de bruijn graph from sets of short reads with k length word"""
    edges = dict()
    vertices = dict()

    for read in reads:
        i = 0
        while i + k < len(read):
            v1 = read[i:i + k]
            v2 = read[i + 1:i + k + 1]
            if v1 in edges.keys():
                vertices[v1].outdegree += 1
                edges[v1] += [Edge(v2)]
            else:
                vertices[v1] = Node(v1)
                vertices[v1].outdegree += 1
                edges[v1] = [Edge(v2)]
            if v2 in edges.keys():
                vertices[v2].indegree += 1
            else:
                vertices[v2] = Node(v2)
                vertices[v2].indegree += 1
                edges[v2] = []
            i += 1

    return (vertices, edges)
Beispiel #15
0
    def testChangeInQSlow(self):
        self.logger.info("BEGIN")

        n0 = Node(clusterId="c1", nodeId=0)
        n1 = Node(clusterId="c1", nodeId=1)
        n3 = Node(clusterId="c1", nodeId=3)

        e1 = Edge(weight=1.0, srcId=0, targetId=1)
        n0._addEdge(e1)
        e2 = Edge(weight=1.0, srcId=0, targetId=2)
        n0._addEdge(e2)
        e3 = Edge(weight=1.0, srcId=0, targetId=3)
        n0._addEdge(e3)

        e4 = Edge(weight=1.0, srcId=1, targetId=0)
        n1._addEdge(e4)

        e5 = Edge(weight=1.0, srcId=3, targetId=0)
        n3._addEdge(e5)

        cluster1 = Cluster(clusterId="1", nodeList=[n0, n1, n3])

        n2 = Node(clusterId="c2", nodeId=2)
        e6 = Edge(weight=1.0, srcId=2, targetId=0)
        n2._addEdge(e6)

        n4 = Node(clusterId="c2", nodeId=4)
        n5 = Node(clusterId="c2", nodeId=5)
        e7 = Edge(weight=1.0, srcId=4, targetId=5)
        n4._addEdge(e7)
        e8 = Edge(weight=1.0, srcId=5, targetId=4)
        n5._addEdge(e8)

        e9 = Edge(weight=1.0, srcId=4, targetId=2)
        n4._addEdge(e9)

        e10 = Edge(weight=1.0, srcId=2, targetId=4)
        n2._addEdge(e10)

        cluster2 = Cluster(clusterId="2", nodeList=[n2, n4, n5])

        louvain1 = Louvain("changeInQ1", [cluster1, cluster2])

        # calculate modularity of original graph
        self.logger.info("louvain1._Q:{}".format(louvain1._Q))
        self.assertEqual(louvain1._Q, 0.5599999999999999)

        # move node 2 from cluster 2 to cluster 1
        n2._clusterId = "c1"
        cluster1 = Cluster(clusterId="1", nodeList=[n0, n1, n2, n3])
        cluster2 = Cluster(clusterId="2", nodeList=[n4, n5])

        # calculate modularity
        louvain2 = Louvain("changeInQ2", [cluster1, cluster2])
        self.logger.info("louvain2._Q:{}".format(louvain2._Q))
        self.assertEqual(louvain2._Q, 0.5199999999999999)

        self.logger.info("change in modularity:{}".format(louvain1._Q -
                                                          louvain2._Q))
Beispiel #16
0
def create_topology(node_num, edge_num, max_weight, file_path):
    """
    生成有向随机拓扑
    :param node_num: 节点数
    :param edge_num: 边数
    :param max_weight: 最大权重,表示权重范围在(0,max_weight)之间
    :param file_path: 数据写入文件路径
    :return:
    """
    NODE_NUM = node_num  # 节点数
    EDGE_NUM = edge_num  # 边数
    MAX_WEIGHT = max_weight  # 最大权重
    list_nodes = {}  # 节点邻接字典
    neighbor_nodes = {}
    tree_nodes = []
    list_nodes[str(1)] = list()
    neighbor_nodes[str(1)] = list()
    tree_nodes.append(1)
    for i in range(2, NODE_NUM + 1):
        tree_nodes.append(i)
        list_nodes[str(i)] = list()
        neighbor_nodes[str(i)] = list()
        new_edge = Edge(random.randint(1, i - 1), i,
                        random.randint(1, MAX_WEIGHT))  # 随机生成一条边
        neighbor_nodes[str(new_edge.get_node_a())].append(
            str(new_edge.get_node_b()))
        list_nodes[str(new_edge.get_node_a())].append(new_edge)
    with open(file_path, 'a') as file:
        for key in list_nodes.keys():
            node_a = key
            for edge in list_nodes[key]:
                node_b = edge.get_node_b()
                weight = edge.get_weight()
                file.write(
                    str(node_a) + '\t' + str(node_b) + '\t' + str(weight) +
                    '\n')
        file.close()
    """
    第二步:随机在两个节点之间添加边
    """
    for i in range(1, EDGE_NUM - NODE_NUM + 2):
        while True:
            node_1 = random.randint(1, NODE_NUM)  # 随机选两个节点连线
            node_2 = random.randint(1, NODE_NUM)
            if node_1 != node_2:  # 边连接的两个节点不是同一个点
                if str(node_2) not in neighbor_nodes[str(
                        node_1)]:  # 如果这两个节点未曾连线
                    # 将该条边加入到
                    new_edge = Edge(node_1, node_2,
                                    random.randint(1, MAX_WEIGHT))
                    list_nodes[str(new_edge.get_node_a())].append(new_edge)
                    neighbor_nodes[str(node_1)].append(str(node_2))
                    # 将该条边
                    with open(file_path, 'a') as file:
                        file.write(
                            str(node_1) + '\t' + str(node_2) + '\t' +
                            str(new_edge.get_weight()) + '\n')
                        file.close()
                    break
Beispiel #17
0
 def __DestroyUpsetsEdges(self, upsets):
     for upset in upsets:  #elimin muchiile dintre perosanele suparate
         node1 = Node(upset[0])
         node2 = Node(upset[1])
         edge = Edge(node1, node2, 1)
         edgeReverse = Edge(node2, node1, 1)
         self.RemoveEdge(edge)
         self.RemoveEdge(edgeReverse)
    def add_edge(self, n, m, weight):
        assert self.v > n >= 0, '请输入正确的节点'
        assert self.v > m >= 0, '请输入正确的节点'

        self.info[n].append(Edge(n, m, weight))
        if n != m and not self.directed:
            self.info[m].append(Edge(m, n, weight))
        self.e += 1
Beispiel #19
0
def MergeDuplicate(nodes, edges, lemmatizer):
    new_nodes = []
    eli_nodes = []
    new_edges = []
    eli_edges = []
    for node1 in nodes:
        word1 = node1.getWord()
        node1_in_edges = []
        # list of edges that point TO node1
        node1_out_edges = []
        # list of edges that point FROM node1
        node2_in_edges = []
        # list of edges that point TO node2
        node2_out_edges = []
        # list of edges that point FROM node2
        for node2 in nodes:
            word2 = node2.getWord()
            if (word1 != word2 and (node1 not in eli_nodes)
                    and (node2 not in eli_nodes) and
                (word1.lower() == word2.lower() or lemmatizer.lemmatize(
                    word1.lower()) == lemmatizer.lemmatize(word2.lower()))):
                # Start merging
                #	initialize new node
                new_node = Node(word1.title())
                new_node.setwfreq(node1.getfreq() + node2.getfreq())
                if (node1.gettimeAdded() < node2.gettimeAdded()):
                    new_node.setTime(node2.gettimeAdded())
                else:
                    new_node.setTime(node1.gettimeAdded())
                if (new_node.isDump()): continue
                new_nodes.append(new_node)
                #	redirect edges:

                # 	Incomming nodes
                for ed in (node1_in_edges + node2_in_edges):
                    newEdge = Edge(ed.getWord0() + " " + new_node.getWord())
                    newEdge.setefreq(ed.getfreq())
                    newEdge.setTime(ed.gettimeAdded())
                    if not (newEdge.isDump()):
                        new_edges.append(newEdge)
                # 	Outgoing nodes
                for ed in (node1_out_edges + node2_out_edges):
                    newEdge = Edge(new_node.getWord() + " " + ed.getWord1())
                    newEdge.setefreq(ed.getfreq())
                    newEdge.setTime(ed.gettimeAdded())
                    if not (newEdge.isDump()):
                        new_edges.append(newEdge)
                eli_nodes = eli_nodes + [node1, node2]
                eli_edges = eli_edges + node1_in_edges + node1_out_edges + node2_in_edges + node2_out_edges
    # Now interfere the data !!!!!!!!!!!!!!!!
    for ed in eli_nodes:
        edges.discard(ed)
    for nd in eli_nodes:
        nodes.discard(nd)

    edges.update(new_edges)
    nodes.update(new_nodes)
    return (nodes, edges)
Beispiel #20
0
    def add_vertex(self,
                   after_vertex_id,
                   vertex_type='linear',
                   edge_type='identity'):
        '''
        3.0: 所有 vertex 和 edg 中记录的都是引用
        '''
        changed_edge = None
        # 先寻找那条应该被移除的边, 将其删除
        for i in self.vertices[after_vertex_id - 1].edges_out:
            if i.to_vertex == self.vertices[after_vertex_id]:
                self.vertices[after_vertex_id - 1].edges_out.remove(i)
                break
        for i in self.vertices[after_vertex_id].edges_in:
            if i.from_vertex == self.vertices[after_vertex_id - 1]:
                self.vertices[after_vertex_id].edges_in.remove(i)
                break
        for i, edge in enumerate(self.edges):
            if edge.from_vertex == self.vertices[
                    after_vertex_id -
                    1] and edge.to_vertex == self.vertices[after_vertex_id]:
                changed_edge = self.edges[i]

        # 创建新的 vertex, 并加入队列
        vertex_add = Vertex(edges_in=set(), edges_out=set(), type=vertex_type)
        self.vertices.insert(after_vertex_id, vertex_add)

        # 创建新的 edge, 并加入队列
        if edge_type == 'conv':
            depth_f = max(1.0, random.random() * 4)
            filter_h = 1
            filter_w = 1
            stride_s = math.floor(random.random() * 2)
            edge_add1 = Edge(from_vertex=self.vertices[after_vertex_id - 1],
                             to_vertex=self.vertices[after_vertex_id],
                             type='conv',
                             depth_factor=depth_f,
                             filter_half_height=filter_h,
                             filter_half_width=filter_w,
                             stride_scale=0)
            edge_add1.model_id = -1
        else:
            edge_add1 = Edge(from_vertex=self.vertices[after_vertex_id - 1],
                             to_vertex=self.vertices[after_vertex_id],
                             type='identity')
            edge_add1.model_id = -1
        # 取代的那条边后移
        changed_edge.from_vertex = self.vertices[after_vertex_id]
        # edge_add2 = Edge(from_vertex=self.vertices[after_vertex_id],to_vertex=self.vertices[after_vertex_id + 1])
        self.edges.append(edge_add1)
        # self.edges.append(edge_add2)

        self.vertices[after_vertex_id - 1].edges_out.add(edge_add1)
        vertex_add.edges_in.add(edge_add1), vertex_add.edges_out.add(
            changed_edge)
        self.vertices[after_vertex_id + 1].edges_in.add(changed_edge)
Beispiel #21
0
 def addEdge(self, v, w, weight):
     if 0 <= v < self.n and 0 <= w < self.n:
         if self.hasEdge(v, w):
             return
         self.graph[v].append(Edge(v, w, weight))
         if v != w and self.directed is False:
             self.graph[w].append(Edge(w, v, weight))
         self.m += 1
     else:
         raise Exception('Vertex not in the graph')
Beispiel #22
0
 def add_edge(self, from_, to, capacity):
     # Note that we first append a forward edge and then a backward edge,
     # so all forward edges are stored at even indices (starting from 0),
     # whereas backward edges are stored at odd indices.
     forward_edge = Edge(from_, to, capacity)
     backward_edge = Edge(to, from_, 0)
     self.graph[from_].append(len(self.edges))
     self.edges.append(forward_edge)
     self.graph[to].append(len(self.edges))
     self.edges.append(backward_edge)
Beispiel #23
0
 def addEdge(self, v, w, weight):
     if 0 <= v < self.n and 0 <= w < self.n:
         if self.hasEdge(v, w):
             return
         self.martix[v][w] = Edge(v, w, weight)
         if v != w and self.directed is False:
             self.martix[w][v] = Edge(v, w, weight)
         self.m += 1
     else:
         raise Exception('Vertex not in the graph')
Beispiel #24
0
 def addEdge(self, start_node_id, end_node_id, value):
     for node in self.__nodeMap.keys():
         if node.getID() == start_node_id:
             start_node = node
         if node.getID() == end_node_id:
             end_node = node
     if not self.edgeExist(start_node, end_node):
         new_edge = Edge(start_node, end_node, value)
         self.__nodeMap[start_node].append(new_edge)
         new_edge = Edge(end_node, start_node, value)
         self.__nodeMap[end_node].append(new_edge)
Beispiel #25
0
    def addEadge(self, v, w,weight):
        # 如果v,w之间已经有边了,什么也不做,很好的处理了平行边
        if self.hasEdge(v, w):
            return
        #如果v,w之间没有边
        self.g[v][w] = Edge(v, w, weight)

        #判断其是否时有向图,当不是有向图时,self.g[v][w],self.g[w][v] 之间的边是一样的
        # 条件中加入了 v != w,很好的处理了自环边(即不会重复的添加自环边)
        if v != w and self.directed != True:
            self.g[w][v] = Edge(v, w, weight)
        self.m += 1
Beispiel #26
0
    def addEadge(self, v, w, weight):
        #一般情况下可不判断v,w之间是否有边相连,因为加上这个判断,时间复杂度将变为O(n)
        if self.hasEadge(v, w):
            return

        #当v,w之间未相连时
        self.g[v].append(Edge(v, w, weight))
        #当不是有向图时
        #条件中加入了 v != w,很好的处理了自环边(即不会重复的添加自环边)
        if v != w and self.directed != True:
            self.g[w].append(Edge(w, v, weight))
        self.m += 1
Beispiel #27
0
    def add_edge(self, v1, v2, weight):
        if isinstance(v1, Vertex) and isinstance(v2, Vertex) and weight > 0:
            if type == 'undirected':
                e = Edge(weight)
            else:
                e = Edge(weight, True)

            e.connect_vertices(v1, v2)
            self.Edges.append(e)

            return True
        else:
            return False
def create_E(data):
    E = dict()
    for i in range(data.feed_size - 4):
        edge = Edge(i, i + 1)
        E[edge] = np.zeros((2, 3))
        edge = Edge(i, i + 2)
        E[edge] = np.zeros((2, 3))
        edge = Edge(i, i + 3)
        E[edge] = np.zeros((2, 3))
        # edge = Edge(i,i + 4)
        # E[edge] = np.zeros((2,3))

    return E
Beispiel #29
0
def file_report():
    raw_txt = Reader.readFromFile('data/test1')
    words = Reader.extractWords(raw_txt)
    keywords = Reader.meter(words)
    window = 3

    graph_rw = TermGraph()

    stopwords = nltk.corpus.stopwords.words('english')
    words_clean = []
    for word in words:
        if word not in stopwords:
            words_clean.append(word)
    words = words_clean
    length = words.__len__()
    # print length, len(keywords), window
    # print words

    for i in xrange(0, length - 1, 2):
        print '----', i, '----'
        print words[i:i + window]
        v1 = Vertex(words[i], keywords[words[i]])
        v2 = Vertex(words[i + 1], keywords[words[i + 1]])
        v3 = Vertex(words[i + 2], keywords[words[i + 2]])
        e1 = Edge(v1, v2)
        e2 = Edge(v1, v3)
        e3 = Edge(v2, v3)
        graph_rw.add_edge(e1)
        graph_rw.add_edge(e2)
        graph_rw.add_edge(e3)

    graph_rw.recalc_edges()

    mode = 'rw'
    graph_rw.recalc_vert_weights(mode)

    for i in xrange(0, 100):
        graph_rw.recalc_vert_weights(mode)

    array = graph_rw._verticles.values()
    array.sort(comparator)

    #report
    file = './test_results/' + mode + '-win3.csv'
    toCsv = ''
    for v in array:
        num_joins = graph_rw._verticlesJoins[v.term_value].__len__()
        toCsv += str(v.term_value) + ',' + str(v.term_weight_rw) + ',' + str(
            v.term_weight_tf) + '\n'
        print v, v.term_weight_rw, num_joins, v.term_weight_tf
        print graph_rw._verticlesJoins[v.term_value]
    def ClipWithTopRightCorner(self, dcel):

        # Create another top right vertex
        topRightCorner = Vertex(dcel.ux, dcel.uy, True)
        dcel.vertexList.Add(topRightCorner)

        # Create two psuedo edges for the clips for the middle face
        cornerTop = Edge(True)
        cornerRight = Edge(topRightCorner, True)
        dcel.edgeList.Add(cornerTop)
        dcel.edgeList.Add(cornerRight)

        self.triplet.middle.siteEvent.face.CreateForwardAndBackwardListsAt(
            topRightCorner, cornerTop, cornerRight)