Assemble INDRA Statements and return Graphviz graph dot string.
764038
def assemble_graph():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    stmts_json = body.get('statements')
    stmts = stmts_from_json(stmts_json)
    ga = GraphAssembler(stmts)
    model_str = ga.make_model()
    res = {'model': model_str}
    return res
1051869
def assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None):
    
    if verbose:
        print(">>Assembling for multicolor", [e.name for e in multicolor.multicolors.elements()],
              file=verbose_destination)
    for assembly in assemblies:
        v1, v2, (before, after, ex_data) = assembly
        iv1 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v1))
        iv2 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v2))
        kbreak = KBreak(start_edges=[(v1, iv1), (v2, iv2)],
                        result_edges=[(v1, v2), (iv1, iv2)],
                        multicolor=multicolor)
        if verbose:
            print("(", v1.name, ",", iv1.name, ")x(", v2.name, ",", iv2.name, ")", " score=", before - after, sep="",
                  file=verbose_destination)
        graph.apply_kbreak(kbreak=kbreak, merge=True)
17136
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
    

    node_orig = 1

    if directed:
        graph = Dot(graph_type='digraph')
    else:
        graph = Dot(graph_type='graph')

    for row in matrix:
        if not directed:
            skip = matrix.index(row)
            r = row[skip:]
        else:
            skip = 0
            r = row
        node_dest = skip + 1

        for e in r:
            if e:
                graph.add_edge(
                    Edge(
                        node_prefix + node_orig,
                        node_prefix + node_dest))
            node_dest += 1
        node_orig += 1

    return graph
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)
778222
def get_vertex_string(self, i):
        """"""
        number = self.numbers[i]
        if number == 0:
            return Graph.get_vertex_string(self, i)
        else:
            # pad with zeros to make sure that string sort is identical to number sort
            return "%03i" % number
1243715
def to_dot(buffer='')
      buffer << "digraph G {\n"
      buffer << "  graph[#{to_dot_attributes(self.to_h(true))}]\n"
      each_vertex do |v|
        buffer << "  V#{v.index} [#{to_dot_attributes(v.to_h(true))}]\n"
      end
      each_edge do |e|
        buffer << "  V#{e.source.index} -> V#{e.target.index} [#{to_dot_attributes(e.to_h(true))}]\n"
      end
      buffer << "}\n"
    end
1249008
def get_workflow_graph(promise):
    """"""
    workflow = get_workflow(promise)

    dot = Digraph()
    for i, n in workflow.nodes.items():
        dot.node(str(i), label="{0} \n {1}".format(
            n.foo.__name__,
            _format_arg_list(n.bound_args.args)))

    for i in workflow.links:
        for j in workflow.links[i]:
            dot.edge(str(i), str(j[0]), label=str(j[1].name))

    return dot
385550
def packageGraph(self, packagelevel=None):
        """"""
        packages = {}
        for module in self.listModules():
            package_name = self.packageOf(module.modname, packagelevel)
            if package_name not in packages:
                dirname = os.path.dirname(module.filename)
                packages[package_name] = Module(package_name, dirname)
            package = packages[package_name]
            for name in module.imports:
                package_name = self.packageOf(name, packagelevel)
                if package_name != package.modname: # no loops
                    package.imports.add(package_name)
        graph = ModuleGraph()
        graph.modules = packages
        return graph
837789
function _graphToRDF(graph, namer) {
  var rval = [];

  var ids = Object.keys(graph).sort();
  for(var i = 0; i < ids.length; ++i) {
    var id = ids[i];
    var node = graph[id];
    var properties = Object.keys(node).sort();
    for(var pi = 0; pi < properties.length; ++pi) {
      var property = properties[pi];
      var items = node[property];
      if(property === '@type') {
        property = RDF_TYPE;
      }
      else if(_isKeyword(property)) {
        continue;
      }

      for(var ii = 0; ii < items.length; ++ii) {
        var item = items[ii];

        // RDF subject
        var subject = {};
        subject.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
        subject.value = id;

        // RDF predicate
        var predicate = {};
        predicate.type = (property.indexOf('_:') === 0) ? 'blank node' : 'IRI';
        predicate.value = property;

        // convert @list to triples
        if(_isList(item)) {
          _listToRDF(item['@list'], namer, subject, predicate, rval);
        }
        // convert value or node object to triple
        else {
          var object = _objectToRDF(item);
          rval.push({subject: subject, predicate: predicate, object: object});
        }
      }
    }
  }

  return rval;
}
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
1196313
def isa_to_graph(isa: ISA) -> nx.Graph:
    
    return nx.from_edgelist(e.targets for e in isa.edges if not e.dead)
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
588645
def isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA:
    
    all_qubits = list(range(max(graph.nodes) + 1))
    qubits = [Qubit(i, type=oneq_type, dead=i not in graph.nodes) for i in all_qubits]
    edges = [Edge(sorted((a, b)), type=twoq_type, dead=False) for a, b in graph.edges]
    return ISA(qubits, edges)
789117
def read_graph_from_string(txt):
    
    if not txt.startswith('{'):
        return read_dot(txt)  # standard dot format

    def conv(value):
        if isinstance(value, basestring):
            return '"' + value + '"'
        else:
            return value

    # our compacted format
    doc = literal_eval(txt)
    g = digraph()

    for attrs, values in doc.get("nodes", []):
        attrs = [(k, conv(v)) for k, v in attrs]

        for value in values:
            if isinstance(value, basestring):
                node_name = value
                attrs_ = attrs
            else:
                node_name, label = value
                attrs_ = attrs + [("label", conv(label))]

            g.add_node(node_name, attrs=attrs_)

    for attrs, values in doc.get("edges", []):
        attrs_ = [(k, conv(v)) for k, v in attrs]

        for value in values:
            if len(value) == 3:
                edge = value[:2]
                label = value[-1]
            else:
                edge = value
                label = ''

            g.add_edge(edge, label=label, attrs=attrs_)

    return g
476217
def call_graphviz_dot(src, fmt):
    
    try:
        svg = dot(src, T=fmt)
    except OSError as e:  # pragma: nocover
        if e.errno == 2:
            cli.error("""
               cannot find 'dot'

               pydeps calls dot (from graphviz) to create svg diagrams,
               please make sure that the dot executable is available
               on your path.
            """)
        raise
    return svg
394034
def as_graph(self) -> Digraph:  # pragma: no cover
        """"""
        if Digraph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        graph = Digraph()

        subgraphs = [Digraph(graph_attr={'rank': 'same'}), Digraph(graph_attr={'rank': 'same'})]
        nodes = [{}, {}]  # type: List[Dict[Union[TLeft, TRight], str]]
        edges = []  # type: List [Tuple[str, str]]
        node_id = 0
        for (tail_part, tail), head_set in self.items():
            if tail not in nodes[tail_part]:
                name = 'node{:d}'.format(node_id)
                nodes[tail_part][tail] = name
                subgraphs[tail_part].node(name, label=str(tail))
                node_id += 1
            for head_part, head in head_set:
                if head not in nodes[head_part]:
                    name = 'node{:d}'.format(node_id)
                    nodes[head_part][head] = name
                    subgraphs[head_part].node(name, label=str(head))
                    node_id += 1
                edges.append((nodes[tail_part][tail], nodes[head_part][head]))
        graph.subgraph(subgraphs[0])
        graph.subgraph(subgraphs[1])
        for tail_node, head_node in edges:
            graph.edge(tail_node, head_node)
        return graph
758942
def graph_from_dot_file(path):
    

    fd = open(path, 'rb')
    data = fd.read()
    fd.close()

    return graph_from_dot_data(data)