Create a graph in simple GDF format, suitable for feeding into Gephi,
    or some other graph manipulation and display tool. Setting stop to True
    will stop the current trace.
501821
def make_gdf_graph(filename, stop=True):
    
    if stop:
        stop_trace()

    try:
        f = open(filename, 'w')
        f.write(get_gdf())
    finally:
        if f: f.close()
492066
def create_graph():
  """"""
  # Creates graph from saved graph_def.pb.
  with tf.gfile.FastGFile(os.path.join(
      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')
814074
def run_graphviz(program, code, options=[], format='png'):
    
    import os
    from subprocess import Popen, PIPE

    dot_args = [program] + options + ['-T', format]

    if os.name == 'nt':
        # Avoid opening shell window.
        # * https://github.com/tkf/ipython-hierarchymagic/issues/1
        # * http://stackoverflow.com/a/2935727/727827
        p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=0x08000000)
    else:
        p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
        wentwrong = False

    try:
        # Graphviz may close standard input when an error occurs,
        # resulting in a broken pipe on communicate()
        stdout, stderr = p.communicate(code.encode('utf-8'))
    except (OSError, IOError) as err:
        if err.errno != EPIPE:
            raise
        wentwrong = True
    except IOError as err:
        if err.errno != EINVAL:
            raise
        wentwrong = True

    if wentwrong:
    # in this case, read the standard output and standard error streams
    # directly, to get the error message(s)
        stdout, stderr = p.stdout.read(), p.stderr.read()
        p.wait()

    if p.returncode != 0:
        raise RuntimeError('dot exited with error:\n[stderr]\n{0}'.format(stderr.decode('utf-8')))

    return stdout
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();
        }
    }
882535
def save_graph(symbol: mx.sym.Symbol, filename: str, hide_weights: bool = True):
    
    dot = mx.viz.plot_network(symbol, hide_weights=hide_weights)
    dot.render(filename=filename)
353512
def draw_graph( g, fmt='svg', prg='dot', options={} ):
    
    # Convert RDF to Graphviz
    buf = StringIO()
    rdf2dot( g, buf, options )

    gv_options = options.get('graphviz',[])
    if fmt == 'png':
        gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ]
        metadata = { "width": 5500, "height": 2200, "unconfined" : True }

    #import codecs
    #with codecs.open('/tmp/sparqlkernel-img.dot','w',encoding='utf-8') as f:
    #    f.write( buf.getvalue() )
    
    # Now use Graphviz to generate the graph
    image = run_dot( buf.getvalue(), fmt=fmt, options=gv_options, prg=prg )

    #with open('/tmp/sparqlkernel-img.'+fmt,'w') as f:
    #    f.write( image )

    # Return it
    if fmt == 'png':
        return { 'image/png' : base64.b64encode(image).decode('ascii') }, \
               { "image/png" : metadata }
    elif fmt == 'svg':
        return { 'image/svg+xml' : image.decode('utf-8').replace('<svg','<svg class="unconfined"',1) }, \
               { "unconfined" : True }
