Пример #1
0
def burtFig5(directed=False):
    '''
    Returns the graph presented at Burt's "Role Equivalence" paper, at Figure_x
    '''
    g = Graph(directed=directed)
    g.add_vertex(10)
    if directed:
        addSymmetricEdge(g, 0, 1)
        addSymmetricEdge(g, 1, 2)
        addSymmetricEdge(g, 2, 3)
        addSymmetricEdge(g, 4, 6)
        addSymmetricEdge(g, 6, 5)
        addSymmetricEdge(g, 7, 9)
        addSymmetricEdge(g, 9, 8)
        g.add_edge(4, 0)
        g.add_edge(5, 0)
        g.add_edge(7, 3)
        g.add_edge(8, 3)
    else:
        g.add_edge(0, 1)
        g.add_edge(1, 2)
        g.add_edge(2, 3)
        g.add_edge(4, 6)
        g.add_edge(6, 5)
        g.add_edge(7, 9)
        g.add_edge(9, 8)
        g.add_edge(4, 0)
        g.add_edge(5, 0)
        g.add_edge(7, 3)
        g.add_edge(8, 3)

    return g
Пример #2
0
    def new_function(eptm, *args, **kwargs):
        from .epithelium import Epithelium
        from graph_tool import Graph, GraphView
        local_graph = Graph(GraphView(eptm.graph,
                                      vfilt=eptm.is_local_vert,
                                      efilt=eptm.is_local_edge),
                            prune=True)
        local_eptm = Epithelium(paramtree=eptm.paramtree, graph=local_graph)
        # if local_eptm.at_boundary.fa.sum() > 0:
        #     local_eptm.rotate(np.pi)
        #     local_eptm.current_angle = np.pi
        #     print('rotated')
        out = meth(local_eptm, *args, **kwargs)
        # if not -1e-8 < local_eptm.current_angle < 1e-8:
        #     local_eptm.rotate(-local_eptm.current_angle)
        #     local_eptm.current_angle = 0.
        #     print( 'rotated back')
        eptm.graph.set_vertex_filter(eptm.is_local_vert)
        eptm.graph.set_edge_filter(eptm.is_local_edge)
        for key, val in local_eptm.graph.vertex_properties.items():
            eptm.graph.vertex_properties[key].fa = val.a
        for key, val in local_eptm.graph.edge_properties.items():
            eptm.graph.edge_properties[key].fa = val.a
        eptm.graph.set_vertex_filter(None)
        eptm.graph.set_edge_filter(None)
        eptm.reset_topology()

        return out
Пример #3
0
def burtFig4(directed=False):
    '''
    Returns the graph presented at Burt's "Role Equivalence" paper, at Figure_x
    '''
    g = Graph(directed=directed)
    g.add_vertex(9)
    g.add_edge(0, 4)
    g.add_edge(1, 4)
    g.add_edge(2, 4)
    g.add_edge(3, 4)
    g.add_edge(4, 5)
    g.add_edge(4, 6)
    # 4-clique
    g.add_edge(5, 6)
    g.add_edge(5, 7)
    g.add_edge(5, 8)
    g.add_edge(6, 7)
    g.add_edge(6, 8)
    g.add_edge(7, 8)
    if directed:
        g.add_edge(6, 5)
        g.add_edge(7, 5)
        g.add_edge(8, 5)
        g.add_edge(7, 6)
        g.add_edge(8, 6)
        g.add_edge(8, 7)

    for ed in g.edges():
        print ed
    return g
