Create a GnuPlot file for this BAM file.
509832
def create_gp(self):
        """"""

        categories_order = [
            ("{U}", "#ee82ee", 'Unmapped correctly'),
            ("{u}", "#ff0000", 'Unmapped incorrectly'),
            ("{T}", "#00ff00", 'Thresholded correctly'),
            ("{t}", "#008800", 'Thresholded incorrectly'),
            ("{P}", "#ffff00", 'Multimapped'),
            ("{w}+{x}", "#7f7f7f", 'Mapped, should be unmapped'),
            ("{m}", "#000000", 'Mapped to wrong position'),
            ("{M}", "#0000ff", 'Mapped correctly'),
        ]

        plot_lines = [
            '"{roc_fn}" using (( ({x}) )):({y}) lt rgb "{color}" with filledcurve x1 title "{title}", \\'.format(
                roc_fn=self._roc_fn,
                x=rnftools.lavender._format_xxx(self.default_x_axis),
                y=rnftools.lavender._format_xxx(
                    '({sum})*100/{{all}}'.format(sum="+".join([c[0] for c in categories_order[i:]]))
                ),
                color=categories_order[i][1],
                title=categories_order[i][2],
            ) for i in range(len(categories_order))
        ]

        plot = os.linesep.join((["plot \\"] + plot_lines + [""]))

        with open(self._gp_fn, "w+") as gp:
            gp_content = """
					set title "{{/:Bold=16 {title}}}"
	
					set x2lab "{x_lab}"
					set log x
					set log x2
	
					set format x "10^{{%L}}"
					set format x2 "10^{{%L}}"
					set xran  [{xran}]
					set x2ran [{xran}]
					set x2tics
					unset xtics
	
					set ylab "Part of all reads (%)"
	
					set format y "%g %%"
					set yran [{yran}]
					set y2ran [{yran}]
	
					set pointsize 1.5
	
					set grid ytics lc rgb "#777777" lw 1 lt 0 front
					set grid x2tics lc rgb "#777777" lw 1 lt 0 front
	
					set datafile separator "\\t"
					set palette negative
	
					set termin svg size {svg_size} enhanced
					set out "{svg_fn}"
					set key spacing 0.8 opaque width -5
				""".format(
                svg_fn=self._svg_fn,
                xran="{:.10f}:{:.10f}".format(self.report.default_x_run[0], self.report.default_x_run[1]),
                yran="{:.10f}:{:.10f}".format(self.report.default_y_run[0], self.report.default_y_run[1]),
                svg_size="{},{}".format(self.report.default_svg_size_px[0], self.report.default_svg_size_px[1]),
                title=os.path.basename(self._bam_fn)[:-4],
                x_lab=self.default_x_label,
            )
            gp_content = textwrap.dedent(gp_content) + "\n" + plot
            # gp_lines=gp_content.split("\n")
            # gp_lines=[x.strip() for x in gp_lines]
            # gp_content=gp_lines.join("\n")
            gp.write(gp_content)
898964
def save_plot(cls, data, columns, plottype, fmt='json', **kwargs):
        
        cls._verify_export_dir()
        plot = {"use_visavis_type": plottype, "payload": {}}

        if isinstance(data, pd.DataFrame):
            iter_data = data.iterrows
            pointers = columns
        else:
            iter_data = lambda: enumerate(data)
            pointers = range(len(data[0]))

        if fmt == 'csv':
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".csv")
            f_export = open(fmt_export, "w")
            f_export.write("%s\n" % ",".join(map(str, columns)))
            for _, row in iter_data():
                f_export.write("%s\n" % ",".join([str(row[i]) for i in pointers]))
            f_export.close()

        else:
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".json")
            f_export = open(fmt_export, "w")

            if plottype == 'bar':

                plot["payload"] = {"x": [], "y": [], "xtitle": cls._get_title(columns[0]), "ytitle": cls._get_title(columns[1])}

                for _, row in iter_data():
                    plot["payload"]["x"].append(row[pointers[0]])
                    plot["payload"]["y"].append(row[pointers[1]])

            elif plottype == 'plot3d':

                plot["payload"]["points"] = {"x": [], "y": [], "z": [], "labels": []}
                plot["payload"]["meshes"] = []
                plot["payload"]["xtitle"] = cls._get_title(columns[0])
                plot["payload"]["ytitle"] = cls._get_title(columns[1])
                plot["payload"]["ztitle"] = cls._get_title(columns[2])
                recent_mesh = 0

                for _, row in iter_data():
                    plot["payload"]["points"]["x"].append(row[pointers[0]])
                    plot["payload"]["points"]["y"].append(row[pointers[1]])
                    plot["payload"]["points"]["z"].append(row[pointers[2]])
                    plot["payload"]["points"]["labels"].append(row[pointers[3]])

                    if row[4] != recent_mesh:
                        plot["payload"]["meshes"].append({"x": [], "y": [], "z": []})
                    recent_mesh = row[4]

                    if plot["payload"]["meshes"]:
                        plot["payload"]["meshes"][-1]["x"].append(row[pointers[0]])
                        plot["payload"]["meshes"][-1]["y"].append(row[pointers[1]])
                        plot["payload"]["meshes"][-1]["z"].append(row[pointers[2]])

            if kwargs:
                plot["payload"].update(kwargs)

            else: raise RuntimeError("\r\nError: %s is an unknown plot type" % plottype)

            f_export.write(json.dumps(plot, escape_forward_slashes=False, indent=4))
            f_export.close()

        return fmt_export
