Outputs the graph using the graphviz "dot" format.
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")
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
1040718
def print_graphviz(dump_output):
    
    if hasattr(dump_output, 'encode'):
        print(dump_output)
    else:
        with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream:
            bytestream.write(dump_output)
1116546
def graph_dot(self):
        
        default_graphviz_template = """
digraph role_dependencies {
        size="%size"
        dpi=%dpi
        ratio="fill"
        landscape=false
        rankdir="BT";

        node [shape = "box",
              style = "rounded,filled",
              fillcolor = "lightgrey",
              fontsize = 20];

        edge [style = "dashed",
              dir = "forward",
              penwidth = 1.5];

%roles_list

%dependencies
}
"""

        roles_list = ""
        edges = ""

        # remove the darkest and brightest colors, still have 100+ colors
        adjusted_colors = c.X11_COLORS[125:-325]
        random.shuffle(adjusted_colors)
        backup_colors = adjusted_colors[:]

        for role, fields in sorted(self.report["roles"].iteritems()):
            name = utils.normalize_role(role, self.config)
            color_length = len(adjusted_colors) - 1

            # reset the colors if we run out
            if color_length == 0:
                adjusted_colors = backup_colors[:]
                color_length = len(adjusted_colors) - 1

            random_index = random.randint(1, color_length)
            roles_list += "        role_{0}              [label = \"{1}\"]\n" \
                          .format(re.sub(r'[.-/]', '_', name), name)

            edge = '\n        edge [color = "{0}"];\n' \
                   .format(adjusted_colors[random_index])
            del adjusted_colors[random_index]

            if fields["dependencies"]:
                dependencies = ""

                for dependency in sorted(fields["dependencies"]):
                    dependency_name = utils.role_name(dependency)
                    dependencies += "        role_{0} -> role_{1}\n".format(
                        re.sub(r'[.-/]', '_', name),
                        re.sub(r'[.-/]', '_',
                               utils.normalize_role(dependency_name,
                                                    self.config)
                               )
                    )

                edges += "{0}{1}\n".format(edge, dependencies)

        graphviz_template = default_graphviz_template.replace("%roles_list",
                                                              roles_list)
        graphviz_template = graphviz_template.replace("%dependencies",
                                                      edges)
        graphviz_template = graphviz_template.replace("%size",
                                                      self.size)
        graphviz_template = graphviz_template.replace("%dpi",
                                                      str(self.dpi))

        if self.out_file:
            utils.string_to_file(self.out_file, graphviz_template)
        else:
            print graphviz_template
247481
def _print_dot(targets, components, tasks):
    
    print("Warning: dot option is deprecated.  Use graph instead.", file=sys.stderr)
    _print_graph(targets, components, tasks)
744348
def dump_graph(self):
        
        # we have to hold the lock for the entire dump, if other threads modify
        # self.relations or any cache entry's referenced_by during iteration
        # it's a runtime error!
        with self.lock:
            return {
                dot_separated(k): v.dump_graph_entry()
                for k, v in self.relations.items()
            }
728774
def write_dot(build_context, conf: Config, out_f):
    """"""
    not_buildenv_targets = get_not_buildenv_targets(build_context)
    prebuilt_targets = get_prebuilt_targets(build_context)
    out_f.write('strict digraph  {\n')
    for node in build_context.target_graph.nodes:
        if conf.show_buildenv_deps or node in not_buildenv_targets:
            cached = node in prebuilt_targets
            fillcolor = 'fillcolor="grey",style=filled' if cached else ''
            color = TARGETS_COLORS.get(
                build_context.targets[node].builder_name, 'black')
            out_f.write('  "{}" [color="{}",{}];\n'.format(node, color,
                                                           fillcolor))
    out_f.writelines('  "{}" -> "{}";\n'.format(u, v)
                     for u, v in build_context.target_graph.edges
                     if conf.show_buildenv_deps or
                     (u in not_buildenv_targets and v in not_buildenv_targets))
    out_f.write('}\n\n')
1363033
def dot(self, p_print_labels=True):
        
        out = 'digraph g {\n'

        for from_node, neighbors in sorted(self._edges.items()):
            out += "  {}\n".format(from_node)

            for neighbor in sorted(neighbors):
                out += "  {} -> {}".format(from_node, neighbor)

                edge_id = self.edge_id(from_node, neighbor)
                if edge_id and p_print_labels:
                    out += ' [label="{}"]'.format(edge_id)

                out += "\n"

        out += '}\n'
        return out
