def save(self, file_name, fmt="auto"):
        """ overload Graph.save to make output dotfiles pretty.
            This is entirely cosmetic. """
        u = self

        # add some properties to prettify dot output
        if fmt is "dot" or fmt is "auto" and file_name.endswith(".dot"):
            u = GraphView(self)

            # add shape property according to vertex owners
            shape = u.new_vertex_property("string")
            for v in u.vertices():
                if u.vp.owner[v] == 1:
                    shape[v] = "box"
                else:
                    shape[v] = "diamond"
            u.vp.shape = shape

            # add label property according to priorities
            #u.vertex_properties['label'] = u.vertex_properties['priority']
            label = u.new_vertex_property("string")
            for v in u.vertices():
                prio = u.vertex_properties['priority'][v]
                name = u.vertex_index[v]
                label[v] = "%d (%d)" % (name, prio)
            u.vp.label = label

        Graph.save(u, file_name, fmt)
Beispiel #2
0
def main():
    """
    Visualizes the research network of KTH as a graph.
    """
    start_time = time()

    # Create our undirected graph to return.
    g = Graph(directed=False)
    # The edge properties measuring collaboration.
    e_times = g.new_edge_property("float")
    # Grouping value for the verticies, verticies are in the same group if the
    # have the same value.
    v_groups = g.new_vertex_property("int")
    # Color the verticies based on their faculties colors.
    v_colors = g.new_vertex_property("vector<double>")

    db_path = '/home/_/kth/kexet/db/kex.db'
    query = """SELECT *
               FROM final
               WHERE (
                 name LIKE '%kth%' and
                 name LIKE '%;%' and
                 keywords is not null and
                 year >= 2013 and
                 ContentType = 'Refereegranskat' and
                 PublicationType = 'Artikel i tidskrift'
               );"""
    rows = load.rows(db_path, query)
    for row in rows:
        nobjs = parse.names(row['name'].split(';'))
        graph.add_relation(g, nobjs, e_times, v_colors, v_groups)

    g.edge_properties["times"] = e_times
    g.vertex_properties["colors"] = v_colors
    g.vertex_properties["groups"] = v_groups

    log.info(g.num_vertices())
    log.info(g.num_edges())
    g.save('a.gt')
    log.info('graph saved: a.gt')
    log.info("db & parse %ss" % round(time() - start_time, 2))

    # start_time = time()
    # g = load_graph('a.gt')
    # log.info("loading %ss" % round(time() - start_time, 2))

    draw.largest(g.copy())
    draw.radial_highest(g.copy())
    draw.sfdp(g.copy())
    draw.grouped_sfdp(g.copy())
    draw.min_tree(g.copy())
    draw.radial_random(g.copy())
    draw.hierarchy(g.copy())
    draw.minimize_blockmodel(g.copy())
    draw.netscience(g.copy())
    draw.fruchterman(g.copy())
Beispiel #3
0
def import_carribean_food_web_graph(save=True, export=True):
    saveLoadFolder = "Carribean_FoodWeb"
    graphFile = saveLoadPath + saveLoadFolder + "/Carribean_Adjacency_Matrix_raw.txt"
    g = Graph(directed=False)
    edgeWeights = g.new_edge_property("double")
    counter = -1

    with open(graphFile, "r") as inF:
        for line in inF:
            if line[0] == "#":  # This line is a header. Skip it.
                continue

            if counter == -1:  # First non header line revels all the species/categories.
                categories = line.split()
                num_nodes = int(len(categories))
                print num_nodes
                counter += 1
                g.add_vertex(num_nodes)
                continue

            splitted = line.split()
            category = splitted[0]
            assert (category == categories[counter])

            for neighbor, weight in enumerate(splitted[1:]):
                if weight != "0":
                    e = g.add_edge(g.vertex(neighbor),
                                   g.vertex(counter))  # Neighbor eats him.
                    edgeWeights[e] = float(weight)
            counter += 1

    taxaToInt = {"D": 0, "A": 1, "I": 2, "F": 3, "R": 4, "B": 5}
    troClass = g.new_vertex_property("int")
    for i, categ in enumerate(categories):
        troClass.a[i] = taxaToInt[categ[0]]

    g.vp["trophic_class"] = troClass
    g.ep["edge_weight"] = edgeWeights

    g = make_simple_graph(g, undirected=True, gcc=True)

    graphName = saveLoadFolder
    if save:
        save_data(
            saveLoadPath + saveLoadFolder + "/" + graphName + ".GT.graph", g)
        g.save(saveLoadPath + saveLoadFolder + "/" + graphName + ".graph.xml",
               fmt="xml")
    if export:
        from_GT_To_Greach(
            g,
            saveLoadPath + saveLoadFolder + "/" + graphName + ".greach.graph")
        from_GT_To_Snap(
            g, saveLoadPath + saveLoadFolder + "/" + graphName + ".snap.graph")

    return g
