graph generators
544796
function random (nodes, edges, prefix) {
  prefix = prefix || '#'
  if(isNaN(+nodes)) throw new Error('nodes must be a number')
  if(isNaN(+edges)) throw new Error('edges must be a number')

  var n = 0, g = {}

  function rand(n) {
    return prefix+~~(Math.random()*n)
  }

  for(var i = 0; i < nodes; i++)
    addNode(g, prefix+i)

  for(var i = 0; i < edges; i++) {
    var a = rand(nodes), b = rand(nodes)
    addEdge(g, a, b)
    addEdge(g, b, a)
  }

  return g
}
34240
def _to_graph(self, contexts):
        """"""
        prev = None

        for context in contexts:
            if prev is None:
                prev = context
                continue

            yield prev[0], context[1], context[0]
            prev = context
958841
def generate(self):
        
        logger.info('Generating graphs')
        self._generate_graph(
            'by-version',
            'Downloads by Version',
            self._stats.per_version_data,
            'Version'
        )
        self._generate_graph(
            'by-file-type',
            'Downloads by File Type',
            self._stats.per_file_type_data,
            'File Type'
        )
        self._generate_graph(
            'by-installer',
            'Downloads by Installer',
            self._stats.per_installer_data,
            'Installer'
        )
        self._generate_graph(
            'by-implementation',
            'Downloads by Python Implementation/Version',
            self._stats.per_implementation_data,
            'Implementation/Version'
        )
        self._generate_graph(
            'by-system',
            'Downloads by System Type',
            self._stats.per_system_data,
            'System'
        )
        self._generate_graph(
            'by-country',
            'Downloads by Country',
            self._stats.per_country_data,
            'Country'
        )
        self._generate_graph(
            'by-distro',
            'Downloads by Distro',
            self._stats.per_distro_data,
            'Distro'
        )
        self._generate_badges()
        logger.info('Generating HTML')
        html = self._generate_html()
        html_path = os.path.join(self.output_dir, 'index.html')
        with open(html_path, 'wb') as fh:
            fh.write(html.encode('utf-8'))
        logger.info('HTML report written to %s', html_path)
        logger.info('Writing SVG badges')
        for name, svg in self._badges.items():
            path = os.path.join(self.output_dir, '%s.svg' % name)
            with open(path, 'w') as fh:
                fh.write(svg)
            logger.info('%s badge written to: %s', name, path)
854401
def _graph_reduction(adj, x, g, f):
    
    as_list = set()
    as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
    while as_nodes:
        as_list.union(as_nodes)
        for n in as_nodes:

            # update g and f
            dv = len(adj[n])
            if dv > g:
                g = dv
            if g > f:
                f = g

            # eliminate v
            x.append(n)
            _elim_adj(adj, n)

        # see if we have any more simplicial nodes
        as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}

    return g, f, as_list
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
1048079
def make_batch(size, graph):
        
        i = iter(graph)
        chunk = list(islice(i, size))
        while chunk:
            yield chunk
            chunk = list(islice(i, size))
1138053
def mygenerator(n=5, n_edges=5):
    '''
    
    '''
    G = nx.Graph()

    for i in range(n):
        G.add_node(i)
    
    for i in range(n_edges):
        nodes = list(G.nodes)
        n_in = choice(nodes)
        nodes.remove(n_in)  # Avoid loops
        n_out = choice(nodes)
        G.add_edge(n_in, n_out)
    return G
968030
def generate_graphs(data, name, results_dir):
    
    graphs.resp_graph_raw(data['raw'], name + '_response_times.svg', results_dir)
    graphs.resp_graph(data['compiled'], name + '_response_times_intervals.svg', results_dir)
    graphs.tp_graph(data['compiled'], name + '_throughput.svg', results_dir)