360143
def make_dot_graph(filename, format='png', tool='dot', stop=True):
    
    if stop:
        stop_trace()

    dot_data = get_dot()

    # normalize filename
    regex_user_expand = re.compile('\A~')
    if regex_user_expand.match(filename):
        filename = os.path.expanduser(filename)
    else:
        filename = os.path.expandvars(filename)  # expand, just in case

    if format == 'dot':
        f = open(filename, 'w')
        f.write(dot_data)
        f.close()

    else:
        # create a temporary file to be used for the dot data
        fd, tempname = tempfile.mkstemp()
        with os.fdopen(fd, 'w') as f:
            f.write(dot_data)

        cmd = '%(tool)s -T%(format)s -o%(filename)s %(tempname)s' % locals()
        try:
            ret = os.system(cmd)
            if ret:
                raise PyCallGraphException( \
                    'The command "%(cmd)s" failed with error ' \
                    'code %(ret)i.' % locals())
        finally:
            os.unlink(tempname)
558826
def _make_graph(bsname, version=None, data_dir=None):
    '''
    
    '''

    if not graphviz_avail:
        raise RuntimeError("graphviz package is not installed")

    data_dir = api.fix_data_dir(data_dir)

    md = api._get_basis_metadata(bsname, data_dir)

    if version is None:
        version = md['latest_version']
    else:
        version = str(version)

    if not version in md['versions']:
        raise RuntimeError("Version {} of {} doesn't exist".format(version, bsname))

    gr = graphviz.Digraph(comment='Basis Set Graph: ' + bsname)

    # Read the table file
    table_path = os.path.join(data_dir, md['versions'][version]['file_relpath'])
    table_data = fileio.read_json_basis(table_path)

    table_edges = {}
    for el, entry in table_data['elements'].items():
        if entry not in table_edges:
            table_edges[entry] = []
        table_edges[entry].append(el)

    for k, v in table_edges.items():
        gr.edge(bsname, k, label=compact_elements(v))

    # Element file
    for elfile in table_edges.keys():
        element_path = os.path.join(data_dir, elfile)
        element_data = fileio.read_json_basis(element_path)

        element_edges = {}

        for el, components in element_data['elements'].items():
            components = components['components']
            components_str = '\n'.join(components)

            # skip if this element for the table basis doesn't come from this file
            if el not in table_data['elements']:
                continue
            if table_data['elements'][el] != elfile:
                continue

            if components_str not in element_edges:
                element_edges[components_str] = []
            element_edges[components_str].append(el)

        for k, v in element_edges.items():
            if len(v):
                gr.edge(elfile, k, label=compact_elements(v))

    return gr
614400
def write_graph(self, filename):
        
        f = open(filename, 'w')
        f.write(self._get_graphviz_data())
        f.close()
219218
def dot2svg(dot):
    # type: (str) -> str
    
    svg = graphviz.Source(dot).pipe(format='svg').decode('utf8')  # type: str
    # strip doctype and xml declaration
    svg = svg[svg.index('<svg'):]
    return svg