Beispiel #4
0
class GraphAdapter(AdapterBase):
    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])

    def add_node(self, gene, gen=0, attrs={}):
        v = self.graph.add_vertex()
        self.graph.vp.gene[v] = gene
        self.graph.vp.gen[v] = gen
        self.set_props(v, attrs)

        return self.graph.vertex_index[v]

    def add_edge(self, TAG, srcID, destID, attrs={}):
        e = self.graph.add_edge(srcID, destID)
        self.graph.ep.label[e] = TAG
        for key in attrs:
            self.graph.ep[key][e] = attrs[key]
        return self.graph.edge_index[e]

    def getNode(self, nodeID):
        return self.graph.vertex(nodeID)

    def getEdge(self, edgeID):
        return self.graph.edge(edgeID)

    def fetchIndividual(self, individual):
        targets = graph_tool.util.find_vertex(self.graph, self.graph.vp.gene,
                                              individual)
        # find the last node, the one with highest `gen`
        if targets:
            # guaranteed to be in order!!
            return self.graph.vertex_index[targets[-1]]
        else:
            return None

    def walk_edge(self, TAG, startID):
        pass

    def update_fitness(self, nodeID, fitness):
        v = self.graph.vertex(nodeID)
        self.set_props(v, {'fitness': fitness})

    def update_score(self, nodeID, score):
        v = self.graph.vertex(nodeID)
        self.set_props(v, {'score': score})

    def set_props(self, v, attrs):
        for key in attrs:
            self.graph.vp[key][v] = attrs[key]

    def save(self):
        filename = os.path.join('graphs',
                                self.name) + '.' + self.file_extension
        self.graph.save(filename)
        return filename

    def numNodes(self):
        return self.graph.num_vertices()

prop_question_id = g.new_vertex_property('int')
prop_question_id.a = np.array(list(id2q_map.values()))

# focus on largest CC
g.set_vertex_filter(vfilt)

# re-index the graph
# SO qustion: https://stackoverflow.com/questions/46264296/graph-tool-re-index-vertex-ids-to-be-consecutive-integers
n2i = {n: i for i, n in enumerate(g.vertices())}
i2n = dict(zip(n2i.values(), n2i.keys()))

new_g = Graph()
new_g.add_edge_list([(n2i[e.source()], n2i[e.target()]) for e in g.edges()])


# update question ids
new_prop_question_id = new_g.new_vertex_property('int')
new_prop_question_id.a = [prop_question_id[i2n[i]] for i in range(new_g.num_vertices())]
new_g.vertex_properties['question_id'] = new_prop_question_id


print('saving largest CC in graph')
new_g.save('{}/question_graph.gt'.format(data_dir))


print('saving connected_question_ids')
pkl.dump(list(new_prop_question_id.a),
         open('{}/connected_question_ids.pkl'.format(data_dir), 'wb'))
Beispiel #6
0
    if g.edge(v, u) is None:
        g.add_edge(v, u)

# In[31]:

weight = g.new_edge_property('float')
weight.set_value(EPS)

# In[32]:

for i, r in tqdm(df.iterrows(), total=df.shape[0]):
    u, v, w = int(r['u']), int(r['v']), r['w']
    weight[g.edge(u, v)] = w
g.edge_properties['weights'] = weight

# In[33]:

deg_out = g.degree_property_map('out', weight=weight)

# In[34]:

r = deg_out.a
r = r[r < 2]
s = pd.Series(r)
# s.hist(bins=30)

# In[35]:

g.save('data/{}/graph.gt'.format(graph))
g.save('data/{}/graph_weighted.gt'.format(graph))