241520
function plot(options) {
  /* Required Options */
  if (!options.data || !options.filename) {
    throw("The options object must have 'data' and 'filename' properties!");
    return;
  }
  /* Translate data into an object if needs be */
  if (_.isArray(options.data)) {
    /* If it's a one-dimentional array */
    if (_.isEqual(_.flatten(options.data), options.data)) {
      options.data = { 'Series 1': options.data };
    }
  }

  /* Defaults */
  if (!options.style) {
    options.style = 'lines'; /* Default to lines */
  }

  /* Apply moving averages and maximums */
  if (options.moving_avg) {
    options.data = apply_moving_filter(options.data, moving_average, options.moving_avg);
  }
  if (options.moving_max) {
    options.data = apply_moving_filter(options.data, moving_maximum, options.moving_max);
  }

  /* Execute Gnuplot specifing a function to be called when it terminates */
  if (options.format === 'pdf') { /* Special setup for pdf */
    gnuplot = exec('gnuplot | ps2pdf - ' + options.filename,
		   (options.exec ? options.exec : {}),
		   options.finish || post_gnuplot_processing);

  } else { /* Default for everything else */
    gnuplot = exec('gnuplot > ' + options.filename,
		   (options.exec ? options.exec : {}),
		   options.finish || post_gnuplot_processing);
  }

  /* Sets up gnuplot based on the properties we've been given in the
   * options object */
  setup_gnuplot(gnuplot, options);

  /* Get an array containing all the series */
  var series = _.keys(options.data);
  /* Reject series that are functions or come from higher up the protoype chain */
  var i;
  for (i = 0; i < series.length; i += 1) {
    if (!options.data.hasOwnProperty(series[i]) ||
	typeof options.data[series[i]] === 'function') {
      delete series[i]; /* undefine this element */
    }
  }
  /* Filter out any undefined elements */
  series = _.filter(series, function() { return true; });

  /* Print the command to actually do the plot */
  gnuplot.stdin.write('plot');
  for (i = 1; i <= series.length; i += 1) { /* For each series */
    /* Instruct gnuplot to plot this series */
    gnuplot.stdin.write('\'-\' using 1:2 title\'' + series[i - 1] +
			'\' with ' + options.style + ' lt 1 lc ' + i);
    /* If another series is to follow, add a comma */
    if (i < series.length) { gnuplot.stdin.write(','); }
  }
  gnuplot.stdin.write('\n');

  /* Print out the data */
  for (i = 0; i < series.length; i += 1) { /* For each series */
    for (key in options.data[series[i]]) {
      gnuplot.stdin.write(key + ' ' + options.data[series[i]][key] + '\n');
    }
    /* Terminate the data */
    gnuplot.stdin.write('e\n');
  }

  gnuplot.stdin.end();
}
124255
def make_plots(self, prefix, mcube_map=None, **kwargs):
        """"""

        #mcube_maps = kwargs.pop('mcube_maps', None)
        if mcube_map is None:
            mcube_map = self.model_counts_map()

        plotter = plotting.AnalysisPlotter(self.config['plotting'],
                                           fileio=self.config['fileio'],
                                           logging=self.config['logging'])
        plotter.run(self, mcube_map, prefix=prefix, **kwargs)
605039
def save(self_or_cls, obj, basename, fmt='auto', key={}, info={}, options=None, **kwargs):
        
        if info or key:
            raise Exception('Renderer does not support saving metadata to file.')

        if isinstance(obj, (Plot, NdWidget)):
            plot = obj
        else:
            with StoreOptions.options(obj, options, **kwargs):
                plot = self_or_cls.get_plot(obj)

        if (fmt in list(self_or_cls.widgets.keys())+['auto']) and len(plot) > 1:
            with StoreOptions.options(obj, options, **kwargs):
                if isinstance(basename, basestring):
                    basename = basename+'.html'
                self_or_cls.export_widgets(plot, basename, fmt)
            return

        rendered = self_or_cls(plot, fmt)
        if rendered is None: return
        (data, info) = rendered
        encoded = self_or_cls.encode(rendered)
        prefix = self_or_cls._save_prefix(info['file-ext'])
        if prefix:
            encoded = prefix + encoded
        if isinstance(basename, (BytesIO, StringIO)):
            basename.write(encoded)
            basename.seek(0)
        else:
            filename ='%s.%s' % (basename, info['file-ext'])
            with open(filename, 'wb') as f:
                f.write(encoded)
