Creates the graph from OSM data.
340790
private GraphHopper process(String graphHopperLocation) {
        setGraphHopperLocation(graphHopperLocation);
        GHLock lock = null;
        try {
            if (ghStorage.getDirectory().getDefaultType().isStoring()) {
                lockFactory.setLockDir(new File(graphHopperLocation));
                lock = lockFactory.create(fileLockName, true);
                if (!lock.tryLock())
                    throw new RuntimeException("To avoid multiple writers we need to obtain a write lock but it failed. In " + graphHopperLocation, lock.getObtainFailedReason());
            }

            try {
                DataReader reader = importData();
                DateFormat f = createFormatter();
                ghStorage.getProperties().put("datareader.import.date", f.format(new Date()));
                if (reader.getDataDate() != null)
                    ghStorage.getProperties().put("datareader.data.date", f.format(reader.getDataDate()));
            } catch (IOException ex) {
                throw new RuntimeException("Cannot read file " + getDataReaderFile(), ex);
            }
            cleanUp();
            postProcessing();
            flush();
        } finally {
            if (lock != null)
                lock.release();
        }
        return this;
    }
128985
def _create_graph(self, return_target_sources=None):
        
        if return_target_sources is None:
            # We set it to a defaultdict in order to be consistent with the
            # actual parameter.
            return_target_sources = defaultdict(list)

        cfg = networkx.DiGraph()
        # The corner case: add a node to the graph if there is only one block
        if len(self._nodes) == 1:
            cfg.add_node(self._nodes[next(iter(self._nodes.keys()))])

        # Adding edges
        for tpl, targets in self._exit_targets.items():
            basic_block = self._nodes[tpl] # Cannot fail :)
            for ex, jumpkind in targets:
                if ex in self._nodes:
                    target_bbl = self._nodes[ex]
                    cfg.add_edge(basic_block, target_bbl, jumpkind=jumpkind)

                    # Add edges for possibly missing returns
                    if basic_block.addr in return_target_sources:
                        for src_irsb_key in \
                                return_target_sources[basic_block.addr]:
                            cfg.add_edge(self._nodes[src_irsb_key],
                                               basic_block, jumpkind="Ijk_Ret")
                else:
                    # Debugging output
                    def addr_formalize(addr):
                        if addr is None:
                            return "None"
                        else:
                            return "%#08x" % addr

                    s = "(["
                    for addr in ex[:-1]:
                        s += addr_formalize(addr) + ", "
                    s += "] %s)" % addr_formalize(ex[-1])
                    l.warning("Key %s does not exist.", s)

        return cfg
255698
def graph_from_dot_file(path, encoding=None):
    
    with io.open(path, 'rt', encoding=encoding) as f:
        s = f.read()
    if not PY3:
        s = unicode(s)
    graphs = graph_from_dot_data(s)
    return graphs
106856
def to_graph(self):
        
        edges = set()
        for clause, target in self.edges_iter():
            for source, signature in clause:
                edges.add((source, target, signature))

        return Graph.from_tuples(edges)