556942
def plot(self, vertex_color=None, vertex_size=None, highlight=[],
             edges=None, edge_color=None, edge_width=None,
             indices=False, colorbar=True, limits=None, ax=None,
             title=None, backend=None):
        """
        from pygsp.plotting import _plot_graph
        return _plot_graph(self, vertex_color=vertex_color,
                           vertex_size=vertex_size, highlight=highlight,
                           edges=edges, indices=indices, colorbar=colorbar,
                           edge_color=edge_color, edge_width=edge_width,
                           limits=limits, ax=ax, title=title, backend=backend)
416601
def graph_easy(self):
        
        if not os.path.isfile("/usr/bin/graph-easy"):
            print("Require 'graph-easy': Install with 'slpkg -s sbo "
                  "graph-easy'")
            self.remove_dot()
            raise SystemExit()
        subprocess.call("graph-easy {0}.dot".format(self.image), shell=True)
        self.remove_dot()
        raise SystemExit()
1030086
function makeLineProgram(gl, data, drawTriangles) {
  let lineProgram = lineProgramCache.get(gl)
  if (!lineProgram) {
    var lineVSShader = gl_utils.compile(gl, gl.VERTEX_SHADER, lineVSSrc);
    var lineFSShader = gl_utils.compile(gl, gl.FRAGMENT_SHADER, lineFSSrc);
    lineProgram = gl_utils.link(gl, lineVSShader, lineFSShader);
    lineProgramCache.set(gl, lineProgram);
  }

  var locations = gl_utils.getLocations(gl, lineProgram);

  var lineBuffer = gl.createBuffer();
  var bpe = data.BYTES_PER_ELEMENT;
  var drawType = drawTriangles ? gl.TRIANGLES : gl.LINES;
  gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer)
  gl.bufferData(gl.ARRAY_BUFFER, data.byteLength, gl.STATIC_DRAW);
  gl.bufferSubData(gl.ARRAY_BUFFER, 0, data);

  var api = {
    draw,
    dispose
  }

  return api;

  function dispose() {
    gl.deleteBuffer(lineBuffer);
    gl.deleteProgram(lineProgram);
    lineProgramCache.delete(gl);
  }

  function draw(transform, color, screen) {
    if (data.length === 0) return;

    gl.useProgram(lineProgram);

    gl.uniformMatrix4fv(locations.uniforms.uTransform, false, transform.getArray());
    gl.uniform2f(locations.uniforms.uScreenSize, screen.width, screen.height);
    gl.uniform4f(locations.uniforms.uColor, color.r, color.g, color.b, color.a);

    gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer);
    gl.enableVertexAttribArray(locations.attributes.aPosition)
    // TODO: Avoid buffering, if data hasn't changed?
    gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
    gl.vertexAttribPointer(locations.attributes.aPosition, 2, gl.FLOAT, false, bpe * 2, 0)

    gl.drawArrays(drawType, 0, data.length / 2);
  }
}
571874
function savePrettyGraphSON(graph, filename, callback) {
        var ByteArrayOutputStream = Tinkerpop.autoImport('ByteArrayOutputStream');
        var stream = new ByteArrayOutputStream();
        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 stream.toStringP(); })
            .then(function (ugly) {
            var prettyString = _prettyGraphSONString(ugly);
            var writeFileP = BluePromise.promisify(fs.writeFile);
            return writeFileP(filename, prettyString);
        })
            .then(function () { return graph; })
            .nodeify(callback);
    }
1078093
def _create_graphical_report(inputfile, pwm, background, closest_match, outdir, stats, best_id=None):
    """"""
    if best_id is None:
        best_id = {}

    logger.debug("Creating graphical report")
    
    class ReportMotif(object):
        """Placeholder for motif stats."""
        pass

    config = MotifConfig()
    
    imgdir = os.path.join(outdir, "images")
    if not os.path.exists(imgdir):
        os.mkdir(imgdir)
    
    motifs = read_motifs(pwm, fmt="pwm")
    
    roc_img_file = "%s_roc.%s"

    dbpwm = config.get_default_params()["motif_db"]
    pwmdir = config.get_motif_dir()

    dbmotifs = read_motifs(os.path.join(pwmdir, dbpwm), as_dict=True)
    
    report_motifs = []
    for motif in motifs:
        
        rm = ReportMotif()
        rm.id = motif.id
        rm.id_href = {"href": "#%s" % motif.id}
        rm.id_name = {"name": motif.id}
        rm.img = {"src":  os.path.join("images", "%s.png" % motif.id)}
        motif.to_img(os.path.join(outdir, "images/{}.png".format(motif.id)), fmt="PNG")
        
        # TODO: fix best ID
        rm.best = "Gimme"#best_id[motif.id]

        rm.consensus = motif.to_consensus()
        rm.stars = int(np.mean(
                [stats[str(motif)][bg].get("stars", 0) for bg in background]
                ) + 0.5)

        rm.bg = {}
        for bg in background:
            rm.bg[bg] = {}
            this_stats = stats.get(str(motif), {}).get(bg)
            # TODO: fix these stats
            rm.bg[bg]["e"] = "%0.2f" % this_stats.get("enr_at_fpr", 1.0)
            rm.bg[bg]["p"] = "%0.2f" % this_stats.get("phyper_at_fpr", 1.0)
            rm.bg[bg]["auc"] = "%0.3f" % this_stats.get("roc_auc", 0.5)
            rm.bg[bg]["mncp"] = "%0.3f" % this_stats.get("mncp", 1.0)
            rm.bg[bg]["roc_img"] = {"src": "images/" + os.path.basename(roc_img_file % (motif.id, bg)) + ".png"}
            rm.bg[bg][u"roc_img_link"] = {u"href": "images/" + os.path.basename(roc_img_file % (motif.id, bg)) + ".png"}

        rm.histogram_img = {"data":"images/%s_histogram.svg" % motif.id}
        rm.histogram_link= {"href":"images/%s_histogram.svg" % motif.id}
        
        match_id = closest_match[motif.id][0]
        dbmotifs[match_id].to_img(os.path.join(outdir, "images/{}.png".format(match_id)), fmt="PNG")
    
        rm.match_img = {"src":  "images/{}.png".format(match_id)}
        rm.match_id = closest_match[motif.id][0]
        rm.match_pval = "%0.2e" % closest_match[motif.id][1][-1]

        report_motifs.append(rm)
    
    total_report = os.path.join(outdir, "motif_report.html")

    star_img = os.path.join(config.get_template_dir(), "star.png")
    shutil.copyfile(star_img, os.path.join(outdir, "images", "star.png"))

    env = jinja2.Environment(loader=jinja2.FileSystemLoader([config.get_template_dir()]))
    template = env.get_template("report_template.jinja.html")
    # TODO: title
    result = template.render(
                    motifs=report_motifs, 
                    inputfile=inputfile, 
                    date=datetime.today().strftime("%d/%m/%Y"), 
                    version=__version__,
                    bg_types=list(background.keys()))

    with open(total_report, "wb") as f:
        f.write(result.encode('utf-8'))
1150609
def save_graph(graphdef):
    ''''''
    if graphdef.filename is None:
        if 'HOME' in os.environ:
            dname = os.path.join(os.environ['HOME'], '.mavproxy')
            mp_util.mkdir_p(dname)
            graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        else:
            graphdef.filename = 'mavgraphs.xml'
    if graphdef.filename is None:
        mestate.console.writeln("No file to save graph to", fg='red')
        return
    graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True)
    found_name = False
    for i in range(len(graphs)):
        if graphs[i].name == graphdef.name:
            graphs[i] = graphdef
            found_name = True
            break
    if not found_name:
        graphs.append(graphdef)
    mestate.console.writeln("Saving %u graphs to %s" % (len(graphs), graphdef.filename))
    f = open(graphdef.filename, "w")
    f.write("<graphs>\n\n")
    for g in graphs:
        f.write(" <graph name='%s'>\n" % g.name.strip())
        if g.description is None:
            g.description = ''
        f.write("  <description>%s</description>\n" % g.description.strip())
        for e in g.expressions:
            f.write("  <expression>%s</expression>\n" % e.strip())
        f.write(" </graph>\n\n")
    f.write("</graphs>\n")
    f.close()
707088
def _make_graph(self, max_insert):
        ''''''
        if len(self.partial_links) != 0:
            raise Error('Error in _make_graph(). Cannot continue because there are partial links')
        
        self.contig_links = {}
        for key in self.links:
            for l in self.links[key]:
                insert_size = l.insert_size()
                if insert_size <= max_insert:
                    if key not in self.contig_links:
                        self.contig_links[key] = {}
                    dirs = ''.join(l.dirs)
                    self.contig_links[key][dirs] = self.contig_links[key].get(dirs, 0) + 1
1014654
def display_workflows(prefix, **kwargs):
    
    from IPython.display import display, Markdown

    def create_svg(name, workflow):
        """Create an SVG file with rendered graph from a workflow."""
        name = name.replace('_', '-')
        filename = '{}-{}.svg'.format(prefix, name)
        dot = get_workflow_graph(workflow)
        dot.attr('graph', bgcolor='transparent')
        with open(filename, 'bw') as file:
            file.write(dot.pipe(format='svg'))
        return name, filename

    svg_files = {name: svg for name, svg in
                 (create_svg(name, workflow)
                  for name, workflow in kwargs.items())}

    markdown_table = \
        '| ' + ' | '.join(svg_files.keys()) + ' |\n' + \
        '| ' + ' | '.join('---' for _ in svg_files) + ' |\n' + \
        '| ' + ' | '.join('![workflow {}]({})'.format(name, svg)
                          for name, svg in svg_files.items()) + ' |'
    display(Markdown(markdown_table))
1219641
def write_to_graphic_file (fmt='png', dotfile='graph', params = {})
      src = dotfile + ".dot"
      dot = dotfile + "." + fmt

      File.open(src, 'w') do |f|
        f << self.to_dot_graph(params).to_s << "\n"
      end

      system( "dot -T#{fmt} -o #{dot} #{src}" )
      dot
    end
369714
def _gen_institute_graph(start, end, force_overwrite=False):
    
    filename = graphs.get_institute_graph_filename(start, end)
    csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv')
    png_filename = os.path.join(GRAPH_ROOT, filename + '.png')

    _check_directory_exists(csv_filename)
    _check_directory_exists(png_filename)

    if not settings.GRAPH_DEBUG or force_overwrite:
        if os.path.exists(csv_filename):
            if os.path.exists(png_filename):
                return

    institute_list = Institute.active.all()

    plt.subplots(figsize=(4, 4))

    data = []
    labels = []

    total = 0
    with open(csv_filename, 'w') as csv_file:
        csv_writer = csv.writer(csv_file)
        for institute in institute_list.iterator():
            hours, jobs = usage.get_institute_usage(institute, start, end)
            total = total + int(hours)
            if hours > 0:
                csv_writer.writerow([institute.name, hours, jobs])
                data.append(hours)
                labels.append(institute.name)

        mcu = usage.get_machine_category_usage(start, end)
        hours = int(mcu.available_time - total)
        csv_writer.writerow(["unused", hours])
        data.append(hours)
        labels.append('Unused')

    plt.pie(data, labels=labels, autopct='%1.1f%%', shadow=True)
    plt.tight_layout()
    plt.savefig(png_filename)
    plt.close()
1350850
def save_graph(graphdef):
    ''''''
    if graphdef.filename is None:
        if 'HOME' in os.environ:
            dname = os.path.join(os.environ['HOME'], '.mavproxy')
            if os.path.exists(dname):
                mp_util.mkdir_p(dname)
                graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        elif 'LOCALAPPDATA' in os.environ:
            dname = os.path.join(os.environ['LOCALAPPDATA'], 'MAVProxy')
            if os.path.exists(dname):
                mp_util.mkdir_p(dname)
                graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        else:
            graphdef.filename = 'mavgraphs.xml'
    if graphdef.filename is None:
        print("No file to save graph to")
        return
    try:
        graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True)
    except Exception:
        graphs = []
    found_name = False
    for i in range(len(graphs)):
        if graphs[i].name == graphdef.name:
            graphs[i] = graphdef
            found_name = True
            break
    if not found_name:
        graphs.append(graphdef)
    pipe_console_input.send("Saving %u graphs to %s" % (len(graphs), graphdef.filename))
    f = open(graphdef.filename, "w")
    f.write("<graphs>\n\n")
    for g in graphs:
        f.write(" <graph name='%s'>\n" % g.name.strip())
        if g.description is None:
            g.description = ''
        f.write("  <description>%s</description>\n" % g.description.strip())
        for e in g.expressions:
            f.write("  <expression>%s</expression>\n" % e.strip())
        f.write(" </graph>\n\n")
    f.write("</graphs>\n")
    f.close()