Пример #4
0
def balancedBinaryTree(h, drawGraph=False):
    '''
    h - the height of the tree
    '''
    g = Graph(directed=False)
    g.add_vertex(2**h - 1)

    for i in xrange(1, 2**(h - 1)):
        lc = 2 * i - 1
        rc = lc + 1
        g.add_edge(i - 1, lc)
        g.add_edge(i - 1, rc)

    hIndex = g.new_vertex_property(
        "int")  #associate with each node the height at which it lies
    k = 2
    m = 1
    for i in xrange(1, len(hIndex.a)):
        hIndex.a[i] = m
        k -= 1
        if k == 0:
            m += 1
            k = 2**m
    g.vp['height'] = hIndex

    if drawGraph == True:
        draw.graph_draw(g,
                        vertex_text=g.vertex_index,
                        edge_color="black",
                        output="binaryTree_h_" + str(h) + "_.pdf")

    return g
Пример #5
0
 def create_true_graph(self):
     final_workflow = Graph()
     final_workflow.add_vertex(self.network_size)
     i = 0
     while max([
             shortest_distance(final_workflow, x, (self.network_size - 1))
             for x in final_workflow.get_vertices()
     ]) > 100:
         i += 1
         if i > 10000:
             raise RuntimeError('generating graph took too long')
         valid_source_nodes = [
             index for index, in_degree in enumerate(
                 final_workflow.get_in_degrees(
                     final_workflow.get_vertices()))
             if ((in_degree > 0 or index < self.input_nodes) and index <
                 (self.network_size - 1))
         ]
         valid_to_nodes = [
             index for index in final_workflow.get_vertices()
             if (index >= self.input_nodes)
         ]
         new_edge = final_workflow.add_edge(
             self.np_random.choice(valid_source_nodes),
             self.np_random.choice(valid_to_nodes))
         if not is_DAG(final_workflow):
             final_workflow.remove_edge(new_edge)
         observation = adjacency(final_workflow).toarray().astype(int)
         if not self.observation_space.contains(observation):
             final_workflow.remove_edge(new_edge)
     return final_workflow
Пример #6
0
def transform_npz_nx(g, penalize=20):
    from numpy import int32
    ids = g['ids']
    lat = g['lat']
    long = g['long']
    id2edges = g['id2edges']
    edges_weight = g['edges_weight']
    edges_neighbor = g['edges_neighbor']
    edges_air = g['edges_type']
    rescale = edges_weight.dtype == int32
    from networkx import Graph
    h = Graph()
    index2node = {}
    for index in range(len(ids)):
        node = (int(ids[index]), lat[index] / (10000000. if rescale else 1),
                long[index] / (10000000. if rescale else 1))
        index2node[index] = node
        h.add_node(node)
    for index in range(len(ids)):
        left = id2edges[index]
        right = id2edges[index + 1]
        me = index2node[index]
        for i in range(left, right):
            neighbor = edges_neighbor[i]
            air = edges_air[i]
            w = edges_weight[i] / (
                (1000. * (penalize if air < 0 else 1)) if rescale else 1)
            h.add_edge(me, index2node[neighbor], weight=w, type=air)
    return h
Пример #7
0
    def __init__(self, name, edges, object_ids, weights, hidden_graph=None):
        """
        Params:
            name (str): unique string to name this dataset (for pickling and
                unpickling)
            edges (numpy.ndarray): numpy array of shape [num_edges, 2]
                containing the indices of nodes in all edges
            objects (List[str]): string object ids for all nodes
            weights (numpy.ndarray): numpy array of shape [num_edges]
                containing edge weights
            hidden_graph (GraphDataset): Graph data that should be excluded
                but not considered as negative edges. (i.e. train
                edges should not be in eval dataset but they shouldn't be
                counted as negatives either)
        """

        self.name = name
        self.edges = edges
        self.object_ids = np.asarray(object_ids)
        self.weights = weights
        self.hidden_graph = hidden_graph

        self.graph = Graph(directed=False)
        self.graph.add_vertex(len(object_ids))
        edge_weights = [[edge[0], edge[1], weight]
                        for edge, weight in zip(self.edges, self.weights)]
        self.weight_property = self.graph.new_edge_property("float")
        eprops = [self.weight_property]
        self.graph.add_edge_list(edge_weights, eprops=eprops)
        self.manifold_nns = None
