Write one node and all possible edges.
9104
def log_url (self, url_data):
        """"""
        node = self.get_node(url_data)
        if node:
            self.xml_starttag(u'node', attrs={u"name": u"%d" % node["id"]})
            self.xml_tag(u"label", node["label"])
            if self.has_part("realurl"):
                self.xml_tag(u"url", node["url"])
            self.xml_starttag(u"data")
            if node["dltime"] >= 0 and self.has_part("dltime"):
                self.xml_tag(u"dltime", u"%f" % node["dltime"])
            if node["size"] >= 0 and self.has_part("dlsize"):
                self.xml_tag(u"size", u"%d" % node["size"])
            if node["checktime"] and self.has_part("checktime"):
                self.xml_tag(u"checktime", u"%f" % node["checktime"])
            if self.has_part("extern"):
                self.xml_tag(u"extern", u"%d" % node["extern"])
            self.xml_endtag(u"data")
            self.xml_endtag(u"node")
385237
public static void writeEdge(Node src, Node tgt, Edge edge,
            PrintWriter writer) {
        StringBuilder sb = new StringBuilder();
        RelationshipType rel = edge.rel;
        String reldispval = rel.getDisplayValue();
        sb.append("  <edge label='");
        String dispval = format(EDGE_LABEL, src.label, rel, tgt.label);
        sb.append(dispval);
        sb.append("' source='");
        sb.append(edge.source.toString());
        sb.append("' target='");
        sb.append(edge.target.toString());
        sb.append("'>\n");
        sb.append("    <att name='relationship type'");
        sb.append(" value='");
        sb.append(reldispval);
        sb.append("' />\n");

        // Edge graphics
        String color = color(rel);
        String graphics = format(EDGE_GRAPHICS, 1, color, 1, reldispval);
        sb.append(graphics);

        sb.append("  </edge>\n");
        writer.write(sb.toString());
    }
1182076
private static <N, E> void writeRaw(Graph<N, E> graph,
                                        Appendable a,
                                        DOTVisualizationHelper<N, ? super E> dotHelperOrNull) throws IOException {

        final DOTVisualizationHelper<N, ? super E> dotHelper;

        if (dotHelperOrNull == null) {
            dotHelper = new DefaultDOTVisualizationHelper<>();
        } else {
            dotHelper = dotHelperOrNull;
        }

        final boolean directed = !(graph instanceof UndirectedGraph);

        if (directed) {
            a.append("di");
        }

        a.append("graph g {").append(System.lineSeparator());

        Map<String, String> props = new HashMap<>();

        dotHelper.getGlobalNodeProperties(props);
        if (!props.isEmpty()) {
            a.append('\t').append("node");
            appendParams(props, a);
            a.append(';').append(System.lineSeparator());
        }

        props.clear();
        dotHelper.getGlobalEdgeProperties(props);
        if (!props.isEmpty()) {
            a.append('\t').append("edge");
            appendParams(props, a);
            a.append(';').append(System.lineSeparator());
        }

        dotHelper.writePreamble(a);
        a.append(System.lineSeparator());

        MutableMapping<N, String> nodeNames = graph.createStaticNodeMapping();
        Set<String> initialNodes = new HashSet<>();

        int i = 0;

        for (N node : graph) {
            props.clear();
            if (!dotHelper.getNodeProperties(node, props)) {
                continue;
            }
            String id = "s" + i++;

            // remove potential attributes that are no valid DOT attributes
            if (Boolean.parseBoolean(props.remove(NodeAttrs.INITIAL))) {
                initialNodes.add(id);
            }
            props.remove(NodeAttrs.ACCEPTING);

            a.append('\t').append(id);
            appendParams(props, a);
            a.append(';').append(System.lineSeparator());
            nodeNames.put(node, id);
        }

        for (N node : graph) {
            String srcId = nodeNames.get(node);
            if (srcId == null) {
                continue;
            }
            Collection<E> outEdges = graph.getOutgoingEdges(node);
            if (outEdges.isEmpty()) {
                continue;
            }
            for (E e : outEdges) {
                N tgt = graph.getTarget(e);
                String tgtId = nodeNames.get(tgt);
                if (tgtId == null) {
                    continue;
                }

                if (!directed && tgtId.compareTo(srcId) < 0) {
                    continue;
                }

                props.clear();
                if (!dotHelper.getEdgeProperties(node, e, tgt, props)) {
                    continue;
                }

                a.append('\t').append(srcId).append(' ');
                if (directed) {
                    a.append("-> ");
                } else {
                    a.append("-- ");
                }
                a.append(tgtId);
                appendParams(props, a);
                a.append(';').append(System.lineSeparator());
            }
        }

        a.append(System.lineSeparator());
        renderInitialArrowTip(initialNodes, a);

        dotHelper.writePostamble(a);
        a.append(System.lineSeparator());

        a.append('}').append(System.lineSeparator());
        if (a instanceof Flushable) {
            ((Flushable) a).flush();
        }
    }