1275427
def to_string(self):
        


        graph = list()

        if self.obj_dict.get('strict', None) is not None:

            if (self == self.get_parent_graph() and
                    self.obj_dict['strict']):

                graph.append('strict ')

        graph_type = self.obj_dict['type']
        if (graph_type == 'subgraph' and
                not self.obj_dict.get('show_keyword', True)):
            graph_type = ''
        s = '{type} {name} {{\n'.format(
            type=graph_type,
            name=self.obj_dict['name'])
        graph.append(s)

        for attr in sorted(self.obj_dict['attributes']):

            if self.obj_dict['attributes'].get(attr, None) is not None:

                val = self.obj_dict['attributes'].get(attr)
                if val == '':
                    val = '""'
                if val is not None:
                    graph.append('%s=%s' %
                                 (attr, quote_if_necessary(val)))
                else:
                    graph.append( attr )

                graph.append( ';\n' )


        edges_done = set()

        edge_obj_dicts = list()
        for k in self.obj_dict['edges']:
            edge_obj_dicts.extend(self.obj_dict['edges'][k])

        if edge_obj_dicts:
            edge_src_set, edge_dst_set = list(zip(
                *[obj['points'] for obj in edge_obj_dicts]))
            edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set)
        else:
            edge_src_set, edge_dst_set = set(), set()

        node_obj_dicts = list()
        for k in self.obj_dict['nodes']:
            node_obj_dicts.extend(self.obj_dict['nodes'][k])

        sgraph_obj_dicts = list()
        for k in self.obj_dict['subgraphs']:
            sgraph_obj_dicts.extend(self.obj_dict['subgraphs'][k])


        obj_list = [(obj['sequence'], obj)
                    for obj in (edge_obj_dicts +
                                node_obj_dicts + sgraph_obj_dicts) ]
        obj_list.sort(key=lambda x: x[0])

        for idx, obj in obj_list:

            if obj['type'] == 'node':

                node = Node(obj_dict=obj)

                if self.obj_dict.get('suppress_disconnected', False):

                    if (node.get_name() not in edge_src_set and
                        node.get_name() not in edge_dst_set):

                        continue

                graph.append( node.to_string()+'\n' )

            elif obj['type'] == 'edge':

                edge = Edge(obj_dict=obj)

                if (self.obj_dict.get('simplify', False) and
                        edge in edges_done):
                    continue

                graph.append( edge.to_string() + '\n' )
                edges_done.add(edge)

            else:

                sgraph = Subgraph(obj_dict=obj)

                graph.append( sgraph.to_string()+'\n' )

        graph.append( '}\n' )

        return ''.join(graph)
984891
def _get_graphviz_data(self):
        
        s = []
        header = '// Process this file with graphviz\n'
        s.append( header)
        s.append('digraph G {\n')
        s.append('    node [shape=box];\n')
        for md in self.metadata:
            label = trunc(md.str, 48).replace('"', "'")
            extra = ''
            if md.type == 'instancemethod':
                extra = ', color=red'
            elif md.type == 'frame':
                extra = ', color=orange'
            s.append('    "X%s" [ label = "%s\\n%s" %s ];\n' % \
                (hex(md.id)[1:], label, md.type, extra))
        for e in self.edges:
            extra = ''
            if e.label == '__dict__':
                extra = ',weight=100'
            s.append('    X%s -> X%s [label="%s"%s];\n' % \
                (hex(e.src)[1:], hex(e.dst)[1:], e.label, extra))

        s.append('}\n')
        return "".join(s)
65415
def make_model(self):
        """"""
        # Assemble in two stages.
        # First, create the nodes of the graph
        for stmt in self.statements:
            # Skip SelfModification (self loops) -- has one node
            if isinstance(stmt, SelfModification) or \
               isinstance(stmt, Translocation) or \
               isinstance(stmt, ActiveForm):
                continue
            # Special handling for Associations -- more than 1 node and members
            # are Events
            elif isinstance(stmt, Association):
                for m in stmt.members:
                    self._add_node(m.concept)
            # Special handling for Complexes -- more than 1 node
            elif isinstance(stmt, Complex):
                for m in stmt.members:
                    self._add_node(m)
            # All else should have exactly 2 nodes
            elif all([ag is not None for ag in stmt.agent_list()]):
                if not len(stmt.agent_list()) == 2:
                    logger.warning(
                        '%s has less/more than the expected 2 agents.' % stmt)
                    continue
                for ag in stmt.agent_list():
                    self._add_node(ag)
        # Second, create the edges of the graph
        for stmt in self.statements:
            # Skip SelfModification (self loops) -- has one node
            if isinstance(stmt, SelfModification) or \
               isinstance(stmt, Translocation) or \
               isinstance(stmt, ActiveForm):
                continue
            elif isinstance(stmt, Association):
                self._add_complex(stmt.members, is_association=True)
            elif isinstance(stmt, Complex):
                self._add_complex(stmt.members)
            elif all([ag is not None for ag in stmt.agent_list()]):
                self._add_stmt_edge(stmt)
