Generate a graphviz compatible graph.
431880
def print_network(self):  # pragma: no cover
        
        edges = set()

        def gen_edges(node):
            nonlocal edges
            name = str(id(node))

            yield '{name} [label="{cls_name}"];'.format(
                name=name,
                cls_name=str(node))

            for child in node.children:
                if (node, child.callback) not in edges:
                    yield ('{parent} -> {child} '
                           '[label="{child_label}"];').format(
                        parent=name,
                        child=str(id(child.node)),
                        child_label=child.callback.__name__)
                    edges.add((node, child.callback))
                yield from gen_edges(child.node)

        return "digraph {\n %s \n}" % ("\n".join(
            gen_edges(self.root_node)))
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)
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
415304
def build_graph(formula):
    '''  '''
    graph = {}

    for clause in formula:
        for (lit, _) in clause:
            for neg in [False, True]:
                graph[(lit, neg)] = []

    for ((a_lit, a_neg), (b_lit, b_neg)) in formula:
        add_edge(graph, (a_lit, a_neg), (b_lit, not b_neg))
        add_edge(graph, (b_lit, b_neg), (a_lit, not a_neg))

    return graph
793801
def _gen_trend_graph(start, end, force_overwrite=False):
    
    filename = graphs.get_trend_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

    query = CPUJob.objects.filter(
        date__range=(start, end)
    )
    query = query.values('date').annotate(Sum('cpu_usage'))
    query = query.order_by('date')

    t_start = start
    t_end = end

    start_str = start.strftime('%Y-%m-%d')
    end_str = end.strftime('%Y-%m-%d')

    fig, ax = plt.subplots(figsize=(6, 4))
    ax.set_xlim(start, end)
    ax.set_title('%s - %s' % (start_str, end_str))
    ax.set_ylabel("CPU Time (hours)")
    ax.set_xlabel("Date")

    locator = mdates.AutoDateLocator()
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
    ax.xaxis.set_minor_locator(mdates.DayLocator())

    data = {}
    x_data = []
    y_data = []

    with open(csv_filename, 'w') as csv_file:
        csv_writer = csv.writer(csv_file)
        for row in query.iterator():
            csv_writer.writerow([
                row['date'], row['cpu_usage__sum'] / 3600.00
            ])

            date = row['date']

            data[date] = row['cpu_usage__sum']

    start = t_start
    end = t_end
    while start <= end:
        total = 0
        if start in data:
            total = data[start]
        x_data.append(start)
        y_data.append(total / 3600.00)
        start = start + datetime.timedelta(days=1)

    del data

    ax.plot(x_data, y_data)

    del x_data
    del y_data

    fig.autofmt_xdate()
    plt.tight_layout()
    plt.savefig(png_filename)
    plt.close()
311914
def _get_pydot_graph(self):
        """"""
        rel = "is_a"
        pydot = self._get_pydot()
        # Initialize empty dag
        dag = pydot.Dot(label=self.title, graph_type='digraph', dpi="{}".format(self.dpi))
        # Initialize nodes
        go2node = self._get_go2pydotnode()
        # Add nodes to graph
        for node in go2node.values():
            dag.add_node(node)
        # Add edges to graph
        rel2col = self.pltvars.rel2col
        for src, tgt in self.godag.get_edges():
            dag.add_edge(pydot.Edge(
                go2node[tgt], go2node[src],
                shape="normal",
                color=rel2col[rel],
                dir="back")) # invert arrow direction for obo dag convention
        return dag
493279
def maybe_with_graph(graph=None, create_if_none=True):
  """"""
  if tf.executing_eagerly():
    yield None
  else:
    if graph is None and create_if_none:
      graph = tf.Graph()

    if graph is None:
      yield None
    else:
      with graph.as_default():
        yield graph
401498
def cx_to_networkx(cx):
    """"""
    graph = networkx.MultiDiGraph()
    for node_entry in get_aspect(cx, 'nodes'):
        id = node_entry['@id']
        attrs = get_attributes(get_aspect(cx, 'nodeAttributes'), id)
        attrs['n'] = node_entry['n']
        graph.add_node(id, **attrs)
    for edge_entry in get_aspect(cx, 'edges'):
        id = edge_entry['@id']
        attrs = get_attributes(get_aspect(cx, 'edgeAttributes'), id)
        attrs['i'] = edge_entry['i']
        graph.add_edge(edge_entry['s'], edge_entry['t'], key=id, **attrs)
    return graph
1100357
def new_graph(self, graph, typ):
        """"""
        graph = self.pack(graph)
        return self.sql('new_graph', graph, typ)
1345779
def output_to_graphviz(file, namer=_graphviz_default_namer, block=None):
    
    print(block_to_graphviz_string(block, namer), file=file)
1366169
def create_layout(graph, graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    graphviz_layout = graphutils.graphviz_layout(graph, prog=graphviz_prog)
    # print('GRAPHIZ LAYOUT:', graphviz_layout)
    layout = {k: (int(x // 10), int(y // 10))
              for k, (x, y) in graphviz_layout.items()}
    # apply an offset for layouts to get all position >= 0
    max_x = max(layout.values(), key=lambda t: t[0])[0]
    min_x = min(layout.values(), key=lambda t: t[0])[0]
    max_y = max(layout.values(), key=lambda t: t[1])[1]
    min_y = min(layout.values(), key=lambda t: t[1])[1]
    offset_x = - min(0, min_x)
    offset_y = - min(0, min_y)
    return {
        node: (offset_x + x, offset_y + y)
        for node, (x, y) in layout.items()
    }
1249936
def build_graph(steps):
    

    graph = Graph()

    for step in steps:
        graph.add_step(step)

    for step in steps:
        for dep in step.requires:
            graph.connect(step.name, dep)

        for parent in step.required_by:
            graph.connect(parent, step.name)

    return graph
1353880
def graph(bare=False, json=False, json_tree=False, reverse=False):
    """"""
    from ..core import do_graph

    do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse)
224076
def render_output_pygraphviz(self, dotdata, **kwargs):
        """"""
        if not HAS_PYGRAPHVIZ:
            raise CommandError("You need to install pygraphviz python module")

        version = pygraphviz.__version__.rstrip("-svn")
        try:
            if tuple(int(v) for v in version.split('.')) < (0, 36):
                # HACK around old/broken AGraph before version 0.36 (ubuntu ships with this old version)
                tmpfile = tempfile.NamedTemporaryFile()
                tmpfile.write(dotdata)
                tmpfile.seek(0)
                dotdata = tmpfile.name
        except ValueError:
            pass

        graph = pygraphviz.AGraph(dotdata)
        graph.layout(prog=kwargs['layout'])
        graph.draw(kwargs['outputfile'])
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
468166
function graphvizualize(data, cb) {
  var cp = exec('dot -Tsvg');

  // buffer stdout
  var buf = '';
  cp.stdout.on('data', function (data) {
    buf += data;
  });
  cp.on('error', function () {});
  cp.on('close', function (code) {
    cb(null, code > 0 ? '' : buf);
  });

  // set dot to stdin
  cp.stdin.end(data);
}
290784
def do_graphviz(self, args, arguments):
        
        filename = arguments['FILENAME']
        if platform.system() == 'Darwin':
            if os.path.isfile(filename):
                os.system("open -a '\''/Applications/Graphviz.app'\'' " + filename)