1768
def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None,
                               weighting='none'):
  ''''''
  assert ((k is not None) or (epsilon is not None)
          ), "Must provide `k` or `epsilon`"
  assert (_issequence(k) ^ _issequence(epsilon)
          ), "Exactly one of `k` or `epsilon` must be a sequence."
  assert weighting in ('binary','none'), "Invalid weighting param: " + weighting
  is_weighted = weighting == 'none'

  if precomputed:
    D = X
  else:
    D = pairwise_distances(X, metric='euclidean')
  # pre-sort for efficiency
  order = np.argsort(D)[:,1:]

  if k is None:
    k = D.shape[0]

  # generate the sequence of graphs
  # TODO: convert the core of these loops to Cython for speed
  W = np.zeros_like(D)
  I = np.arange(D.shape[0])
  if _issequence(k):
    # varied k, fixed epsilon
    if epsilon is not None:
      D[D > epsilon] = 0
    old_k = 0
    for new_k in k:
      idx = order[:, old_k:new_k]
      dist = D[I, idx.T]
      W[I, idx.T] = dist if is_weighted else 1
      yield Graph.from_adj_matrix(W)
      old_k = new_k
  else:
    # varied epsilon, fixed k
    idx = order[:,:k]
    dist = D[I, idx.T].T
    old_i = np.zeros(D.shape[0], dtype=int)
    for eps in epsilon:
      for i, row in enumerate(dist):
        oi = old_i[i]
        ni = oi + np.searchsorted(row[oi:], eps)
        rr = row[oi:ni]
        W[i, idx[i,oi:ni]] = rr if is_weighted else 1
        old_i[i] = ni
      yield Graph.from_adj_matrix(W)
316652
def iter_initial_relations(self, subject_graph):
        """"""
        vertex0 = 0
        for vertex1 in range(subject_graph.num_vertices):
            yield vertex0, vertex1
430872
def _build_graph(self):
        
        self._graph.add_nodes_from(self.tasks)
        for node1 in self._graph.nodes:
            for node2 in self._graph.nodes:
                for input_file in node1.inputs:
                    for output_file in node2.outputs:
                        if output_file == input_file:
                            self._graph.add_edge(node2, node1)
        for order, task in enumerate(topological_sort(self._graph)):
            task.predecessors = self._graph.predecessors(task)
            task.order = order