Пример #8
0
def query_graph_s1():
    """query s1"""
    G = Graph(directed=True)

    v0 = G.add_vertex()
    v1 = G.add_vertex()
    v2 = G.add_vertex()
    v3 = G.add_vertex()
    v4 = G.add_vertex()
    v5 = G.add_vertex()
    v6 = G.add_vertex()
    v7 = G.add_vertex()
    v8 = G.add_vertex()
    v9 = G.add_vertex()

    G.add_edge(v0, v1)  # e0, gr:includes
    G.add_edge(v2, v0)  # e1, gr:offers
    G.add_edge(v0, v3)  # e2, gr:price
    G.add_edge(v0, v4)  # e3, gr:serial_number
    G.add_edge(v0, v5)  # e4, gr:validFrom
    G.add_edge(v0, v6)  # e5, gr:validThrough
    G.add_edge(v0, v7)  # e6, sorg:eligible_Region
    G.add_edge(v0, v8)  # e7, sorg:eligible_Region
    G.add_edge(v0, v9)  # e8, gr:priceValidUntil

    return G
def gen_cascade(g, p, source=None, stop_fraction=0.5):
    if source is None:
        source = random.choice(np.arange(g.num_vertices()))
    infected = {source}
    infection_times = np.ones(g.num_vertices()) * -1
    infection_times[source] = 0
    time = 0
    edges = []
    while np.count_nonzero(
            infection_times != -1) / g.num_vertices() <= stop_fraction:
        infected_nodes_until_t = copy(infected)
        time += 1
        for i in infected_nodes_until_t:
            for j in g.vertex(i).all_neighbours():
                j = int(j)
                if j not in infected and random.random() <= p:
                    infected.add(j)
                    infection_times[j] = time
                    edges.append((i, j))

    tree = Graph(directed=True)
    for _ in range(g.num_vertices()):
        tree.add_vertex()
    for u, v in edges:
        tree.add_edge(u, v)
    return source, infection_times, tree
Пример #10
0
    def load(self, data):
        data = [x.strip() for x in data]
        # Create a new undirectedgraph
        self.graph = Graph(directed=False)

        # Label everything so I'm not going back and forth between hashes
        v_name = self.graph.new_vertex_property('string')
        self.graph.vertex_properties["name"] = v_name

        self.planets = dict()
        # Create all the vertexes first, so that creating the edges (orbits)
        # is easier
        for item in data:
            # Add vertexes, as needed
            src, dest = item.split(")")
            if src not in self.planets:
                v_src = self.graph.add_vertex()
                v_name[v_src] = src
                self.planets[src] = v_src
            if dest not in self.planets:
                v_dest = self.graph.add_vertex()
                v_name[v_dest] = dest
                self.planets[dest] = v_dest
            # Add edge
            self.graph.add_edge(self.planets[src], self.planets[dest])
Пример #11
0
 def __init__(self):
     self.g = Graph()
     self.dvertex_index = dict()
     self.vertex_label = self.g.new_vertex_property("string")
     self.g.vertex_properties["label"] = self.vertex_label
     self.edge_weight = self.g.new_edge_property("int")
     self.g.edge_properties["weight"] = self.edge_weight
Пример #12
0
def test_isolate_disconnected_components():
    ######### case 1 #######
    g = remove_filters(Graph(directed=False))
    g.add_vertex(4)
        
    hide_disconnected_components(g, [0, 2])  # 1, 3 are isolated
    assert set(extract_nodes(g)) == {0, 2}

    ######### case 2 #######
    g = remove_filters(Graph(directed=False))
    g.add_vertex(4)
    g.add_edge(0, 1)
    g.add_edge(1, 2)

    hide_disconnected_components(g, [0])
    assert set(extract_nodes(g)) == {0, 1, 2}
Пример #13
0
 def __init__(self, protocol):
     self._protocol = protocol
     self._graph = Graph(directed=True)
     self._vertices = {}
     self._leaves = set()
     self._speed = Speed.ZERO
     self._construct_tree()
