Graph nodes are ID's, and have a 'label' in the node data with the right label

    :param graph:
    :param source_node:
    :param str output_path:
    :param base_iri:
772610
def nx_to_ontology(graph, source_node, output_path, base_iri):
    
    ontology = owlready.Ontology(base_iri)

    parent_lookup = {
        source_node: types.new_class(source_node, (owlready.Thing,), kwds={"ontology": ontology})
    }

    def recur(pnode):
        for neighbor in graph.neighbors(pnode):
            data = graph.node[neighbor]
            neighbor_class = types.new_class(neighbor, (parent_lookup[pnode],), kwds={"ontology": ontology})
            owlready.ANNOTATIONS[neighbor_class].add_annotation(owlready.rdfs.label, data['label'])
            recur(neighbor)

    recur(source_node)

    ontology.save(filename=output_path)
576785
def insert_into_graph(self, graph):
        
        u = self.source.as_bel()
        v = self.target.as_bel()

        if self.evidence:
            return graph.add_qualified_edge(u, v, **json.loads(self.data))
        else:
            return graph.add_unqualified_edge(u, v, self.relation)
773162
def assign_mv_feeder_to_nodes(mv_grid):
    
    mv_station_neighbors = mv_grid.graph.neighbors(mv_grid.station)
    # get all nodes in MV grid and remove MV station to get separate subgraphs
    mv_graph_nodes = mv_grid.graph.nodes()
    mv_graph_nodes.remove(mv_grid.station)
    subgraph = mv_grid.graph.subgraph(mv_graph_nodes)

    for neighbor in mv_station_neighbors:
        # determine feeder
        mv_feeder = mv_grid.graph.line_from_nodes(mv_grid.station, neighbor)
        # get all nodes in that feeder by doing a DFS in the disconnected
        # subgraph starting from the node adjacent to the MVStation `neighbor`
        subgraph_neighbor = nx.dfs_tree(subgraph, source=neighbor)
        for node in subgraph_neighbor.nodes():
            # in case of an LV station assign feeder to all nodes in that LV
            # grid
            if isinstance(node, LVStation):
                for lv_node in node.grid.graph.nodes():
                    lv_node.mv_feeder = mv_feeder
            else:
                node.mv_feeder = mv_feeder
755411
def render_edge_with_node_label(self, name, edge, edge_settings):
        
        props_to_display = self.extract_props(edge.settings)

        label = '<'
        label += "|".join(self.get_label(prop, value) for prop, value in props_to_display.items()) 
        label += '>'

        edge_node_name = "{}-{}".format(name, edge.to)

        self.gv_graph.node(edge_node_name, label=label, shape="record")

        self.gv_graph.edge(self.get_path_from_name(name), edge_node_name, arrowhead="none", **edge_settings)
        self.gv_graph.edge(edge_node_name, self.get_path_from_name(edge.to), **edge_settings)
698909
def _draw_ascii_graph(self, field):
        ''''''
        row_strings = []
        for y in range(len(field[0])):
            row = ''
            for x in range(len(field)):
                row += field[x][y]
            row_strings.insert(0, row)
        graph_string = '\n'.join(row_strings)
        return graph_string
431880
def print_network(self):  # pragma: no cover
        
        edges = set()

        def gen_edges(node):
            nonlocal edges
            name = str(id(node))

            yield '{name} [label="{cls_name}"];'.format(
                name=name,
                cls_name=str(node))

            for child in node.children:
                if (node, child.callback) not in edges:
                    yield ('{parent} -> {child} '
                           '[label="{child_label}"];').format(
                        parent=name,
                        child=str(id(child.node)),
                        child_label=child.callback.__name__)
                    edges.add((node, child.callback))
                yield from gen_edges(child.node)

        return "digraph {\n %s \n}" % ("\n".join(
            gen_edges(self.root_node)))
1261728
def inc_edges(self, node):
        
        try:
            return list(self.nodes[node][0])
        except KeyError:
            raise GraphError('Invalid node %s' % node)

        return None