78278
def get_outfile(self, outfile, goids=None):
        """"""
        # 1. Use the user-specfied output filename for the GO Term plot
        if outfile != self.dflt_outfile:
            return outfile
        # 2. If only plotting 1 GO term, use GO is in plot name
        if goids is not None and len(goids) == 1:
            goid = next(iter(goids))
            goobj = self.gosubdag.go2obj[goid]
            fout = "GO_{NN}_{NM}".format(NN=goid.replace("GO:", ""), NM=goobj.name)
            return ".".join([re.sub(r"[\s#'()+,-./:<=>\[\]_}]", '_', fout), 'png'])
        # 3. Return default name
        return self.dflt_outfile
1178857
def make_nb(config, path=None, stop_on_error=True, just_tests=False):
    """"""
    root, nb_name = nb_name_from_path(config, path)
    clean = lambda varStr: re.sub('\W|^(?=\d)', '_', varStr)
    name = clean(nb_name)

    mpl_style = config.get('misc', 'matplotlib', fallback='inline')
    cells = [new_markdown_cell('## Sciunit Testing Notebook for %s' % nb_name)]
    add_code_cell(cells, (
        "%%matplotlib %s\n"
        "from IPython.display import display\n"
        "from importlib.machinery import SourceFileLoader\n"
        "%s = SourceFileLoader('scidash', '%s/__init__.py').load_module()") %
        (mpl_style, name, root))
    if just_tests:
        add_code_cell(cells, (
            "for test in %s.tests.tests:\n"
            "  score_array = test.judge(%s.models.models, stop_on_error=%r)\n"
            "  display(score_array)") % (name, name, stop_on_error))
    else:
        add_code_cell(cells, (
            "for suite in %s.suites.suites:\n"
            "  score_matrix = suite.judge("
            "%s.models.models, stop_on_error=%r)\n"
            "  display(score_matrix)") % (name, name, stop_on_error))
    write_nb(root, nb_name, cells)
549166
def makefile(graph):
    """"""
    from renku.models.provenance.activities import ProcessRun, WorkflowRun

    for activity in graph.activities.values():
        if not isinstance(activity, ProcessRun):
            continue
        elif isinstance(activity, WorkflowRun):
            steps = activity.subprocesses.values()
        else:
            steps = [activity]

        for step in steps:
            click.echo(' '.join(step.outputs) + ': ' + ' '.join(step.inputs))
            tool = step.process
            click.echo(
                '\t@' + ' '.join(tool.to_argv()) + ' ' + ' '.join(
                    tool.STD_STREAMS_REPR[key] + ' ' + str(path)
                    for key, path in tool._std_streams().items()
                )
            )
1064275
def create(plot_data, header, ploti, sample_config, out_file_base, outtype="png",
           title=None, size=None):
    
    if mpl is None or plt is None or sns is None:
        not_found = ", ".join([x for x in ['mpl', 'plt', 'sns'] if eval(x) is None])
        logger.info("No validation plot. Missing imports: %s" % not_found)
        return None
    mpl.use('Agg', force=True)

    if header:
        df = pd.DataFrame(plot_data, columns=header)
    else:
        df = plot_data
    df["aligner"] = [get_aligner(x, sample_config) for x in df["sample"]]
    df["bamprep"] = [get_bamprep(x, sample_config) for x in df["sample"]]
    floors = get_group_floors(df, cat_labels)
    df["value.floor"] = [get_floor_value(x, cat, vartype, floors)
                         for (x, cat, vartype) in zip(df["value"], df["category"], df["variant.type"])]
    out = []
    for i, prep in enumerate(df["bamprep"].unique()):
        out.append(plot_prep_methods(df, prep, i + ploti, out_file_base, outtype, title, size))
    return out