468817
def to_graphml(graph: BELGraph, path: Union[str, BinaryIO]) -> None:
    
    rv = nx.MultiDiGraph()

    for node in graph:
        rv.add_node(node.as_bel(), function=node.function)

    for u, v, key, edge_data in graph.edges(data=True, keys=True):
        rv.add_edge(
            u.as_bel(),
            v.as_bel(),
            interaction=edge_data[RELATION],
            bel=graph.edge_to_bel(u, v, edge_data),
            key=key,
        )

    nx.write_graphml(rv, path)
537166
function loadGraphSON(graph, filename, callback) {
        var FileInputStream = Tinkerpop.autoImport('FileInputStream');
        var stream = new FileInputStream(filename);
        return Tinkerpop.GraphSONReader.buildP()
            .then(function (builder) {
            return _newGraphSONMapper()
                .then(function (mapper) { return builder.mapperP(mapper); });
        })
            .then(function (builder) { return builder.createP(); })
            .then(function (reader) { return reader.readGraphP(stream, graph); })
            .then(function () { return graph; })
            .nodeify(callback);
    }
1161302
def startGraph(self):
        """"""
        g = r.Graph()
        g.namespace_manager.bind("rdf", r.namespace.RDF)    
        g.namespace_manager.bind("foaf", r.namespace.FOAF)    
        g.namespace_manager.bind("xsd", r.namespace.XSD)    
        g.namespace_manager.bind("opa", "http://purl.org/socialparticipation/opa/")    
        g.namespace_manager.bind("ops", "http://purl.org/socialparticipation/ops/")    
        g.namespace_manager.bind("wsg", "http://www.w3.org/2003/01/geo/wgs84_pos#")    
        g.namespace_manager.bind("dc2", "http://purl.org/dc/elements/1.1/")    
        g.namespace_manager.bind("dc", "http://purl.org/dc/terms/")    
        g.namespace_manager.bind("sioc", "http://rdfs.org/sioc/ns#")    
        g.namespace_manager.bind("tsioc", "http://rdfs.org/sioc/types#")    
        g.namespace_manager.bind("schema", "http://schema.org/")
        g.namespace_manager.bind("part", "http://participa.br/")
        self.g=g
38976
private static Graph buildGraph() {
        Graph g = new TinkerGraph();
        //add vertices
        Vertex v1 = g.addVertex("v1");
        Vertex v2 = g.addVertex("v2");
        Vertex v3 = g.addVertex("v3");
        Vertex v4 = g.addVertex("v4");
        Vertex v5 = g.addVertex("v5");
        Vertex v6 = g.addVertex("v6");

        //add edges labeled with costs
        Edge e1 = g.addEdge("e1", v1, v2, "(7, 1)");
        e1.setProperty("c1", 7);
        e1.setProperty("c2", 1);

        Edge e2 = g.addEdge("e2", v1, v3, "(1, 4)");
        e2.setProperty("c1", 1);
        e2.setProperty("c2", 4);

        Edge e3 = g.addEdge("e3", v1, v4, "(2, 1)");
        e3.setProperty("c1", 2);
        e3.setProperty("c2", 1);

        Edge e4 = g.addEdge("e4", v2, v4, "(1, 1)");
        e4.setProperty("c1", 1);
        e4.setProperty("c2", 1);

        Edge e5 = g.addEdge("e5", v2, v6, "(2, 1)");
        e5.setProperty("c1", 2);
        e5.setProperty("c2", 1);

        Edge e6 = g.addEdge("e6", v3, v4, "(1, 1)");
        e6.setProperty("c1", 1);
        e6.setProperty("c2", 1);

        Edge e7 = g.addEdge("e7", v4, v5, "(3, 2)");
        e7.setProperty("c1", 3);
        e7.setProperty("c2", 2);

        Edge e8 = g.addEdge("e8", v4, v6, "(4, 8)");
        e8.setProperty("c1", 4);
        e8.setProperty("c2", 8);

        Edge e9 = g.addEdge("e9", v5, v6, "(1, 1)");
        e9.setProperty("c1", 1);
        e9.setProperty("c2", 1);

        return g;
    }
