Write in dotfile a graph equivalent to those depicted in bubble file
503239
def bubble_to_dot(bblfile:str, dotfile:str=None, render:bool=False,
                  oriented:bool=False):
    """"""
    tree = BubbleTree.from_bubble_file(bblfile, oriented=bool(oriented))
    return tree_to_dot(tree, dotfile, render=render)
1340908
private <T,E extends TypedEdge<T>> void write(
                         Multigraph<T,E> g, File f, Map<T,Color> edgeColors, 
                         boolean useColors, Indexer<String> vertexLabels,
                         boolean useLabels) throws IOException {

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
            docBuilder = dbfac.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            throw new IOError(new IOException(pce));
        }
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement("gexf");
        root.setAttribute("xmlns","http://www.gexf.net/1.2draft");
        root.setAttribute("xmlns:viz", "http://www.gexf.net/1.2draft/viz");
        root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.setAttribute("version","1.2");
        root.setAttribute("xsi:schemaLocation","http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd");
        doc.appendChild(root);

        Element graph = doc.createElement("graph");
        graph.setAttribute("defaultedgetype","undirected");
        root.appendChild(graph);

        Element nodes = doc.createElement("nodes");
        graph.appendChild(nodes);
        Element edges = doc.createElement("edges");
        graph.appendChild(edges);

        IntIterator vIter = g.vertices().iterator();
        while (vIter.hasNext()) {
            int vertex = vIter.next();
            Element node = doc.createElement("node");
            node.setAttribute("id", String.valueOf(vertex));
            if (useLabels) 
                node.setAttribute("label", vertexLabels.lookup(vertex));
            else
                node.setAttribute("label", String.valueOf(vertex));
            nodes.appendChild(node);
        }

        ColorGenerator cg = null;
        if (useColors)
            cg = new ColorGenerator();

        int edgeId = 0;
        for (E e : g.edges()) {
            Element edge = doc.createElement("edge");
            edges.appendChild(edge);
            edge.setAttribute("id", "" + (edgeId++));
            edge.setAttribute("source", String.valueOf(e.from()));
            edge.setAttribute("target", String.valueOf(e.to()));
            edge.setAttribute("label", String.valueOf(e.edgeType()));
            if (useColors) {
                Element cEdge = doc.createElement("viz:color");
                edge.appendChild(cEdge);
                Color c = edgeColors.get(e.edgeType());
                if (c == null) {
                    c = cg.next();
                    edgeColors.put(e.edgeType(), c);
                }
                cEdge.setAttribute("r", String.valueOf(c.getRed()));
                cEdge.setAttribute("g", String.valueOf(c.getGreen()));
                cEdge.setAttribute("b", String.valueOf(c.getBlue()));
            }
        }

        // Set up a transformer
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "2");
        
            // Create string from xml tree
            BufferedOutputStream bos = 
                new BufferedOutputStream(new FileOutputStream(f));
            StreamResult result = new StreamResult(bos);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            bos.close();         
        } catch (TransformerException te) {
            throw new IOError(new IOException(te));
        }
    }
172517
def dot_format(out, graph, name="digraph"):
    """"""

    out.write("digraph %s {\n" % name)
    for step, deps in each_step(graph):
        for dep in deps:
            out.write("  \"%s\" -> \"%s\";\n" % (step, dep))

    out.write("}\n")
865586
def get_dot(stop=True):
    
    defaults = []
    nodes    = []
    edges    = []


    # define default attributes
    for comp, comp_attr in graph_attributes.items():
        attr = ', '.join( '%s = "%s"' % (attr, val)
                         for attr, val in comp_attr.items() )
        defaults.append( '\t%(comp)s [ %(attr)s ];\n' % locals() )

    # define nodes
    for func, hits in func_count.items():
        calls_frac, total_time_frac, total_time = _frac_calculation(func, hits)
        col = settings['node_colour'](calls_frac, total_time_frac)
        attribs = ['%s="%s"' % a for a in settings['node_attributes'].items()]
        node_str = '"%s" [%s];' % (func, ', '.join(attribs))
        nodes.append( node_str % locals() )

    # define edges
    for fr_key, fr_val in call_dict.items():
        if not fr_key: continue
        for to_key, to_val in fr_val.items():
            calls_frac, total_time_frac, totla_time = \
                _frac_calculation(to_key, to_val)
            col = settings['edge_colour'](calls_frac, total_time_frac)
            edge = '[ color = "%s", label="%s" ]' % (col, to_val)
            edges.append('"%s"->"%s" %s;' % (fr_key, to_key, edge))

    defaults = '\n\t'.join( defaults )
    nodes    = '\n\t'.join( nodes )
    edges    = '\n\t'.join( edges )

    dot_fmt = ("digraph G {\n"
               "	%(defaults)s\n\n"
               "	%(nodes)s\n\n"
               "	%(edges)s\n}\n"
              )
    return dot_fmt % locals()
247481
def _print_dot(targets, components, tasks):
    
    print("Warning: dot option is deprecated.  Use graph instead.", file=sys.stderr)
    _print_graph(targets, components, tasks)