523714
public void create(final Path data, final Path output)
		throws IOException
	{
		_parameters.put(DATA_NAME, data.toString());
		_parameters.put(OUTPUT_NAME, output.toString());

		final String params = _parameters.entrySet().stream()
			.map(Gnuplot::toParamString)
			.collect(Collectors.joining("; "));

		String script = new String(Files.readAllBytes(_template));
		for (Map.Entry<String, String> entry : _environment.entrySet()) {
			final String key = format("${%s}", entry.getKey());
			script = script.replace(key, entry.getValue());
		}

		final Path scriptPath = tempPath();
		try {
			IO.write(script, scriptPath);
			final List<String> command = Arrays.
				asList("gnuplot", "-e", params, scriptPath.toString());

			final Process process = new ProcessBuilder()
				.command(command)
				.start();

			System.out.println(IO.toText(process.getErrorStream()));
			try {
				process.waitFor();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		} finally {
			deleteIfExists(scriptPath);
		}
	}
760093
def tb_h_file_creation(target, source, env):
    """"""

    files = [str(x) for x in source]

    try:
        desc = TBDescriptor(files)
    except pyparsing.ParseException as e:
        raise BuildError("Could not parse tilebus file", parsing_exception=e)

    block = desc.get_block(config_only=True)
    block.render_template(block.CommandHeaderTemplate, out_path=str(target[0]))
    block.render_template(block.ConfigHeaderTemplate, out_path=str(target[1]))
90251
def create(client, output_file, revision, paths):
    """"""
    graph = Graph(client)
    outputs = graph.build(paths=paths, revision=revision)

    output_file.write(
        yaml.dump(
            ascwl(
                graph.ascwl(outputs=outputs),
                filter=lambda _, x: x is not None and x != [],
                basedir=os.path.dirname(getattr(output_file, 'name', '.')) or
                '.',
            ),
            default_flow_style=False
        )
    )
946431
def wrplt(self, fout_dir, plt_ext="png"):
        """"""
        # Ex basename
        basename = self.grprobj.get_fout_base(self.ntplt.hdrgo)
        plt_pat = self.get_pltpat(plt_ext)
        fout_basename = plt_pat.format(BASE=basename)
        fout_plt = os.path.join(fout_dir, fout_basename)
        self.gosubdagplot.plt_dag(fout_plt) # Create Plot
        return fout_plt
1359014
def _create_pileup(bam_file, data, out_base, background):
    
    out_file = "%s-mpileup.txt" % out_base
    if not utils.file_exists(out_file):
        with file_transaction(data, out_file) as tx_out_file:
            background_bed = os.path.normpath(os.path.join(
                os.path.dirname(os.path.realpath(utils.which("verifybamid2"))),
                "resource", "%s.%s.%s.vcf.gz.dat.bed" % (background["dataset"],
                                                         background["nvars"], background["build"])))
            local_bed = os.path.join(os.path.dirname(out_base),
                                     "%s.%s-hg19.bed" % (background["dataset"], background["nvars"]))
            if not utils.file_exists(local_bed):
                with file_transaction(data, local_bed) as tx_local_bed:
                    with open(background_bed) as in_handle:
                        with open(tx_local_bed, "w") as out_handle:
                            for line in in_handle:
                                out_handle.write("chr%s" % line)
            mpileup_cl = samtools.prep_mpileup([bam_file], dd.get_ref_file(data), data["config"], want_bcf=False,
                                                target_regions=local_bed)
            cl = ("{mpileup_cl} | sed 's/^chr//' > {tx_out_file}")
            do.run(cl.format(**locals()), "Create pileup from BAM input")
    return out_file
558895
def make_figure(plots):
    
    # NB: matplotlib is imported inside since it is a costly import
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots()
    ax.grid(True)
    ax.set_xlabel('tasks')
    ax.set_ylabel('GB')
    start = 0
    for task_name, mem in plots:
        ax.plot(range(start, start + len(mem)), mem, label=task_name)
        start += len(mem)
    ax.legend()
    return plt
631691
def export(self, filename, fmt="DER"):
        
        f = open(filename, "wb")
        f.write(self.output(fmt))
        f.close()
486572
public static void installMyGnuPlot() {
      if(!FOUND_GP) {
        LOG.warn("Skipping Gnuplot Shell Script Install since Gnuplot executable was not found");
        return;
      }
      if(!GP_FILE.exists()) {
        if(!GP_FILE.getParentFile().exists()) {
          GP_FILE.getParentFile().mkdirs();
        }
        InputStream is = null;
        FileOutputStream fos = null;
        try {
          is = GnuplotInstaller.class.getClassLoader().getResourceAsStream(GP_BATCH_FILE_NAME);
          ChannelBuffer buff = new DynamicChannelBuffer(is.available());
          buff.writeBytes(is, is.available());
          is.close(); is = null;
          fos = new FileOutputStream(GP_FILE);
          buff.readBytes(fos, buff.readableBytes());
          fos.close(); fos = null;
          GP_FILE.setExecutable(true);
        } catch (Exception ex) {
          throw new IllegalArgumentException("Failed to install mygnuplot", ex);
        } finally {
          if( is!=null ) try { is.close(); } catch (Exception x) { /* No Op */ }
          if( fos!=null ) try { fos.close(); } catch (Exception x) { /* No Op */ }
        }
      }
    }