Create a DOT graph file of the files included in a basis set
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
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
412427
def polydata_fromfile(f, self):
    """"""
    points = []
    data = dict(vertices=[], lines=[], polygons=[], triangle_strips=[])
    l = common._getline(f).decode('ascii')
    k,n,datatype = [s.strip().lower() for s in l.split(' ')]
    if k!='points':
        raise ValueError('expected points but got %s'%(repr(k)))
    n = int(n)
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)

    log.debug('\tgetting %s points'%n)
    while len(points) < 3*n:
        l = common._getline(f).decode('ascii')
        points += map(eval,l.split(' '))
    assert len(points)==3*n
    while 1:
        l = common._getline(f)
        if l is None:
            break
        l = l.decode('ascii')
        sl = l.split(' ')
        k = sl[0].strip().lower()
        if k not in ['vertices','lines','polygons','triangle_strips']:
            break
        assert len(sl)==3
        n = int(sl[1])
        size = int(sl[2])
        lst = []
        while len(lst) < size:
            l = common._getline(f).decode('ascii')
            lst += map(eval, l.split(' '))
        assert len(lst)==size
        lst2 = []
        j = 0
        for i in range(n):
            lst2.append(lst[j+1:j+lst[j]+1])
            j += lst[j]+1
        data[k] = lst2

    return PolyData(points,data['vertices'], data['lines'], data['polygons'], data['triangle_strips']), l.encode()
452218
def write_dftbp(filename, atoms):
    
    scale_pos = dftbpToBohr

    lines = ""

    # 1. line, use absolute positions
    natoms = atoms.get_number_of_atoms()
    lines += str(natoms)
    lines += ' S \n'

    # 2. line
    expaned_symbols = atoms.get_chemical_symbols()
    symbols = get_reduced_symbols(expaned_symbols)
    lines += ' '.join(symbols) + '\n'

    atom_numbers = []
    for ss in expaned_symbols:
        atom_numbers.append(symbols.index(ss) + 1)

    positions = atoms.get_positions()/scale_pos

    for ii in range(natoms):
        pos = positions[ii]
        pos_str = "{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\n".format(
            ii + 1, atom_numbers[ii], pos[0], pos[1], pos[2])
        lines += pos_str

    # origin arbitrary
    lines +='0.0 0.0 0.0\n'

    cell = atoms.get_cell()/scale_pos

    for ii in range(3):
        cell_str = "{:20.15f} {:20.15f} {:20.15f}\n".format(
            cell[ii][0], cell[ii][1], cell[ii][2])
        lines += cell_str

    outfile = open(filename, 'w')
    outfile.write(lines)
770774
def draw_graph(G: nx.DiGraph, filename: str):
    
    A = to_agraph(G)
    A.graph_attr["rankdir"] = "LR"
    A.draw(filename, prog="dot")
1330756
def lattice(lattice, filename, directory, render, view, **kwargs):
    """"""
    dot = graphviz.Digraph(
        name=lattice.__class__.__name__,
        comment=repr(lattice),
        filename=filename,
        directory=directory,
        node_attr=dict(shape='circle', width='.25', style='filled', label=''),
        edge_attr=dict(dir='none', labeldistance='1.5', minlen='2'),
        **kwargs
    )

    sortkey = SORTKEYS[0]

    node_name = NAME_GETTERS[0]

    for concept in lattice._concepts:
        name = node_name(concept)
        dot.node(name)

        if concept.objects:
            dot.edge(name, name,
                headlabel=' '.join(concept.objects),
                labelangle='270', color='transparent')

        if concept.properties:
            dot.edge(name, name,
                taillabel=' '.join(concept.properties),
                labelangle='90', color='transparent')

        dot.edges((name, node_name(c))
            for c in sorted(concept.lower_neighbors, key=sortkey))

    if render or view:
        dot.render(view=view)  # pragma: no cover
    return dot
1177731
def dot(graph, simple=True, debug=False, landscape=False):
    """"""
    import sys

    from rdflib import ConjunctiveGraph
    from rdflib.plugin import register, Parser
    from rdflib.tools.rdf2dot import rdf2dot

    register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')

    g = ConjunctiveGraph().parse(
        data=_jsonld(graph, 'expand'),
        format='json-ld',
    )

    g.bind('prov', 'http://www.w3.org/ns/prov#')
    g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#')
    g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#')
    g.bind('wfprov', 'http://purl.org/wf4ever/wfprov#')

    if debug:
        rdf2dot(g, sys.stdout)
        return

    sys.stdout.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n ')
    if landscape:
        sys.stdout.write('rankdir="LR" \n')
    if simple:
        _rdf2dot_simple(g, sys.stdout)
        return
    _rdf2dot_reduced(g, sys.stdout)