607660
def new_multidigraph(self, name, data=None, **attr):
        
        self._init_graph(name, 'MultiDiGraph')
        mdg = MultiDiGraph(self, name, data, **attr)
        self._graph_objs[name] = mdg
        return mdg
134104
def _build_graph(self):
        ''''''

        # Set palette colors if necessary
        if not self.colors:
            self.palette = self.env.get_template('palette.js')
            self.template_vars.update({'palette': self.palette.render()})
            self.colors = {x['name']: 'palette.color()' for x in self.json_data}

        template_vars = []
        for index, dataset in enumerate(self.json_data):
            group = 'datagroup' + str(index)
            template_vars.append({'name': str(dataset['name']),
                                  'color': self.colors[dataset['name']],
                                  'data': 'json[{0}].data'.format(index)})

        variables = {'dataset': template_vars, 'width': self.width,
                     'height': self.height, 'render': self.renderer,
                     'chart_id': self.chart_id}
        if not self.y_zero:
            variables.update({'min': "min: 'auto',"})

        graph = self.env.get_template('graph.js')
        self.template_vars.update({'graph': graph.render(variables)})
1019817
def create_copy_without_data(G):
    """"""
    H = nx.Graph()
    for i in H.nodes_iter():
        H.node[i] = {}
    return H
360143
def make_dot_graph(filename, format='png', tool='dot', stop=True):
    
    if stop:
        stop_trace()

    dot_data = get_dot()

    # normalize filename
    regex_user_expand = re.compile('\A~')
    if regex_user_expand.match(filename):
        filename = os.path.expanduser(filename)
    else:
        filename = os.path.expandvars(filename)  # expand, just in case

    if format == 'dot':
        f = open(filename, 'w')
        f.write(dot_data)
        f.close()

    else:
        # create a temporary file to be used for the dot data
        fd, tempname = tempfile.mkstemp()
        with os.fdopen(fd, 'w') as f:
            f.write(dot_data)

        cmd = '%(tool)s -T%(format)s -o%(filename)s %(tempname)s' % locals()
        try:
            ret = os.system(cmd)
            if ret:
                raise PyCallGraphException( \
                    'The command "%(cmd)s" failed with error ' \
                    'code %(ret)i.' % locals())
        finally:
            os.unlink(tempname)
178250
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):
    """"""
    graph = tf.get_default_graph()
    assert graph.unique_name(scope, False) == scope, (
        'Scope "%s" already exists. Provide explicit scope names when '
        'importing multiple instances of the model.') % scope
    t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)
    tf.import_graph_def(
        self.graph_def, {self.input_name: t_prep_input}, name=scope)
    self.post_import(scope)
434949
def construct_graph(args):
    """"""

    app = Core(args)

    setup_root(app)

    if args['debug']:
        from circuits import Debugger
        hfoslog("Starting circuits debugger", lvl=warn, emitter='GRAPH')
        dbg = Debugger().register(app)
        # TODO: Make these configurable from modules, navdata is _very_ noisy
        # but should not be listed _here_
        dbg.IgnoreEvents.extend([
            "read", "_read", "write", "_write",
            "stream_success", "stream_complete",
            "serial_packet", "raw_data", "stream",
            "navdatapush", "referenceframe",
            "updateposition", "updatesubscriptions",
            "generatevesseldata", "generatenavdata", "sensordata",
            "reset_flood_offenders", "reset_flood_counters",  # Flood counters
            "task_success", "task_done",  # Thread completion
            "keepalive"  # IRC Gateway
        ])

    hfoslog("Beginning graph assembly.", emitter='GRAPH')

    if args['drawgraph']:
        from circuits.tools import graph

        graph(app)

    if args['opengui']:
        import webbrowser
        # TODO: Fix up that url:
        webbrowser.open("http://%s:%i/" % (args['host'], args['port']))

    hfoslog("Graph assembly done.", emitter='GRAPH')

    return app