Dumps the workflow as a graphviz graph.

Available options:

* graph: The default options for the whole graph
* node: The default options for nodes (places)
* edge: The default options for edges
356741
public function dump(string $initialPlaces, Graph $graph, array $options = array())
    {
        $places = $this->findPlaces($initialPlaces, $graph);
        $edges = $this->findEdges($graph);

        $options = array_replace_recursive(self::$defaultOptions, $options);

        return $this->startDot($options)
            .$this->addPlaces($places)
            .$this->addEdges($edges)
            .$this->endDot()
        ;
    }
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
968030
def generate_graphs(data, name, results_dir):
    
    graphs.resp_graph_raw(data['raw'], name + '_response_times.svg', results_dir)
    graphs.resp_graph(data['compiled'], name + '_response_times_intervals.svg', results_dir)
    graphs.tp_graph(data['compiled'], name + '_throughput.svg', results_dir)
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)
836521
def _gen_prov(self):
        
        # Export worfklow graph to node-link data format
        wf_dict = nx_json.node_link_data(self.workflow._graph)
        # Replace references to Node objects with the node's provenance
        # information and convert to a dict organised by node name to allow it
        # to be compared more easily. Also change link node-references from
        # node index to node ID so it is not dependent on the order the nodes
        # are written to the dictionary (which for Python < 3.7 is guaranteed
        # to be the same between identical runs)
        for link in wf_dict['links']:
            if int(networkx_version.split('.')[0]) < 2:  # @UndefinedVariable
                link['source'] = wf_dict['nodes'][link['source']]['id'].name
                link['target'] = wf_dict['nodes'][link['target']]['id'].name
            else:
                link['source'] = link['source'].name
                link['target'] = link['target'].name
        wf_dict['nodes'] = {n['id'].name: n['id'].prov
                            for n in wf_dict['nodes']}
        # Roundtrip to JSON to convert any tuples into lists so dictionaries
        # can be compared directly
        wf_dict = json.loads(json.dumps(wf_dict))
        dependency_versions = {d: extract_package_version(d)
                               for d in ARCANA_DEPENDENCIES}
        pkg_versions = {'arcana': __version__}
        pkg_versions.update((k, v) for k, v in dependency_versions.items()
                            if v is not None)
        prov = {
            '__prov_version__': PROVENANCE_VERSION,
            'name': self.name,
            'workflow': wf_dict,
            'study': self.study.prov,
            'pkg_versions': pkg_versions,
            'python_version': sys.version,
            'joined_ids': self._joined_ids()}
        return prov
931957
def graph_repo(repo_url, output_loc, format='graphml'):  
  
  log = logging.getLogger("graphgit")
  # repo type
  local_repo = os.path.isabs(repo_url)
  # repo name
  repo_name = repo_url[repo_url.rfind('/')+1:repo_url.rfind('.git')] \
    if not local_repo else repo_url[repo_url.rfind(os.sep)+1:]
  log.info ("Processing git repository: %s" % repo_name)
  # repo location
  repo_loc = os.path.join(constants.REPO_DOWNLOAD_LOCATION, repo_name) \
    if not local_repo else repo_url
  # initialize repo
  repo = None
  gitt = git.Git()
  try:
    # check if repo is already cloned
    # if local repo exists, assign
    repo = git.Repo(repo_loc, odbt=git.GitCmdObjectDB)    
    log.info( "Repository already cloned... Going ahead and using it..." )
    # TODO: check if repo is dirty and if so, update
  except git.exc.NoSuchPathError:
    # local repo doesn't exist. clone
    try:
      if local_repo:
        raise Exception
      log.info( "Cloning repository... this might take some time, please wait !" )
      gitt.clone(repo_url, repo_loc)
      log.info( "Git clone completed..." )  
      repo = git.Repo(repo_loc, odbt=git.GitCmdObjectDB)
    except:
      log.error( "Could not obtain repository: %s !" % repo_url )
      sys.exit(1)
    
  if repo is None:
    log.error( "Could not obtain repository: %s !" % repo_url )
    sys.exit(1)

  # create a graph for the repo
  G = nx.DiGraph()
  # root node
  G.add_node(repo_name, type=constants.NODE_TYPE_VALS['REPOSITORY'])
  # branches & commits
  for branch in repo.branches:
    log.debug ("Processing branch %s" % branch)
    G.add_node(branch, type=constants.NODE_TYPE_VALS['BRANCH'])
    G.add_edge(repo_name, branch, 
      label=constants.EDGE_LABEL_VALS['REPOSITORY_BRANCH'])
    for commit in repo.iter_commits(branch):
      try:
        author = safe_str(commit.author)
        ts = commit.committed_date
        sha = safe_str(commit)
        log.debug ("%s> %s --[commit]--> %s" % (branch, author, sha))
        G.add_node(author, type=constants.NODE_TYPE_VALS['PERSON'])
        G.add_node(sha, ts=ts,
          type=constants.NODE_TYPE_VALS['COMMIT'])
        G.add_edge(author, sha, 
          label=constants.EDGE_LABEL_VALS['PERSON_COMMIT'])
        G.add_edge(branch, sha, 
          label=constants.EDGE_LABEL_VALS['BRANCH_COMMIT'])
      except LookupError:
        log.warning('Could not process %s !' % commit)      
        continue

  log.info( "Graph built ! saving..." )

  # save graph
  output_file_name = '%s.%s' % (repo_name, format)
  output_file_loc = os.path.join(output_loc, output_file_name)
  if format == 'graphml':
    nx.write_graphml(G, output_file_loc, encoding='utf-8')
  elif format == 'gexf':
    nx.write_gexf(G, output_file_loc, encoding='utf-8')
  else:
    log.error( "Invalid output format: %s !" % format )
    sys.exit(1)

  log.info( "Saved to %s !" % output_file_loc )