1274040
def generate_graphs(data_frames, hardware_info, steps, outdir,
                    verbose=False):
    """"""
    _setup_matplotlib()
    # Hash of hosts containing (data, hardware, steps) tuple
    collectl_info = collections.defaultdict(dict)

    for host, data_frame in data_frames.items():
        if verbose:
            print('Generating CPU graph for {}...'.format(host))
        graph, data_cpu = graph_cpu(data_frame, steps, hardware_info[host]['num_cpus'])

        graph.get_figure().savefig(
            os.path.join(outdir, '{}_cpu.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        ifaces = set([series.split('_')[0]
                      for series in data_frame.keys()
                      if series.startswith(('eth', 'ib'))])

        if verbose:
            print('Generating network graphs for {}...'.format(host))
        graph, data_net_bytes = graph_net_bytes(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_bytes.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        graph, data_net_pkts = graph_net_pkts(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_pkts.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating memory graph for {}...'.format(host))
        graph, data_mem = graph_memory(data_frame, steps, hardware_info[host]["memory"])
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_memory.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating storage I/O graph for {}...'.format(host))
        drives = set([
            series.split('_')[0]
            for series in data_frame.keys()
            if series.startswith(('sd', 'vd', 'hd', 'xvd'))
        ])
        graph, data_disk = graph_disk_io(data_frame, steps, drives)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_disk_io.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        print('Serializing output to pickle object for node {}...'.format(host))
        # "Clean" dataframes ready to be plotted
        collectl_info[host] = { "hardware": hardware_info,
                                "steps": steps, "cpu": data_cpu, "mem": data_mem,
                                "disk": data_disk, "net_bytes": data_net_bytes,
                                "net_pkts": data_net_pkts
                              }
    return collectl_info
684839
def draw(graph, fname):
    """"""
    ag = networkx.nx_agraph.to_agraph(graph)
    ag.draw(fname, prog='dot')
787529
def get_dotstr(self):
        """"""
        dotobj = self.gosubdagplot.get_pydot_graph() # pydot.Dot
        dotstr = dotobj.create_dot()
        return dotstr
1056388
def dotter():
    """"""
    # Use a global variable
    global globalcount
    if globalcount <= 80:
        sys.stdout.write('.')
        globalcount += 1
    else:
        sys.stdout.write('\n.')
        globalcount = 1
66945
def _write_to_graph(self):
        """"""
        traces = []
        for byte_code, trace_data in self.coverage.items():
            traces += [list(trace_data.keys()), list(trace_data.values()), "r--"]

        plt.plot(*traces)
        plt.axis([0, self.end - self.begin, 0, 100])
        plt.xlabel("Duration (seconds)")
        plt.ylabel("Coverage (percentage)")

        plt.savefig("{}.png".format(self.name))
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")
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")
1001435
def write(graph, fileformat=None, filename=None):
        

        filewriter = None
        if fileformat is None:
            fileformat = 'turtle'
        if filename is not None:

            with open(filename, 'wb') as filewriter:
                LOG.info("Writing triples in %s to %s", fileformat, filename)
                # rdflib serialize
                graph.serialize(filewriter, format=fileformat)
        else:
            print(graph.serialize(fileformat).decode())
        return
945457
function saveGraphSON(graph, filename, callback) {
        var FileOutputStream = Tinkerpop.autoImport('FileOutputStream');
        var stream = new FileOutputStream(filename);
        return Tinkerpop.GraphSONWriter.buildP()
            .then(function (builder) {
            return _newGraphSONMapper()
                .then(function (mapper) { return builder.mapperP(mapper); });
        })
            .then(function (builder) { return builder.createP(); })
            .then(function (writer) { return writer.writeGraphP(stream, graph); })
            .then(function () { return graph; })
            .nodeify(callback);
    }
744596
def output(self, filename):
        
        if filename == '':
            filename = 'contracts.dot'
        if not filename.endswith('.dot'):
            filename += ".dot"
        info = 'Inheritance Graph: ' + filename
        self.info(info)
        with open(filename, 'w', encoding='utf8') as f:
            f.write('digraph "" {\n')
            for c in self.contracts:
                f.write(self._summary(c))
            f.write('}')
277356
def write(self, file_or_filename, prog=None, format='xdot'):
        
        if prog is None:
            file = super(DotWriter, self).write(file_or_filename)
        else:
            buf = StringIO.StringIO()
            super(DotWriter, self).write(buf)
            buf.seek(0)
            data = self.create(buf.getvalue(), prog, format)

            if isinstance(file_or_filename, basestring):
                file = None
                try:
                    file = open(file_or_filename, "wb")
                except:
                    logger.error("Error opening %s." % file_or_filename)
                finally:
                    if file is not None:
                        file.write(data)
                        file.close()
            else:
                file = file_or_filename
                file.write(data)

        return file
169181
def save_dot(self, file_name=None):
        '''
        
        '''

        if not file_name:
            warnings.warn(DeprecationWarning, "always pass a file_name")
            file_name = self.temp_dot

        fp   = open(file_name, "w")
        try:
            for chunk in self.iterdot():
                fp.write(chunk)
        finally:
            fp.close()