1052428
def _get_output_nodes(self, output_path, error_path):
        
        from aiida.orm.data.array.trajectory import TrajectoryData
        import re

        state = None
        step = None
        scale = None
        with open(output_path) as f:
            lines = [x.strip('\n') for x in f.readlines()]

        result_dict = dict()
        trajectory = None
        for line in lines:
            if state is None and re.match('^\s*NWChem SCF Module\s*$',line):
                state = 'nwchem-scf-module'
                continue
            if state is None and re.match('^\s*NWChem Geometry Optimization\s*$',line):
                state = 'nwchem-geometry-optimisation'
                trajectory = TrajectoryData()
                continue
            if state == 'nwchem-scf-module' and re.match('^\s*Final RHF \s*results\s*$',line):
                state = 'final-rhf-results'
                continue
            if re.match('^\s*\-*\s*$',line):
                continue
            if state == 'final-rhf-results':
                result = re.match('^\s*([^=]+?)\s*=\s*([\-\d\.]+)$',line)
                if result:
                    key = re.sub('[^a-zA-Z0-9]+', '_', result.group(1).lower())
                    result_dict[key] = result.group(2)
                else:
                    state = 'nwchem-scf-module'
            if state == 'nwchem-geometry-optimisation' and re.match('^\s*Step\s+\d+\s*$',line):
                result = re.match('^\s*Step\s+(\d+)\s*$',line)
                step = result.group(1)
                continue
            if state == 'nwchem-geometry-optimisation' and \
                re.match('^\s*Output coordinates in a.u.',line):
                state = 'nwchem-geometry-optimisation-coordinates'
                result = re.match('scale by \s(*[\-\d\.]+)',line)
                scale = result.group(1)
                continue
        return [('parameters', ParameterData(dict=result_dict))]
81512
def as_graph(self) -> Graph:  # pragma: no cover
        """"""
        if Graph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        graph = Graph()
        nodes_left = {}  # type: Dict[TLeft, str]
        nodes_right = {}  # type: Dict[TRight, str]
        node_id = 0
        for (left, right), value in self._edges.items():
            if left not in nodes_left:
                name = 'node{:d}'.format(node_id)
                nodes_left[left] = name
                graph.node(name, label=str(left))
                node_id += 1
            if right not in nodes_right:
                name = 'node{:d}'.format(node_id)
                nodes_right[right] = name
                graph.node(name, label=str(right))
                node_id += 1
            edge_label = value is not True and str(value) or ''
            graph.edge(nodes_left[left], nodes_right[right], edge_label)
        return graph
530233
def graph(self, ig):
        

        res = copy.copy(self)
        res._edges = ig
        res._nodes = None
        return res
120592
def gtfs_to_graphviz(gtfs, stop_ids=None):
    
    graph = GraphViz()
    location_ids = choose_location_ids(gtfs, stop_ids)
    locations = [gtfs.get_location(i) for i in location_ids]

    for location in locations:
        if not location.parent_id:
            graph.add_cluster(GraphCluster(
                location.gtfs_id,
                location_label(location, max_length=-1),
                location_color(location.location_type)))

    for location in locations:
        if location.parent_id and requires_platform_cluster(location):
            graph.get_cluster(location.parent_id).add_cluster(GraphCluster(
                location.gtfs_id,
                location_label(location),
                location_color(location.location_type)))

    for location in locations:
        if not location.parent_id or requires_platform_cluster(location):
            continue
        node = GraphNode(
            location.gtfs_id,
            location_label(location, max_length=25),
            location_color(location.location_type),
            location_shape(location.location_type))
        cluster = graph.get_cluster(location.station().gtfs_id)
        if location.location_type == LocationType.boarding_area:
            cluster = cluster.get_cluster(location.parent_id)
        cluster.nodes.append(node)

    for pathway in gtfs.pathways:
        if pathway.from_id in location_ids and pathway.to_id in location_ids:
            graph.edges.append(GraphEdge(
                pathway.from_id, pathway.to_id,
                'both' if pathway.is_bidirectional else 'forward',
                pathway_label(pathway)))

    return graph