Пример #14
0
def line_g():
    g = Graph(directed=True)
    g.add_edge(0, 1)
    g.add_edge(1, 0)
    g.add_edge(1, 2)
    g.add_edge(2, 1)
    return g
Пример #15
0
    def __init__(
            self,
            seed_str,
            name,
            file_extension='gml',
            vertex_schema={
                'gene': 'vector<bool>',
                'gen': 'int',
                'fitness': 'vector<long>',
                'score': 'long'
            },
            edge_schema={
                'label': 'string',
                'gen': 'int'
            }):

        self.seed = seed_str
        self.name = name
        self.file_extension = file_extension
        self.graph = Graph()

        # Create graph properties
        self.graph.gp.labels = self.graph.new_gp('vector<string>')
        self.graph.gp.labels = [seed_str]

        self.graph.gp.name = self.graph.new_gp('string')
        self.graph.gp.name = self.name

        # Create vertex properties
        for key in vertex_schema:
            self.graph.vp[key] = self.graph.new_vp(vertex_schema[key])

        # Create edge properties
        for key in edge_schema:
            self.graph.ep[key] = self.graph.new_ep(edge_schema[key])
Пример #16
0
def query_graph_c2():
    """query c2"""
    G = Graph(directed=True)

    v0 = G.add_vertex()
    v1 = G.add_vertex()
    v2 = G.add_vertex()
    v3 = G.add_vertex()
    v4 = G.add_vertex()
    v5 = G.add_vertex()
    v6 = G.add_vertex()
    v7 = G.add_vertex()
    v8 = G.add_vertex()
    v9 = G.add_vertex()
    v10 = G.add_vertex()

    G.add_edge(v0, v1)  # e0, sorg:legalName
    G.add_edge(v0, v2)  # e1, gr:offers
    G.add_edge(v2, v3)  # e2, gr:includes
    G.add_edge(v2, v5)  # e3, sorg:eligibleRegion
    G.add_edge(v3, v8)  # e4, sorg:actor
    G.add_edge(v8, v9)  # e5, rev:totalVotes
    G.add_edge(v7, v3)  # e6, wsdbm:purchaseFor
    G.add_edge(v4, v7)  # e7, wsdbm:makesPurchase
    G.add_edge(v4, v10)  # e8, sorg:jobTitle
    G.add_edge(v4, v6)  # e9, foaf:homepage

    return G
def test_fill_missing_time():
    """simple chain graph test
    """
    g = Graph(directed=False)
    g.add_vertex(4)
    g.add_edge_list([(0, 1), (1, 2), (2, 3)])

    t = GraphView(g, directed=True)
    efilt = t.new_edge_property('bool')
    efilt.a = True
    efilt[t.edge(2, 3)] = False
    t.set_edge_filter(efilt)
    vfilt = t.new_vertex_property('bool')
    vfilt.a = True
    vfilt[3] = False
    t.set_vertex_filter(vfilt)

    root = 0
    obs_nodes = {0, 2}
    infection_times = [0, 1.5, 3, -1]

    pt = fill_missing_time(g, t, root, obs_nodes, infection_times, debug=False)

    for i in range(4):
        assert pt[i] == infection_times[i]