831327
def load_graphs():
    ''''''
    mestate.graphs = []
    gfiles = ['mavgraphs.xml']
    if 'HOME' in os.environ:
        for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['HOME'], ".mavproxy")):
            for filename in filenames:
                
                if filename.lower().endswith('.xml'):
                    gfiles.append(os.path.join(dirname, filename))
    for file in gfiles:
        if not os.path.exists(file):
            continue
        graphs = load_graph_xml(open(file).read(), file)
        if graphs:
            mestate.graphs.extend(graphs)
            mestate.console.writeln("Loaded %s" % file)
    # also load the built in graphs
    dlist = pkg_resources.resource_listdir("MAVProxy", "tools/graphs")
    for f in dlist:
        raw = pkg_resources.resource_stream("MAVProxy", "tools/graphs/%s" % f).read()
        graphs = load_graph_xml(raw, None)
        if graphs:
            mestate.graphs.extend(graphs)
            mestate.console.writeln("Loaded %s" % f)
    mestate.graphs = sorted(mestate.graphs, key=lambda g: g.name)
140830
def _project_eigenvectors(self):
        """"""

        self._p_eigenvectors = []
        for vecs_q in self._eigenvectors:
            p_vecs_q = []
            for vecs in vecs_q.T:
                p_vecs_q.append(np.dot(vecs.reshape(-1, 3),
                                       self._projection_direction))
            self._p_eigenvectors.append(np.transpose(p_vecs_q))
        self._p_eigenvectors = np.array(self._p_eigenvectors)
339140
def init_supervisor_data(dotfile, sample_sets):
    
    with open(dotfile) as wf:
        graph_data = wf.read()

    graph = pydot.graph_from_dot_data(graph_data)[0]
    nodes = [n.get_name().strip('"') for n in graph.get_nodes()]

    monitor_data = dict()
    dependencies = {n:[] for n in nodes}

    # Initialize empty list of dependencies
    for n in nodes:
        monitor_data[n] = dict()
        for sset in sample_sets:
            monitor_data[n][sset] = {
                'state'        : "Not Started",
                'evaluated'    : False,
                'succeeded'    : False
            }

    edges = graph.get_edges()

    # Iterate over the edges, and get the dependency information for each node
    for e in edges:
        source = e.get_source().strip('"')
        dest = e.get_destination().strip('"')

        dep = e.get_attributes()
        dep['upstream_task'] = source

        dependencies[dest].append(dep)

    return monitor_data, dependencies
678802
private static void runGraphviz(String dotExecutable, String outputFolder, String packageName, String name, RootDoc root) {
    if (dotExecutable == null) {
      dotExecutable = "dot";
    }
	File dotFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".dot");
  File svgFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".svg");

	try {
	    Process p = Runtime.getRuntime().exec(new String [] {
		dotExecutable,
    "-Tsvg",
		"-o",
		svgFile.getAbsolutePath(),
		dotFile.getAbsolutePath()
	    });
	    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
	    String line;
	    while((line = reader.readLine()) != null)
		root.printWarning(line);
	    int result = p.waitFor();
	    if (result != 0)
		root.printWarning("Errors running Graphviz on " + dotFile);
	} catch (Exception e) {
	    e.printStackTrace();
	    System.err.println("Ensure that dot is in your path and that its path does not contain spaces");
	}
    }
285787
def merge_required_files(dirnames, out_dir):
    
    # The list of files to merge
    fn_to_merge = ("steps_summary.tex", "excluded_markers.txt",
                   "excluded_samples.txt")

    # Merging the files
    for fn in fn_to_merge:
        o_fn = os.path.join(out_dir, fn)
        with open(o_fn, "w") as o_file:
            for dn in dirnames:
                i_fn = os.path.join(dn, fn)
                with open(i_fn, "r") as i_file:
                    o_file.write(i_file.read())

    # Merging the result summary file
    o_fn = os.path.join(out_dir, "results_summary.txt")
    with open(o_fn, "w") as o_file:
        for i, dn in enumerate(dirnames):
            i_fn = os.path.join(dn, "results_summary.txt")
            with open(i_fn, "r") as i_file:
                if i != 0:
                    # We skip the first 4 lines (file descriptions)
                    [i_file.readline() for i in range(4)]
                o_file.write(i_file.read())

    # Merging the graphic paths file
    graphic_paths = set()
    for dn in dirnames:
        fn = os.path.join(dn, "graphic_paths.txt")
        if os.path.isfile(fn):
            with open(fn, "r") as i_file:
                graphic_paths.update({
                    os.path.join(dn, path)
                    for path in i_file.read().splitlines()
                })
    if len(graphic_paths) > 0:
        with open(os.path.join(out_dir, "graphic_paths.txt"), "w") as o_file:
            for path in sorted(graphic_paths):
                print >>o_file, os.path.relpath(path, out_dir)