346468
def _store_graph_parts(self, graph: BELGraph, use_tqdm: bool = False) -> Tuple[List[Node], List[Edge]]:
        
        log.debug('inserting %s into edge store', graph)
        log.debug('building node models')
        node_model_build_start = time.time()

        nodes = list(graph)
        if use_tqdm:
            nodes = tqdm(nodes, total=graph.number_of_nodes(), desc='nodes')

        node_model = {}
        for node in nodes:
            namespace = node.get(NAMESPACE)

            if graph.skip_storing_namespace(namespace):
                continue  # already know this node won't be cached

            node_object = self.get_or_create_node(graph, node)

            if node_object is None:
                log.warning('can not add node %s', node)
                continue

            node_model[node] = node_object

        node_models = list(node_model.values())
        log.debug('built %d node models in %.2f seconds', len(node_models), time.time() - node_model_build_start)

        node_model_commit_start = time.time()
        self.session.add_all(node_models)
        self.session.commit()
        log.debug('stored %d node models in %.2f seconds', len(node_models), time.time() - node_model_commit_start)

        log.debug('building edge models')
        edge_model_build_start = time.time()

        edges = graph.edges(keys=True, data=True)
        if use_tqdm:
            edges = tqdm(edges, total=graph.number_of_edges(), desc='edges')

        edge_models = list(self._get_edge_models(graph, node_model, edges))

        log.debug('built %d edge models in %.2f seconds', len(edge_models), time.time() - edge_model_build_start)

        edge_model_commit_start = time.time()
        self.session.add_all(edge_models)
        self.session.commit()
        log.debug('stored %d edge models in %.2f seconds', len(edge_models), time.time() - edge_model_commit_start)

        return node_models, edge_models
628525
def graph_save(permanent: false, &block)
      if block
        Tempfile.open{|tmp|
          graph(output: tmp)
          tmp.seek(0)
          block.(tmp)
        }
      else
        tmp = Tempfile.open
        graph(output: tmp).tap{|t|t.seek(0)}
      end
    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)
288212
def dump_graph(node):
    """"""
    
    def _dump(node, level):
        print("  " * level + "- " + str(node))
        for child in node.children:
            _dump(child, level + 1)
    
    _dump(node, 0)
529242
private function collectTransitions()
	{
		$nlEdges = $this->_xp->query('//ns:edge');
		if ($nlEdges->length == 0) {
			throw new WorkflowException("no edge could be found in this workflow");
		}

		$result = [];
		for ($i = 0; $i < $nlEdges->length; $i ++) {
			$currentNode = $nlEdges->item($i);

			$source = trim($this->_xp->query("@source", $currentNode)->item(0)->value);
			$target = trim($this->_xp->query("@target", $currentNode)->item(0)->value);

			if (! isset($result[$source]) || ! isset($result[$source][$target])) {
				$result[$source][$target] = [];
			}
		}
		return $result;
	}
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
835827
def _export_graph(self):
        
        for brain_name in self.trainers.keys():
            self.trainers[brain_name].export_model()
234951
def save_graph_to_file(graph_file_name, module_spec, class_count):
  """"""
  sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
  graph = sess.graph

  output_graph_def = tf.graph_util.convert_variables_to_constants(
      sess, graph.as_graph_def(), [FLAGS.final_tensor_name])

  with tf.gfile.GFile(graph_file_name, 'wb') as f:
    f.write(output_graph_def.SerializeToString())
468817
def to_graphml(graph: BELGraph, path: Union[str, BinaryIO]) -> None:
    
    rv = nx.MultiDiGraph()

    for node in graph:
        rv.add_node(node.as_bel(), function=node.function)

    for u, v, key, edge_data in graph.edges(data=True, keys=True):
        rv.add_edge(
            u.as_bel(),
            v.as_bel(),
            interaction=edge_data[RELATION],
            bel=graph.edge_to_bel(u, v, edge_data),
            key=key,
        )

    nx.write_graphml(rv, path)
272190
def out_edges(self, node):
        
        try:
            return list(self.nodes[node][1])
        except KeyError:
            raise GraphError('Invalid node %s' % node)

        return None
746491
def dump(args):
    """"""
    if len(args) != 1:
        log.error('One target required.')
        app.quit(1)

    try:
        bb = Butcher()
        bb.load_graph(args[0])
    except error.BrokenGraph as lolno:
        log.fatal(lolno)
        app.quit(1)
    print "Nodes:"
    pprint.pprint(bb.graph.node)
    print "Edges:"
    pprint.pprint(bb.graph.edge)