Пример #18
0
def diagram_to_graph(diagram):
    '''Convert specified chord diagram to the equivalent graph.
       Construct the graph with a vertex for each diagram chord, and an edge
       from the vertex for each node to the next greater node as though manually
       drawing the planar diagram from the chord diagram, such that edges go
       from nodes (1 -> 2), (2 -> 3),..., (n-1 -> n), (n -> 1).

       Arguments:
           diagram: A list of chords, where each chord is a node tuple.
       Returns:
           Returns the graph corresponding to the input diagram.
       Raises:
           None
    '''
    graph = Graph()

    # Create a vertex for each chord - same vertex stored for each node of chord
    vertex_by_node = {}
    for chord in diagram:
        vertex = graph.add_vertex()
        vertex_by_node[chord[0]] = vertex
        vertex_by_node[chord[1]] = vertex

    # As though drawing the planar diagram from the chord diagram by hand,
    # add an edge from 1st node to 2nd, 2nd to 3rd, and so on, until closing
    # the loop back to the 1st node.
    nodes = vertex_by_node.keys()
    n_nodes = len(nodes)
    for i in range(0, len(nodes)):
        j = (i + 1) % n_nodes
        graph.add_edge(vertex_by_node[nodes[i]], vertex_by_node[nodes[j]])

    return graph
Пример #19
0
    def init2(self, emacs_var_dict):
        self.emacs_var_dict = emacs_var_dict

        self.link_str = self.emacs_var_dict['links']
        self.g = Graph()
        self.label_ep = self.g.new_edge_property("string")
        self.links = self.link_str.split(";")

        link_tpls = [i.split(" -- ") for i in self.links]
        dumper([str(i) for i in link_tpls])

        self.g_id = self.g.add_edge_list(link_tpls,
                                         hashed=True,
                                         string_vals=True,
                                         eprops=[self.label_ep])

        self.adj = np.array([(int(i.source()), int(i.target()))
                             for i in self.g.edges()])
        self.node_names = [self.g_id[i] for i in self.g.vertices()]

        self.vd = {}
        for i in self.g.vertices():
            self.vd[self.g_id[i]] = int(i)

        # self.pos_vp = sfdp_layout(self.g, K=0.5)
        self.pos_vp = fruchterman_reingold_layout(self.g)
        self.base_pos_ar = self.pos_vp.get_2d_array((0, 1)).T
        self.qt_coords = self.nolz_pos_ar(self.base_pos_ar)

        dumper([str(self.qt_coords)])
Пример #20
0
def build_minimum_tree(g, root, terminals, edges, directed=True):
    """remove redundant edges from `edges` so that root can reach each node in terminals
    """
    # build the tree
    t = Graph(directed=directed)

    for _ in range(g.num_vertices()):
        t.add_vertex()

    for (u, v) in edges:
        t.add_edge(u, v)

    # mask out redundant edges
    vis = init_visitor(t, root)
    pbfs_search(t, source=root, terminals=list(terminals), visitor=vis)

    minimum_edges = {
        e
        for u in terminals
        for e in extract_edges_from_pred(t, root, u, vis.pred)
    }
    # print(minimum_edges)
    efilt = t.new_edge_property('bool')
    efilt.a = False
    for u, v in minimum_edges:
        efilt[u, v] = True
    t.set_edge_filter(efilt)

    return filter_nodes_by_edges(t, minimum_edges)
Пример #21
0
def find_cycles2(args, wires):
    # implemented with graph-tools
    g = Graph()
    t_a = datetime.now()
    lst = []
    for i in range(0, len(wires)):
        lst.append(g.add_vertex())

    for i in range(0, len(wires)):
        if wires[i].type != "inp":
            for j in range(len(wires[i].operands)):
                g.add_edge(lst[wires[i].operands[j].index],
                           lst[wires[i].index])

    cycles = []
    for c in all_circuits(g):
        if len(cycles) > 100000:
            logging.info("number of cycles is limited.")
            break
        cycles.append(c.tolist())

    t_b = datetime.now()
    logging.info("time of finding cycles: " + diff(t_a, t_b))
    logging.info("there are" + str(len(cycles)) + "cycles")
    if args.p:
        logging.info("list of cycles:")
        for cycle in cycles:
            tmp = ""
            for i in range(len(cycle)):
                tmp += wires[cycle[i]].name + " "
            logging.info(tmp)
        print()
    return cycles
def build_graph_from_edges(edges):
    """returns Graph (a new one)
    """
    g = Graph()
    for u, v in edges:
        g.add_edge(u, v)
    return g