326861
def as_graph(self) -> Digraph:  # pragma: no cover
        """"""
        if Digraph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        dot = Digraph()

        nodes = set()
        queue = [self._root]
        while queue:
            state = queue.pop(0)
            if not state.payload:
                dot.node('n{!s}'.format(state.id), '', {'shape': ('circle' if state else 'doublecircle')})
            else:
                dot.node('n{!s}'.format(state.id), '\n'.join(map(str, state.payload)), {'shape': 'box'})

            for next_state in state.values():
                if next_state.id not in nodes:
                    queue.append(next_state)
                    nodes.add(state.id)

        nodes = set()
        queue = [self._root]
        while queue:
            state = queue.pop(0)
            if state.id in nodes:
                continue
            nodes.add(state.id)

            for (label, other) in state.items():
                dot.edge('n{!s}'.format(state.id), 'n{!s}'.format(other.id), _term_str(label))
                if other.id not in nodes:
                    queue.append(other)

        return dot
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()
697618
def graphviz_dot(sentence, font="Arial", colors=BLUE):
    
    s  = 'digraph sentence {\n'
    s += '\tranksep=0.75;\n'
    s += '\tnodesep=0.15;\n'
    s += '\tnode [penwidth=1, fontname="%s", shape=record, margin=0.1, height=0.35];\n' % font
    s += '\tedge [penwidth=1];\n'
    s += '\t{ rank=same;\n'
    # Create node groups for words, chunks and PNP chunks.
    for w in sentence.words:
        s += '\t\tword%s [label="<f0>%s|<f1>%s"%s];\n' % (w.index, w.string, w.type, _colorize(w, colors))
    for w in sentence.words[:-1]:
        # Invisible edges forces the words into the right order:
        s += '\t\tword%s -> word%s [color=none];\n' % (w.index, w.index+1)
    s += '\t}\n'
    s += '\t{ rank=same;\n'        
    for i, ch in enumerate(sentence.chunks):
        s += '\t\tchunk%s [label="<f0>%s"%s];\n' % (i+1, "-".join([x for x in (
            ch.type, ch.role, str(ch.relation or '')) if x]) or '-', _colorize(ch, colors))
    for i, ch in enumerate(sentence.chunks[:-1]):
        # Invisible edges forces the chunks into the right order:
        s += '\t\tchunk%s -> chunk%s [color=none];\n' % (i+1, i+2)
    s += '}\n'
    s += '\t{ rank=same;\n'
    for i, ch in enumerate(sentence.pnp):
        s += '\t\tpnp%s [label="<f0>PNP"%s];\n' % (i+1, _colorize(ch, colors))
    s += '\t}\n'
    s += '\t{ rank=same;\n S [shape=circle, margin=0.25, penwidth=2]; }\n'
    # Connect words to chunks.
    # Connect chunks to PNP or S.
    for i, ch in enumerate(sentence.chunks):
        for w in ch:
            s += '\tword%s -> chunk%s;\n' % (w.index, i+1)
        if ch.pnp:
            s += '\tchunk%s -> pnp%s;\n' % (i+1, sentence.pnp.index(ch.pnp)+1)
        else:
            s += '\tchunk%s -> S;\n' % (i+1)
        if ch.type == 'VP':
            # Indicate related chunks with a dotted
            for r in ch.related:
                s += '\tchunk%s -> chunk%s [style=dotted, arrowhead=none];\n' % (
                    i+1, sentence.chunks.index(r)+1)
    # Connect PNP to anchor chunk or S.
    for i, ch in enumerate(sentence.pnp):
        if ch.anchor:
            s += '\tpnp%s -> chunk%s;\n' % (i+1, sentence.chunks.index(ch.anchor)+1)
            s += '\tpnp%s -> S [color=none];\n' % (i+1)
        else:
            s += '\tpnp%s -> S;\n' % (i+1)
    s += "}"
    return s
1232730
def make_graph_pygraphviz(self, recs, nodecolor,
                              edgecolor, dpi,
                              draw_parents=True, draw_children=True):
        """"""
        import pygraphviz as pgv

        grph = pgv.AGraph(name="GO tree")

        edgeset = set()
        for rec in recs:
            if draw_parents:
                edgeset.update(rec.get_all_parent_edges())
            if draw_children:
                edgeset.update(rec.get_all_child_edges())

        edgeset = [(self.label_wrap(a), self.label_wrap(b))
                   for (a, b) in edgeset]

        # add nodes explicitly via add_node
        # adding nodes implicitly via add_edge misses nodes
        # without at least one edge
        for rec in recs:
            grph.add_node(self.label_wrap(rec.item_id))

        for src, target in edgeset:
            # default layout in graphviz is top->bottom, so we invert
            # the direction and plot using dir="back"
            grph.add_edge(target, src)

        grph.graph_attr.update(dpi="%d" % dpi)
        grph.node_attr.update(shape="box", style="rounded,filled",
                              fillcolor="beige", color=nodecolor)
        grph.edge_attr.update(shape="normal", color=edgecolor,
                              dir="back", label="is_a")
        # highlight the query terms
        for rec in recs:
            try:
                node = grph.get_node(self.label_wrap(rec.item_id))
                node.attr.update(fillcolor="plum")
            except:
                continue

        return grph
1301617
def to_graphviz(self) -> str:
        
        graph = "digraph finite_state_machine { rankdir=LR; node [fixedsize=true];"
        for origin, dest in self._transitions.items():
            origin = origin.replace(" ", "_")
            for d in dest:
                d = d.replace(" ", "_")
                graph += "{0} -> {1};".format(origin, d)
        graph += "}"
        return graph