242622
def _make_graph(self):
        """"""
        self.nodes['graph'] = self.svg.node(
            class_='graph %s-graph %s' % (
                self.__class__.__name__.lower(),
                'horizontal' if self.horizontal else 'vertical'
            )
        )
        self.svg.node(
            self.nodes['graph'],
            'rect',
            class_='background',
            x=0,
            y=0,
            width=self.width,
            height=self.height
        )
        self.nodes['plot'] = self.svg.node(
            self.nodes['graph'],
            class_="plot",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.svg.node(
            self.nodes['plot'],
            'rect',
            class_='background',
            x=0,
            y=0,
            width=self.view.width,
            height=self.view.height
        )
        self.nodes['title'] = self.svg.node(
            self.nodes['graph'], class_="titles"
        )
        self.nodes['overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['text_overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot text-overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['tooltip_overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot tooltip-overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['tooltip'] = self.svg.node(
            self.nodes['tooltip_overlay'],
            transform='translate(0 0)',
            style="opacity: 0",
            **{'class': 'tooltip'}
        )

        self.svg.node(
            self.nodes['tooltip'],
            'rect',
            rx=self.tooltip_border_radius,
            ry=self.tooltip_border_radius,
            width=0,
            height=0,
            **{'class': 'tooltip-box'}
        )
        self.svg.node(self.nodes['tooltip'], 'g', class_='text')
1261507
def filter_edges(graph: BELGraph, edge_predicates: EdgePredicates) -> EdgeIterator:
    
    compound_edge_predicate = and_edge_predicates(edge_predicates=edge_predicates)
    for u, v, k in graph.edges(keys=True):
        if compound_edge_predicate(graph, u, v, k):
            yield u, v, k
516753
void graphToRDF(String graphName, Map<String, Object> graph) {
        // 4.2)
        final List<Quad> triples = new ArrayList<Quad>();
        // 4.3)
        final List<String> subjects = new ArrayList<String>(graph.keySet());
        // Collections.sort(subjects);
        for (final String id : subjects) {
            if (JsonLdUtils.isRelativeIri(id)) {
                continue;
            }
            final Map<String, Object> node = (Map<String, Object>) graph.get(id);
            final List<String> properties = new ArrayList<String>(node.keySet());
            Collections.sort(properties);
            for (String property : properties) {
                final List<Object> values;
                // 4.3.2.1)
                if ("@type".equals(property)) {
                    values = (List<Object>) node.get("@type");
                    property = RDF_TYPE;
                }
                // 4.3.2.2)
                else if (isKeyword(property)) {
                    continue;
                }
                // 4.3.2.3)
                else if (property.startsWith("_:") && !api.opts.getProduceGeneralizedRdf()) {
                    continue;
                }
                // 4.3.2.4)
                else if (JsonLdUtils.isRelativeIri(property)) {
                    continue;
                } else {
                    values = (List<Object>) node.get(property);
                }

                Node subject;
                if (id.indexOf("_:") == 0) {
                    // NOTE: don't rename, just set it as a blank node
                    subject = new BlankNode(id);
                } else {
                    subject = new IRI(id);
                }

                // RDF predicates
                Node predicate;
                if (property.startsWith("_:")) {
                    predicate = new BlankNode(property);
                } else {
                    predicate = new IRI(property);
                }

                for (final Object item : values) {
                    // convert @list to triples
                    if (isList(item)) {
                        final List<Object> list = (List<Object>) ((Map<String, Object>) item)
                                .get("@list");
                        Node last = null;
                        Node firstBNode = nil;
                        if (!list.isEmpty()) {
                            last = objectToRDF(list.get(list.size() - 1));
                            firstBNode = new BlankNode(api.generateBlankNodeIdentifier());
                        }
                        triples.add(new Quad(subject, predicate, firstBNode, graphName));
                        for (int i = 0; i < list.size() - 1; i++) {
                            final Node object = objectToRDF(list.get(i));
                            triples.add(new Quad(firstBNode, first, object, graphName));
                            final Node restBNode = new BlankNode(api.generateBlankNodeIdentifier());
                            triples.add(new Quad(firstBNode, rest, restBNode, graphName));
                            firstBNode = restBNode;
                        }
                        if (last != null) {
                            triples.add(new Quad(firstBNode, first, last, graphName));
                            triples.add(new Quad(firstBNode, rest, nil, graphName));
                        }
                    }
                    // convert value or node object to triple
                    else {
                        final Node object = objectToRDF(item);
                        if (object != null) {
                            triples.add(new Quad(subject, predicate, object, graphName));
                        }
                    }
                }
            }
        }
        put(graphName, triples);
    }
404916
public Graph generateRandomMMapGraph(String graphName, int size, float dens) {
		
		Graph graph = null;
		String dir = "graphs/MMap/" + graphName;
		
		SerializationUtils.deleteMMapGraph(dir);
		graph = new Graph(new MMapGraphStructure(dir));
		
		Random rand = new Random();
		
		for (int i = 0; i < size; i++)
			graph.addNode(new Node(i));
		
		for (int i = 0; i < size; i++) {
			for (int j = i+1; j < size; j++) {
				
				if (rand.nextFloat() < dens) {
					int randomCost = Math.abs(rand.nextInt(50)) + 1;
					Edge e = new Edge(i, j, randomCost);
					e.setBidirectional(rand.nextBoolean());
					
					graph.addEdge(e);
				}
			
			}
		}

		return graph;
	}
566137
public void learn(Graph graph, SplitWord splitWord, Forest... forests) {

		this.splitWord = splitWord;

		this.forests = forests;
	}
1096219
def sequence_to_graph(G, seq, color='black'):
    
    for x in seq:
        if x.endswith("_1"):  # Mutation
            G.node(x, color=color, width="0.1", shape="circle", label="")
        else:
            G.node(x, color=color)
    for a, b in pairwise(seq):
        G.edge(a, b, color=color)