972902
def complete(self):
        
        for each in self.nodes():
            for other in self.nodes():
                if (each != other and not self.has_edge((each, other))):
                    self.add_edge((each, other))
906196
def write(self, *messages):
        """"""

        for i in self.graph.outputs_of(BEGIN):
            for message in messages:
                self[i].write(message)
1226185
def write_grid_to_vtk(fname, nodes, edges, node_flag=None, edge_flag=None):
    

    if node_flag is None:
        node_flag = np.ones([nodes.shape[0]], dtype=np.bool)
    if edge_flag is None:
        edge_flag = np.ones([edges.shape[0]], dtype=np.bool)
    nodes = make_nodes_3d(nodes)
    f = open(fname, "w")

    f.write("# vtk DataFile Version 2.6\n")
    f.write("output file\nASCII\nDATASET UNSTRUCTURED_GRID\n")

    idxs = nm.where(node_flag > 0)[0]
    nnd = len(idxs)
    aux = -nm.ones(node_flag.shape, dtype=nm.int32)
    aux[idxs] = nm.arange(nnd, dtype=nm.int32)
    f.write("\nPOINTS %d float\n" % nnd)
    for ndi in idxs:
        f.write("%.6f %.6f %.6f\n" % tuple(nodes[ndi, :]))

    idxs = nm.where(edge_flag > 0)[0]
    ned = len(idxs)
    f.write("\nCELLS %d %d\n" % (ned, ned * 3))
    for edi in idxs:
        f.write("2 %d %d\n" % tuple(aux[edges[edi, :]]))

    f.write("\nCELL_TYPES %d\n" % ned)
    for edi in idxs:
        f.write("3\n")
1365475
def exist_edge(self, graph, orig, dest, idx, branch, turn, tick, extant):
        """"""
        if (branch, turn, tick) in self._btts:
            raise TimeError
        self._btts.add((branch, turn, tick))
        graph, orig, dest = map(self.pack, (graph, orig, dest))
        self._edges2set.append((graph, orig, dest, idx, branch, turn, tick, extant))
985791
def neighbors(self, node_id):
        """"""
        node = self.get_node(node_id)
        return [self.get_edge(edge_id)['vertices'][1] for edge_id in node['edges']]
1032150
def get_root_graph(self,root):
      """"""
      children = self.get_children(root)
      g = Graph()
      nodes = [root]+children
      for node in nodes: g.add_node(node)
      node_ids = [x.id for x in nodes]
      edges = [x for x in self._edges.values() if x.node1.id in node_ids and x.node2.id in node_ids]
      for e in edges: g.add_edge(e)
      return g
1092360
def write_as_dot(self, f, data=None, max_levels=None):
        ""
        assert (max_levels is None) or (max_levels >= 0)
        def visit_node(n, levels):
            lbl = "{"
            if data is None:
                if self.k <= max_k_labeled:
                    lbl = repr(n.label()).\
                          replace("{","\{").\
                          replace("}","\}").\
                          replace("|","\|").\
                          replace("<","\<").\
                          replace(">","\>")
                else:
                    lbl = str(n)
            else:
                s = self.bucket_to_block(n.bucket)
                for i in xrange(self.blocks_per_bucket):
                    lbl += "{%s}" % (data[s+i])
                    if i + 1 != self.blocks_per_bucket:
                        lbl += "|"
            lbl += "}"
            f.write("  %s [penwidth=%s,label=\"%s\"];\n"
                    % (n.bucket, 1, lbl))
            levels += 1
            if (max_levels is None) or (levels <= max_levels):
                for i in xrange(self.k):
                    cn = n.child_node(i)
                    if not self.is_nil_node(cn):
                        visit_node(cn, levels)
                        f.write("  %s -> %s ;\n" % (n.bucket, cn.bucket))

        f.write("// Created by SizedVirtualHeap.write_as_dot(...)\n")
        f.write("digraph heaptree {\n")
        f.write("node [shape=record]\n")

        if (max_levels is None) or (max_levels > 0):
            visit_node(self.root_node(), 1)
        f.write("}\n")