Пример #23
0
def golang_graph_to_graphtool_graph(edge_data):
    g = golang_graph_to_graph(edge_data)
    G = Graph(directed=False)
    handles = [G.add_vertex() for _ in g.nodes()]
    for u, v in g.edges():
        G.add_edge(handles[u], handles[v])
    return G
def build_closure(g, terminals, debug=False, verbose=False):
    terminals = list(terminals)
    # build closure
    gc = Graph(directed=False)
    gc.add_vertex(g.num_vertices())

    edges_with_weight = set()
    r2pred = {}

    for r in terminals:
        if debug:
            print('root {}'.format(r))
        vis = init_visitor(g, r)
        pbfs_search(g, source=r, terminals=terminals, visitor=vis)
        new_edges = set(get_edges(vis.dist, r, terminals))
        if debug:
            print('new edges {}'.format(new_edges))
        edges_with_weight |= new_edges
        r2pred[r] = vis.pred

    for u, v, c in edges_with_weight:
        gc.add_edge(u, v)

    eweight = gc.new_edge_property('int')
    weights = np.array([c for _, _, c in edges_with_weight])
    eweight.set_2d_array(weights)

    vfilt = gc.new_vertex_property('bool')
    vfilt.a = False
    for v in terminals:
        vfilt[v] = True
    gc.set_vertex_filter(vfilt)
    return gc, eweight, r2pred
Пример #25
0
    def __init__(self, state: SampleState, graph: Graph,
                 old_true_block_assignment: np.ndarray) -> None:
        """Creates a new Sample object. Contains information about the sampled vertices and edges, the mapping of
        sampled vertices to the original graph vertices, and the true block membership for the sampled vertices.

        Parameters
        ----------
        state : SampleState
            contains the sampled vertices
        graph : Graph
            the graph from which the sample is taken
        old_true_block_assignment : np.ndarray[int]
            the vertex-to-community assignment array. Currently assumes that community assignment is non-overlapping.
        """
        self.state = state
        sampled_vertices = sorted(state.sample_idx[-state.sample_size:])
        self.vertex_mapping = dict([(v, k)
                                    for k, v in enumerate(sampled_vertices)])
        binary_filter = np.zeros(graph.num_vertices())
        binary_filter[sampled_vertices] = 1
        graph.set_vertex_filter(
            graph.new_vertex_property("bool", binary_filter))
        self.graph = Graph(
            graph, prune=True
        )  # If ordering is wacky, may need to play around with vorder
        graph.clear_filters()
        true_block_assignment = old_true_block_assignment[sampled_vertices]
        # Assuming the sample doesn't capture all the blocks, the block numbers in the sample may not be consecutive
        # The true_blocks_mapping ensures that they are consecutive
        true_blocks = list(set(true_block_assignment))
        self.true_blocks_mapping = dict([(v, k)
                                         for k, v in enumerate(true_blocks)])
        self.true_block_assignment = np.asarray(
            [self.true_blocks_mapping[b] for b in true_block_assignment])
        self.sample_num = len(self.vertex_mapping)
Пример #26
0
def query_graph_f4():
    """query f4"""
    G = Graph(directed=True)

    v0 = G.add_vertex()
    v1 = G.add_vertex()
    v2 = G.add_vertex()
    v3 = G.add_vertex()
    v4 = G.add_vertex()
    v5 = G.add_vertex()
    v6 = G.add_vertex()
    v7 = G.add_vertex()
    v8 = G.add_vertex()
    v9 = G.add_vertex()

    G.add_edge(v0, v1)  # e0, foaf:homepage
    G.add_edge(v2, v0)  # e1, gr:includes
    G.add_edge(v0, v3)  # e2, og:title
    G.add_edge(v0, v4)  # e3, sorg:description
    G.add_edge(v0, v8)  # e4, sorg:contentSize
    G.add_edge(v1, v5)  # e5, sorg:url
    G.add_edge(v1, v6)  # e6, wsdbm:hits
    G.add_edge(v7, v1)  # e7, wsdbm:likes
    G.add_edge(v1, v9)  # e8, sorg:language

    return G
