def copy_edge_attributes(g_to: gt.Graph, edge_to: gt.Edge, g_from: gt.Graph, edge_from: gt.Edge): for p_type, ep_name in g_from.ep.properties: if p_type != 'e': continue old_ep = g_from.ep[ep_name] if ep_name not in g_to.ep: g_to.ep[ep_name] = g_to.new_ep(old_ep.value_type()) new_ep = g_to.ep[ep_name] new_ep[edge_to] = deepcopy(old_ep[edge_from])
def __make_graph(self, X): # make a graph g = Graph(directed=False) # define node properties # kind: docs - 0, words - 1 kind = g.vp["kind"] = g.new_vp("int") if self.weighted_edges: ecount = g.ep["count"] = g.new_ep("int") # add all documents first doc_vertices = [g.add_vertex() for _ in range(X.shape[0])] word_vertices = [g.add_vertex() for _ in range(X.shape[1])] # add all documents and words as nodes # add all tokens as links X = scipy.sparse.coo_matrix(X) if not self.weighted_edges and X.dtype != int: X_int = X.astype(int) if not np.allclose(X.data, X_int.data): raise ValueError('Data must be integer if ' 'weighted_edges=False') X = X_int for row, col, count in zip(X.row, X.col, X.data): doc_vert = doc_vertices[row] kind[doc_vert] = 0 word_vert = word_vertices[col] kind[word_vert] = 1 if self.weighted_edges: e = g.add_edge(doc_vert, word_vert) ecount[e] = count else: for n in range(count): g.add_edge(doc_vert, word_vert) return g
def ep_map(g: gt.Graph, e_property: str, p_type: str = 'int') -> gt.PropertyMap: if e_property not in g.ep: g.ep[e_property] = g.new_ep(p_type) return g.ep[e_property]
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()
def load_graph_from_kgtk( kr: KgtkReader, directed: bool = False, eprop_types: typing.Optional[typing.List[str]] = None, hashed: bool = True, hash_type: str = "string", # for future support ecols: typing.Optional[typing.Tuple[int, int]] = None, out: typing.TextIO = sys.stderr, verbose: bool = False, ): """Load a graph from a `KgtkReader` file containing a list of edges and edge properties. This code is based on load_graph_from_csv(...) in `graph-tool/src/graph_tool/__init__.py`, downloaded from git.skewed.de on 27-Jul-2020. Parameters ---------- kr : ``KgtkReader`` directed : ``bool`` (optional, default: ``False``) Whether or not the graph is directed. eprop_types : list of ``str`` (optional, default: ``None``) List of edge property types to be read from remaining columns (if this is ``None``, all properties will be of type ``string``. hashed : ``bool`` (optional, default: ``True``) If ``True`` the vertex values in the edge list are not assumed to correspond to vertex indices directly. In this case they will be mapped to vertex indices according to the order in which they are encountered, and a vertex property map with the vertex values is returned. hash_type : ``str`` (optional, default: ``string``) If ``hashed == True``, this will determined the type of the vertex values. It can be any property map value type (see :class:`PropertyMap`). Note: As of 29-Jul-2020, this parameter to graph.add_edge_list(...) is supported in the git version of graph_tools, but is not mentioned in the graph-tools 2.33 documentation. ecols : pair of ``int`` (optional, default: ``(0,1)``) Line columns used as source and target for the edges. Returns ------- g : :class:`~graph_tool.Graph` The loaded graph. It will contain additional columns in the file as internal edge property maps. If ``hashed == True``, it will also contain an internal vertex property map with the vertex names. """ r = kr # R may be wrapped for column reordering and/or non-hashed use. if ecols is None: ecols = (kr.node1_column_idx, kr.node2_column_idx) if ecols != (0, 1): def reorder(rows): for row in rows: row = list(row) s = row[ecols[0]] t = row[ecols[1]] del row[min(ecols)] del row[max(ecols) - 1] yield [s, t] + row r = reorder(r) if not hashed: def conv(rows): for row in rows: row = list(row) row[0] = int(row[0]) row[1] = int(row[1]) yield row r = conv(r) g = Graph(directed=directed) if eprop_types is None: if verbose: print("eprop_types is None", file=out, flush=True) eprops = [g.new_ep("string") for x in kr.column_names[2:]] else: if verbose: print("eprop_types: [%s]" % (", ".join([repr(x) for x in eprop_types])), file=out, flush=True) if len(eprop_types) != kr.column_count - 2: raise ValueError("There are %d eprop columns and %d eprop types." % (kr.column_count - 2, len(eprop_types))) eprops = [g.new_ep(t) for t in eprop_types] # 29-Jul-2020: This is supported in the git.skewed.de repository, and # presumably will be supported in a future release. Unfortunately, graph-tool # doesn't appear to include a version indicator or API version indicator # easily accessible from Python. # # The graph-tool 2.33 documentation does not include the hash_type parameter. # # name = g.add_edge_list(itertools.chain([line], r), hashed=hashed, # hash_type=hash_type, eprops=eprops) if verbose: print("Adding edges from the input file.", file=out, flush=True) name = g.add_edge_list(r, hashed=hashed, eprops=eprops) if verbose: print("Done adding edges from the input file.", file=out, flush=True) g.vp.name = name eprop_names: typing.List[str] = list(kr.column_names) del eprop_names[min(ecols)] del eprop_names[max(ecols) - 1] if verbose: print("eprop_names: [%s]" % (", ".join([repr(x) for x in eprop_names])), file=out, flush=True) for i, p in enumerate(eprops): ename = eprop_names[i] g.ep[ename] = p if verbose: print("prop %d name=%s" % (i, repr(ename)), file=out, flush=True) return g