1042205
def _adjacency_to_edges(adjacency):
    """"""
    edges = set()
    for u in adjacency:
        for v in adjacency[u]:
            try:
                edge = (u, v) if u <= v else (v, u)
            except TypeError:
                # Py3 does not allow sorting of unlike types
                if (v, u) in edges:
                    continue
                edge = (u, v)

            edges.add(edge)
    return edges
18056
def _rm_gos_edges(rm_goids, edges_all):
        """"""
        edges_reduced = []
        for goid_child, goid_parent in sorted(edges_all, key=lambda t: t[1]):
            if goid_child not in rm_goids and goid_parent not in rm_goids:
                edges_reduced.append((goid_child, goid_parent))
        return edges_reduced
312725
function writeNode(node, c, end) {
      var toYield = [];
      forEach(simplifyDOM(node, end), function(part) {
        toYield.push(insertPart(part));
      });
      return yield(toYield.join(""), c);
    }
49347
def subgraph(graph, nodes: Iterable[BaseEntity]):
    
    sg = graph.subgraph(nodes)

    # see implementation for .copy()
    result = graph.fresh_copy()
    result.graph.update(sg.graph)

    for node, data in sg.nodes(data=True):
        result.add_node(node, **data)

    result.add_edges_from(
        (u, v, key, datadict.copy())
        for u, v, key, datadict in sg.edges(keys=True, data=True)
    )

    return result
343352
def write(G):
    
    
    # Document root
    grxml = Document()
    if (type(G) == graph):
        grxmlr = grxml.createElement('graph')
    elif (type(G) == digraph ):
        grxmlr = grxml.createElement('digraph')
    elif (type(G) == hypergraph ):
        return write_hypergraph(G)
    else:
        raise InvalidGraphType
    grxml.appendChild(grxmlr)

    # Each node...
    for each_node in G.nodes():
        node = grxml.createElement('node')
        node.setAttribute('id', str(each_node))
        grxmlr.appendChild(node)
        for each_attr in G.node_attributes(each_node):
            attr = grxml.createElement('attribute')
            attr.setAttribute('attr', each_attr[0])
            attr.setAttribute('value', each_attr[1])
            node.appendChild(attr)

    # Each edge...
    for edge_from, edge_to in G.edges():
        edge = grxml.createElement('edge')
        edge.setAttribute('from', str(edge_from))
        edge.setAttribute('to', str(edge_to))
        edge.setAttribute('wt', str(G.edge_weight((edge_from, edge_to))))
        edge.setAttribute('label', str(G.edge_label((edge_from, edge_to))))
        grxmlr.appendChild(edge)
        for attr_name, attr_value in G.edge_attributes((edge_from, edge_to)):
            attr = grxml.createElement('attribute')
            attr.setAttribute('attr', attr_name)
            attr.setAttribute('value', attr_value)
            edge.appendChild(attr)

    return grxml.toprettyxml()
1266598
def _create_complete_graph(node_ids):
    
    g = nx.Graph()
    g.add_nodes_from(node_ids)
    for (i, j) in combinations(node_ids, 2):
        g.add_edge(i, j)
    return g
577510
def toposorted(nodes, edges):
    
    incoming = defaultdict(set)
    outgoing = defaultdict(set)
    for edge in edges:
        incoming[edge.to_id].add(edge.from_id)
        outgoing[edge.from_id].add(edge.to_id)

    working_set = list(nodes.values())
    results = []
    while working_set:
        remaining = []
        for node in working_set:
            if incoming[node.id]:
                # node still has incoming edges
                remaining.append(node)
                continue

            results.append(node)
            for child in outgoing[node.id]:
                incoming[child].remove(node.id)

        if len(working_set) == len(remaining):
            raise Exception("Cycle detected")
        working_set = remaining

    return results