56214
private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)
	    throws IOException {
        Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {
            public int compare(ClassDoc cd1, ClassDoc cd2) {
                return cd1.name().compareTo(cd2.name());
            }
        });
        for (ClassDoc classDoc : root.classes())
            classDocs.add(classDoc);

	ContextView view = null;
	for (ClassDoc classDoc : classDocs) {
	    try {
		if(view == null)
		    view = new ContextView(outputFolder, classDoc, root, opt);
		else
		    view.setContextCenter(classDoc);
		UmlGraph.buildGraph(root, view, classDoc);
		runGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);
		alterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),
			classDoc.name() + ".html", Pattern.compile(".*(Class|Interface|Enum) " + classDoc.name() + ".*") , root);
	    } catch (Exception e) {
		throw new RuntimeException("Error generating " + classDoc.name(), e);
	    }
	}
    }
924955
def save_dot(self, file_name='graph.dot'):
        
        s = self.get_string()
        with open(file_name, 'wt') as fh:
            fh.write(s)
80527
def dotty (params = {})
      dotfile = "graph.dot"
      File.open(dotfile, "w") {|f|
        print_dotted_on(params, f)
      }
      system("dotty", dotfile)
    end
802198
def to_dotfile(G: nx.DiGraph, filename: str):
    
    A = to_agraph(G)
    A.write(filename)
927519
def render_dot(self, code, options, format, prefix='graphviz'):
    # type: (nodes.NodeVisitor, unicode, Dict, unicode, unicode) -> Tuple[unicode, unicode]
    """"""
    graphviz_dot = options.get('graphviz_dot', self.builder.config.graphviz_dot)
    hashkey = (code + str(options) + str(graphviz_dot) +
               str(self.builder.config.graphviz_dot_args)).encode('utf-8')

    fname = '%s-%s.%s' % (prefix, sha1(hashkey).hexdigest(), format)
    relfn = posixpath.join(self.builder.imgpath, fname)
    outfn = path.join(self.builder.outdir, self.builder.imagedir, fname)

    if path.isfile(outfn):
        return relfn, outfn

    if (hasattr(self.builder, '_graphviz_warned_dot') and
       self.builder._graphviz_warned_dot.get(graphviz_dot)):
        return None, None

    ensuredir(path.dirname(outfn))

    # graphviz expects UTF-8 by default
    if isinstance(code, text_type):
        code = code.encode('utf-8')

    dot_args = [graphviz_dot]
    dot_args.extend(self.builder.config.graphviz_dot_args)
    dot_args.extend(['-T' + format, '-o' + outfn])
    if format == 'png':
        dot_args.extend(['-Tcmapx', '-o%s.map' % outfn])
    try:
        p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    except OSError as err:
        if err.errno != ENOENT:   # No such file or directory
            raise
        logger.warning(__('dot command %r cannot be run (needed for graphviz '
                          'output), check the graphviz_dot setting'), graphviz_dot)
        if not hasattr(self.builder, '_graphviz_warned_dot'):
            self.builder._graphviz_warned_dot = {}
        self.builder._graphviz_warned_dot[graphviz_dot] = True
        return None, None
    try:
        # Graphviz may close standard input when an error occurs,
        # resulting in a broken pipe on communicate()
        stdout, stderr = p.communicate(code)
    except (OSError, IOError) as err:
        if err.errno not in (EPIPE, EINVAL):
            raise
        # 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 GraphvizError(__('dot exited with error:\n[stderr]\n%s\n'
                               '[stdout]\n%s') % (stderr, stdout))
    if not path.isfile(outfn):
        raise GraphvizError(__('dot did not produce an output file:\n[stderr]\n%s\n'
                               '[stdout]\n%s') % (stderr, stdout))
    return relfn, outfn