1125776
def gdfs_to_graph(gdf_nodes, gdf_edges):
    

    G = nx.MultiDiGraph()
    G.graph['crs'] = gdf_nodes.crs
    G.graph['name'] = gdf_nodes.gdf_name.rstrip('_nodes')

    # add the nodes and their attributes to the graph
    G.add_nodes_from(gdf_nodes.index)
    attributes = gdf_nodes.to_dict()
    for attribute_name in gdf_nodes.columns:
        # only add this attribute to nodes which have a non-null value for it
        attribute_values = {k:v for k, v in attributes[attribute_name].items() if pd.notnull(v)}
        nx.set_node_attributes(G, name=attribute_name, values=attribute_values)

    # add the edges and attributes that are not u, v, key (as they're added
    # separately) or null
    for _, row in gdf_edges.iterrows():
        attrs = {}
        for label, value in row.iteritems():
            if (label not in ['u', 'v', 'key']) and (isinstance(value, list) or pd.notnull(value)):
                attrs[label] = value
        G.add_edge(row['u'], row['v'], key=row['key'], **attrs)

    return G
753659
def _process_graph(self):
        
        all_nodes = [x.name for x in self.graph.as_graph_def().node]
        nodes = [x for x in all_nodes if x in self.possible_output_nodes]
        logger.info('List of nodes to export for brain :' + self.brain.brain_name)
        for n in nodes:
            logger.info('\t' + n)
        return nodes
293297
def export_graph(checkpoint_path, output_nodes):
    
    if not tf.gfile.Exists(checkpoint_path):
        raise AssertionError(
            "Export directory doesn't exists. Please specify an export "
            "directory: %s" % checkpoint_path)

    if not output_nodes:
        print("You need to supply the name of a node to --output_node_names.")
        return -1

        # We retrieve our checkpoint fullpath
    checkpoint = tf.train.get_checkpoint_state(checkpoint_path)
    input_checkpoint = checkpoint.model_checkpoint_path

    # We precise the file fullname of our freezed graph
    output_graph = checkpoint_path + "/frozen_model.pb"

    # We clear devices to allow TensorFlow to control on which device it will load operations
    clear_devices = True

    # We start a session using a temporary fresh Graph
    with tf.Session(graph=tf.Graph()) as sess:
        # We import the meta graph in the current default Graph
        saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)

        # We restore the weights
        saver.restore(sess, input_checkpoint)

        # We use a built-in TF helper to export variables to constants
        output_graph_def = tf.graph_util.convert_variables_to_constants(
            sess,  # The session is used to retrieve the weights
            tf.get_default_graph().as_graph_def(),  # The graph_def is used to retrieve the nodes
            output_nodes  # The output node names are used to select the useful nodes
        )

        # Finally we serialize and dump the output graph to the filesystem
        with tf.gfile.GFile(output_graph, "wb") as f:
            f.write(output_graph_def.SerializeToString())
        print("%d ops in the final graph." % len(output_graph_def.node))

    return output_graph_def
878794
def _get_output_nodes(self, output_path, error_path):
        
        status = cod_deposition_states.UNKNOWN
        messages = []

        if output_path is not None:
            content = None
            with open(output_path) as f:
                content = f.read()
            status, message = CifCodDepositParser._deposit_result(content)
            messages.extend(message.split('\n'))

        if error_path is not None:
            with open(error_path) as f:
                content = f.readlines()
            lines = [x.strip('\n') for x in content]
            messages.extend(lines)

        parameters = {'output_messages': messages, 'status': status}

        output_nodes = []
        output_nodes.append(('messages', Dict(dict=parameters)))

        if status == cod_deposition_states.SUCCESS:
            return True, output_nodes

        return False, output_nodes
1177731
def dot(graph, simple=True, debug=False, landscape=False):
    """"""
    import sys

    from rdflib import ConjunctiveGraph
    from rdflib.plugin import register, Parser
    from rdflib.tools.rdf2dot import rdf2dot

    register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')

    g = ConjunctiveGraph().parse(
        data=_jsonld(graph, 'expand'),
        format='json-ld',
    )

    g.bind('prov', 'http://www.w3.org/ns/prov#')
    g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#')
    g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#')
    g.bind('wfprov', 'http://purl.org/wf4ever/wfprov#')

    if debug:
        rdf2dot(g, sys.stdout)
        return

    sys.stdout.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n ')
    if landscape:
        sys.stdout.write('rankdir="LR" \n')
    if simple:
        _rdf2dot_simple(g, sys.stdout)
        return
    _rdf2dot_reduced(g, sys.stdout)
1313303
def edge_by_id(self, edge):
        
        try:
            head, tail, data =  self.edges[edge]
        except KeyError:
            head, tail = None, None
            raise GraphError('Invalid edge %s' % edge)

        return (head, tail)