Пример #27
0
    def __init__(self):
        """
        Constructor of the abstract SegmentationGraph object.

        Returns:
            None
        """
        self.graph = Graph(directed=False)
        """graph_tool.Graph: a graph object storing the segmentation graph
        topology, geometry and properties (initially empty).
        """

        # Add "internal property maps" to the graph.
        # vertex property for storing the xyz coordinates of the corresponding
        # vertex:
        self.graph.vp.xyz = self.graph.new_vertex_property("vector<float>")
        # edge property for storing the distance between the connected vertices:
        self.graph.ep.distance = self.graph.new_edge_property("float")

        self.coordinates_to_vertex_index = {}
        """dict: a dictionary mapping the vertex coordinates (x, y, z) to the
        vertex index.
        """
        self.coordinates_pair_connected = set()
        """set: a set storing pairs of vertex coordinates that are
Пример #28
0
def edges2graph(g, edges):
    tree = Graph(directed=True)
    for _ in range(g.num_vertices()):
        tree.add_vertex()
    for u, v in edges:
        tree.add_edge(int(u), int(v))

    return filter_nodes_by_edges(tree, edges)
Пример #29
0
def build_cooc_graph(coDic, posMap):
    '''    
    Converts a dictionary keeping word-word co-occurrences to a graph object where the edge weight
    between nodes (words) corresponds to their co-occurrence.

    Args:
        coOcDic: A dictionary where keys are tuples with 2 elements, (string1, string2) corresponding to the co-occurrence of two words. 
        The corresponding value is an integer capturing the times the co-occurrence happened (e.g., through out a book).
        posMap: A dictionary from word to Part Of Speech.
    Returns:
        A graph object.
    
    '''
    g = Graph(directed=False)
    wordToNodeID = dict(
    )  #maps a word to the ID of the node that it will be stored
    eWeight = g.new_edge_property(
        "int")  #edges have weights capturing number of co-occurrences
    words = g.new_vertex_property(
        "object"
    )  #keep for each node the (potentially unicode) corresponding word as an attribute
    POS = g.new_vertex_property("string")  #keep the Part Of Speech
    nodeID = 0
    for word1, word2 in coDic.keys(
    ):  #Each key is a (noun, noun) string. It will become an edge
        if word1 not in wordToNodeID:
            wordToNodeID[word1] = nodeID
            v = g.add_vertex()
            assert (str(v) == str(nodeID))
            words[v] = word1
            POS[v] = posMap[word1]
            nodeID += 1
        if word2 not in wordToNodeID:
            wordToNodeID[word2] = nodeID
            v = g.add_vertex()
            assert (str(v) == str(nodeID))
            words[v] = word2
            POS[v] = posMap[word2]
            nodeID += 1
        source = wordToNodeID[word1]
        target = wordToNodeID[word2]
        e = g.add_edge(source, target)
        eWeight[e] = coDic[(word1, word2)]

    g.edge_properties["co-occurrence"] = eWeight
    g.vertex_properties["word"] = words
    g.vertex_properties["partOfSpeach"] = POS

    #Encode the POS as a short number
    POS_encoded = g.new_vertex_property("short")
    posEncoder = part_of_speech_int_map(posToInt=True)

    for v in g.vertices():
        POS_encoded[v] = posEncoder[POS[v][0]]

    g.vertex_properties["partOfSpeach_encoded"] = POS_encoded

    return g
Пример #30
0
def input_data_gt():
    g_nx = nx.karate_club_graph()
    g = Graph(directed=True)
    g.add_vertex(g_nx.number_of_nodes())
    for u, v in g_nx.edges():
        g.add_edge(u, v)
        g.add_edge(v, u)  # the other direction

    return g, from_gt(g, None), g.num_vertices()