Beispiel #1
0
def plot_2(plotdata, filename, title, use_offset=False):
    f = mpl.figure.Figure(figsize=(11, 8.5))
    canvas = FigureCanvasPdf(f)
    f.suptitle(title)
    gs = GridSpec(len(plotdata), 1)
    gs.update(left=0.05, right=0.94, wspace=0.05)
    i = 0
    offset = 0
    for newdata, refdata, invert, series_no in plotdata:
        ax1 = f.add_subplot(gs[i, :])
        ax2 = ax1.twinx()
        data = newdata.match.rate().data
        ax2.plot(data[0], data[1], color='#e0b040', linewidth=2.0,
                 linestyle='-', marker='+', markeredgewidth=2.0)
        ax2max = ax2.get_ylim()[1]
        ax2.set_ylim([0, ax2max * 2])
        ax1.set_ylabel(newdata.series1[series_no].get_name())
        data = newdata.series1[series_no].data
        if use_offset:
            offset = -newdata.series1[series_no].std()*2
            if invert:
                offset = -offset
        ax1.plot(refdata.data[0], refdata.data[1]+offset, linewidth=2.0,
                 color='#9090ff')
        ax1.plot(data[0], data[1], color='black', linewidth=0.75)
        ax1.set_zorder(ax2.get_zorder()+1)  # put ax in front of ax2
        ax1.patch.set_visible(False)  # hide the 'canvas'
        if invert:
            ax1.invert_yaxis()
        i = i + 1
    canvas.print_figure(filename)
Beispiel #2
0
def make_plot(seriess, filename, title=None, invert=False):
    f = mpl.figure.Figure(figsize=(11, 8.5))
    canvas = FigureCanvasPdf(f)
    if title:
        f.suptitle(title)

    gs = GridSpec(len(seriess), 1)
    gs.update(left=0.05, right=0.94, wspace=0.05)
    for i in range(0, len(seriess)):
        s = seriess[i]
        if isinstance(s, (list, tuple)):
            ax1 = f.add_subplot(gs[i, :])
            ax2 = ax1.twinx()
            ax2.plot(s[1].data[0],
                     s[1].data[1],
                     color='#aaaaaa',
                     linewidth=5.0)
            ax1.set_ylabel(s[0].get_name())
            ax1.plot(s[0].data[0], s[0].data[1], color='black')
            ax1.set_zorder(ax2.get_zorder() + 1)  # put ax in front of ax2
            ax1.patch.set_visible(False)  # hide the 'canvas'
            if invert:
                ax1.invert_yaxis()
                ax2.invert_yaxis()
        else:
            ax = f.add_subplot(gs[i, :])
            ax.set_ylabel(s.get_name())
            ax.plot(s.data[0], s.data[1], color='black')
            if invert:
                ax.invert_yaxis()

    canvas.print_figure(filename)
Beispiel #3
0
    def output(self, file_suffix):

        if self.wide:
            left_text = self.header + '\n' + self.ts.title
            text_len = len(left_text.split('\n'))
            fontsize = self.ax.yaxis.label.get_size()
            linespacing = 1.2
            fontrate = float(fontsize * linespacing) / 72. / 15.5
            yloc = .8 - fontrate * (
                text_len - 1)  # this doesn't quite work. fontrate is too
            # small by a small amount
            self.fig.text(.05, yloc, left_text, linespacing=linespacing)
            self.fname = '_'.join([
                self.prefix, self.ts.j.id, self.ts.owner, 'wide_' + file_suffix
            ])
        elif self.header != None:
            title = self.header + '\n' + self.ts.title
            if self.threshold:
                title += ', V: %(v)-6.1f' % {'v': self.threshold}
            self.fig.suptitle(title)
            self.fname = '_'.join(
                [self.prefix, self.ts.j.id, self.ts.owner, file_suffix])
        else:
            self.fname = '_'.join(
                [self.prefix, self.ts.j.id, self.ts.owner, file_suffix])

        if self.mode == 'hist':
            self.fname += '_hist'
        elif self.mode == 'percentile':
            self.fname += '_perc'
        if not self.save:
            self.canvas = FigureCanvasAgg(self.fig)
        else:
            self.canvas = FigureCanvasPdf(self.fig)
            self.fig.savefig(os.path.join(self.outdir, self.fname))
Beispiel #4
0
def backtest_plot(account_value,
                  baseline_start=config.START_TRADE_DATE,
                  baseline_end=config.END_DATE,
                  baseline_ticker="^DJI",
                  positions=None,
                  transactions=None,
                  value_col_name="account_value"):

    df = deepcopy(account_value)
    test_returns = get_daily_return(df, value_col_name=value_col_name)

    baseline_df = get_baseline(baseline_ticker, baseline_start, baseline_end)
    baseline_returns = get_daily_return(baseline_df, value_col_name="close")
    baseline_returns = baseline_returns.reindex(pd.date_range(
        start=test_returns.index.min(), end=test_returns.index.max()),
                                                fill_value=0)

    with pyfolio.plotting.plotting_context(font_scale=1.1):
        figs = pyfolio.create_full_tear_sheet(positions=positions,
                                              transactions=transactions,
                                              returns=test_returns,
                                              benchmark_rets=baseline_returns,
                                              set_context=False,
                                              return_figs=True)
    now = datetime.now().strftime(config.DATETIME_FMT)
    with PdfPages(
            f'./{config.RESULTS_DIR}/full_tear_sheet_{now}.pdf') as pages:
        for fig in figs:
            canvas = FigureCanvasPdf(fig)
            canvas.print_figure(pages)
def write_figures(prefix, directory, dose_name, dose_data, data, ec50_coeffs,
                  feature_set, log_transform):
    '''Write out figure scripts for each measurement

    prefix - prefix for file names
    directory - write files into this directory
    dose_name - name of the dose measurement
    dose_data - doses per image
    data - data per image
    ec50_coeffs - coefficients calculated by calculate_ec50
    feature_set - tuples of object name and feature name in same order as data
    log_transform - true to log-transform the dose data
    '''
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_pdf import FigureCanvasPdf

    if log_transform:
        dose_data = np.log(dose_data)
    for i, (object_name, feature_name) in enumerate(feature_set):
        fdata = data[:, i]
        fcoeffs = ec50_coeffs[i, :]
        filename = "%s%s_%s.pdf" % (prefix, object_name, feature_name)
        pathname = os.path.join(directory, filename)
        f = Figure()
        canvas = FigureCanvasPdf(f)
        ax = f.add_subplot(1, 1, 1)
        x = np.linspace(0, np.max(dose_data), num=100)
        y = sigmoid(fcoeffs, x)
        ax.plot(x, y)
        dose_y = sigmoid(fcoeffs, dose_data)
        ax.plot(dose_data, dose_y, "o")
        ax.set_xlabel('Dose')
        ax.set_ylabel('Response')
        ax.set_title('%s_%s' % (object_name, feature_name))
        f.savefig(pathname)
Beispiel #6
0
def main(args):
	table = read_table(args.table)

	# Discard rows with any mutation within J at all
	logger.info('%s rows read', len(table))
	if not args.ignore_J:
		# Discard rows with any mutation within J at all
		table = table[table.J_SHM == 0][:]
		logger.info('%s rows remain after discarding J%%SHM > 0', len(table))

	if args.minimum_group_size is None:
		total = len(table)
		minimum_group_size = min(total // 1000, 100)
		logger.info('Skipping genes with less than %s assignments', minimum_group_size)
	else:
		minimum_group_size = args.minimum_group_size
	n = 0
	too_few = 0
	with PdfPages(args.pdf) as pages:
		for gene, group in table.groupby('V_gene'):
			if len(group) < minimum_group_size:
				too_few += 1
				continue
			fig = plot_difference_histogram(group, gene)
			n += 1
			FigureCanvasPdf(fig).print_figure(pages, bbox_inches='tight')
	logger.info('%s plots created (%s skipped because of too few sequences)', n, too_few)
Beispiel #7
0
  def canvas(self):
    type = self.get("imageType", "png")
    fig = Figure()
    if type == "png":
      canvas = FigureCanvasAgg(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "svg":
      canvas = FigureCanvasSVG(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "pdf":
      canvas = FigureCanvasPdf(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "ps" or type == "eps":
      canvas = FigureCanvasPS(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    else:
      raise "Invalid render target requested"

    # Set basic figure parameters
    dpi = float(self.get('dpi'))
    (w, h) = (float(self.get('width')), float(self.get('height')))
    (win, hin) = (w/dpi, h/dpi)
    fig.set_size_inches(win, hin)
    fig.set_dpi(dpi)
    fig.set_facecolor('white')
    return (fig, canvas, w, h)
Beispiel #8
0
def test_no_pyplot():
    # tests pickle-ability of a figure not created with pyplot
    from matplotlib.backends.backend_pdf import FigureCanvasPdf
    fig = mfigure.Figure()
    _ = FigureCanvasPdf(fig)
    ax = fig.add_subplot(1, 1, 1)
    ax.plot([1, 2, 3], [1, 2, 3])
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
Beispiel #9
0
def main(args):
    table = read_table(
        args.table, usecols=['V_gene', 'J_gene', 'V_SHM', 'J_SHM', 'CDR3_nt'])
    if not args.multi and not args.boxplot:
        print('Don’t know what to do', file=sys.stderr)
        sys.exit(2)

    # Discard rows with any mutation within J at all
    logger.info('%s rows read', len(table))
    if args.max_j_shm is not None:
        # Discard rows with too many J mutations
        table = table[table.J_SHM <= args.max_j_shm][:]
        logger.info(
            '%s rows remain after keeping only those with J%%SHM <= %s',
            len(table), args.max_j_shm)

    if args.minimum_group_size is None:
        total = len(table)
        minimum_group_size = min(total // 1000, 100)
        logger.info('Skipping genes with less than %s assignments',
                    minimum_group_size)
    else:
        minimum_group_size = args.minimum_group_size

    # Genes with high enough assignment count
    all_genes = table['V_gene'].unique()
    genes = sorted(table['V_gene'].value_counts().
                   loc[lambda x: x >= minimum_group_size].index)
    gene_set = set(genes)

    logger.info('%s out of %s genes have enough assignments', len(genes),
                len(all_genes))
    if args.multi:
        with PdfPages(args.multi) as pages:
            for gene, group in table.groupby('V_gene'):
                if gene not in gene_set:
                    continue
                fig = plot_difference_histogram(group, gene)
                FigureCanvasPdf(fig).print_figure(pages, bbox_inches='tight')

        logger.info('Wrote %r', args.multi)

    if args.boxplot:
        aspect = 1 + len(genes) / 32
        g = sns.catplot(x='V_gene',
                        y='V_SHM',
                        kind='boxen',
                        order=genes,
                        data=table,
                        height=2 * 2.54,
                        aspect=aspect,
                        color='g')
        # g.set(ylim=(-.1, None))
        g.set(ylabel='% V SHM (nt)')
        g.set(xlabel='V gene')
        g.set_xticklabels(rotation=90)
        g.savefig(args.boxplot)
        logger.info('Wrote %r', args.boxplot)
Beispiel #10
0
    def finalize(self, key):
        logi = self.instances.pop(key)

        from matplotlib.figure import Figure
        from matplotlib.backends.backend_pdf import FigureCanvasPdf

        fig = Figure(figsize=(6, 8))
        fig.suptitle("%s - order:%d" % (key))
        logi.render(fig)

        FigureCanvasPdf(fig)

        self.pdf.savefig(figure=fig)
Beispiel #11
0
def plot_flattend_a0v(spec_flattener, w, s_orig, of_list, data_list,
                      fout=None):
        print "Now generating figures"

        from matplotlib.backends.backend_pdf import Figure, FigureCanvasPdf
        fig = Figure()
        FigureCanvasPdf(fig)

        ax1 = fig.add_subplot(211)
        ax2 = fig.add_subplot(212, sharex=ax1)

        # data_list = [("flattened_spec", s_orig/continuum_array),
        #              ("wavelength", w),
        #              ("fitted_continuum", continuum_array),
        #              ("mask", mask_array),
        #              ("a0v_norm", a0v_array),
        #              ("model_teltrans", teltrans_array),
        #              ]

        s_a0v = data_list[4][1]
        tt_list = data_list[5][1]
        msk_list = data_list[3][1]
        cont_list = data_list[2][1]

        _interim_result = zip(w, s_orig, of_list, s_a0v, tt_list, msk_list, cont_list)

        for w1, s1_orig, of, s1_a0v, tt1, msk, cont in _interim_result:
            spec_flattener.plot_fitted(w1, s1_orig, s1_a0v, tt1,
                                       msk, msk, cont,
                                       ax1=ax1, ax2=ax2)

        ax2.set_ylim(-0.1, 1.2)
        ax2.axhline(1.0, color="0.8")
        ax2.set_xlabel(r"Wavelength [$\mu$m]")
        ax2.set_ylabel(r"Flattened Spectra")
        ax1.set_ylabel(r"Spectra w/o Blaze function correction")

        from matplotlib.backends.backend_pdf import PdfPages
        if fout is None:
            fout = 'multipage_pdf.pdf'
        with PdfPages(fout) as pdf:
            w = np.array(w)
            wmin, wmax = w.min(), w.max()
            ymax = np.nanmax(s_orig)
            ax1.set_xlim(wmin, wmax)
            ax1.set_ylim(-0.1*ymax, 1.1*ymax)
            pdf.savefig(figure=fig)

            for w1, s1_orig, of, s1_a0v, tt1, msk, cont in _interim_result:
                ax1.set_xlim(min(w1), max(w1))
                pdf.savefig(figure=fig)
Beispiel #12
0
    def makePDF(self, **params):
        from matplotlib.backends.backend_pdf import PdfPages
        #from pylab import *

        # Create the PdfPages object to which we will save the pages:
        imdata = StringIO()
        # should write to string buffer
        pdf = PdfPages(os.path.join(
            self.workDir, 'figures.pdf'))  #imdata) #'multipage_pdf.pdf')

        fig = self.heatmap()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)

        fig = self.histogram()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)  # here's another way - or you could do pdf.savefig(1)

        fig = self.plot()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig

        fig = self.duration()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig

        # We can also set the file's metadata via the PdfPages object:
        d = pdf.infodict()
        d['Title'] = 'Energy Fingerprint Report'
        d['Author'] = 'LBNL Energy Fingerprint Server'
        d['Subject'] = 'Visual summary of energy data with suggestions'
        d['Keywords'] = 'Green Button, Energy data, Fingerprint, LBNL'
        d['CreationDate'] = datetime.datetime.today()
        d['ModDate'] = datetime.datetime.today()

        # Remember to close the object - otherwise the file will not be usable
        pdf.close()
Beispiel #13
0
def download_plot_experiment(request, exp_id, plottype="box"):
    exp = get_object_or_404(models.Experiment, pk=exp_id)
    data, ndatamax = gather_measures(exp)

    fig = plt.Figure()
    if plottype == "box":
        ax = fig.add_subplot(111)
        ax = plot.make_box_plot(ax, data)
    else:
        fig = plot.make_hist_plot(fig, data)

    filename = "%s.pdf" % exp.name.replace(" ", "_")

    canvas = FigureCanvasPdf(fig)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    canvas.print_figure(response)
    return response
Beispiel #14
0
def main(args):
	logger.info('Will plot results to %s', args.pdf)
	cdr3_column = 'CDR3_nt' if args.nt else 'CDR3_aa'
	n_datasets = len(args.tables)
	if args.names:
		names = args.names.split(',')
		if len(names) != n_datasets:
			logger.error('%s dataset names given, but %s datasets provided', len(names), n_datasets)
			sys.exit(1)
	else:
		names = list(range(n_datasets))

	datasets = (read_dataset(path, limit=args.limit, minsize=args.minsize) for path in args.tables)
	df = pd.concat(datasets, keys=range(n_datasets), names=['dataset_id'])
	logger.info('Read %s tables', n_datasets)
	df.rename(columns=lambda x: x[:-4], inplace=True)  # Removes _SHM suffix
	cols = ['V_gene', 'J_gene', cdr3_column]
	n = 0
	with PdfPages(args.pdf) as pages:
		for (v_gene, j_gene, cdr3), group in df.groupby(level=cols):
			group = group.reset_index(level=cols, drop=True)
			skip = False
			counter = Counter(group.index)
			for dataset_id in range(n_datasets):
				if counter[dataset_id] < args.minsize:
					skip = True
					break
			if skip:
				continue
			table = group.stack()
			table.index.set_names('region', level=1, inplace=True)
			table.name = 'SHM'
			table = table.reset_index()
			table = table.assign(Dataset=table['dataset_id'].map(lambda i: names[i]))
			g = sns.factorplot(data=table, x='region', y='SHM', hue='Dataset',
				kind='violin', size=16*CM, aspect=2)
			dscounts = ' vs '.join(str(counter[i]) for i in range(n_datasets))
			g.fig.suptitle('V: {} – J: {} – CDR3: {} ({})'.format(v_gene, j_gene, cdr3, dscounts))
			g.set_axis_labels('Region')
			g.set_ylabels('%SHM')
			# g.despine()
			FigureCanvasPdf(g.fig).print_figure(pages, bbox_inches='tight')
			n += 1
			logger.info('Plotted %s clonotypes', n)
Beispiel #15
0
    def PlotGraphPDF(self):
        '''
        PDFにグラフを描画する関数
        '''
        from matplotlib.backends.backend_pdf import FigureCanvasPdf
        from matplotlib.backends.backend_pdf import PdfPages  # PDFを作成するモジュールの読込
        import os

        if self.GraphDataExist:
            iDir = os.getcwd()  #カレントディレクトリーの読込
            iFile = 'test.pdf'
            openFileDialog = wx.FileDialog(self, "PDFファイルの保存", iDir, iFile,
                                           "PDF files (*.pdf)|*.pdf",
                                           wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)

            _filename = ''
            openFileDialog.ShowModal()
            _filename = openFileDialog.GetPath()
            if _filename != '':
                #         from matplotlib.figure import Figure
                #         if event == wx.EVT_BUTTON:
                #             print(event)

                #         self.figure = Figure(  None )    # Figure(グラフの台紙)オブジェクトを生成
                self.figure.set_size_inches(298. / 25.4, 210. / 25.4, True)
                self.figure.set_dpi(600)
                self.figure.set_facecolor((0.7, 0.7, 1.0))  # Figureの表面色を設定

                pdf1 = PdfPages(_filename)
                self.canvas = FigureCanvasPdf(
                    self.figure)  # Canvas(グラフ)オブジェクトをfigure上に生成

                #         Draw_Graph(self.figure)

                pdf1.savefig(self.figure)
                pdf1.close()
            else:
                print('Print Cancel')
        else:
            dlg = wx.MessageDialog(self, '作図データがありません', '警告',
                                   wx.OK | wx.ICON_WARNING)
            dlg.ShowModal()
            dlg.Destroy()
Beispiel #16
0
def save_as_pdf(x, y, xlim, figsize):
    """Create and save a PDF file from plot data.

    Currently, it doesn't seem possible to select landscape vs. portrait for
    PDF. Try _save_as_eps if that feature is important.

    :param x: (numpy ndarray)
    :param y: (numpy ndarray)
    :param xlim: (float, float) a tuple of
    (max chemical shift, min chemical shift)
    :param figsize: (float, float) a tuple of (plot width, plot height) in
    inches.
    """
    figure = _create_figure(x, y, xlim, figsize)
    backend = FigureCanvasPdf(figure)
    filename = asksaveasfilename()
    if filename:
        if filename[-4:] != '.pdf':
            filename += '.pdf'
        backend.print_pdf(filename)
Beispiel #17
0
 def plot(self, gridspec=None, figsize=(11, 8.5), filetype="pdf"):
     if gridspec is None:
         gridspec = dict(left=0.05, right=0.94, wspace=0.05)
     nplots = len(self.plotspecs)
     fig = mpl.figure.Figure(figsize=figsize)
     if filetype.lower() == "pdf":
         FigureCanvasPdf(fig)
     elif filetype.lower() == "svg":
         FigureCanvasSVG(fig)
     else:
         raise ValueError("Unknown filetype: %s" % filetype)
     if self.title:
         fig.suptitle(self.title)
     gs = GridSpec(nplots, 1)
     gs.update(**gridspec)
     for i in xrange(0, nplots):
         self.plotspecs[i].plot(fig, gs, i)
     fig.set_size_inches(figsize)
     fig.savefig(self.filename + "." + filetype,
                 format=filetype.lower(), facecolor="none")
Beispiel #18
0
    def draw(self, path=None, show=True):
        self.main_drawing_flow(self.figure)

        if path is None:
            handle, path = tempfile.mkstemp(prefix="tmp_solcore_",
                                            suffix=".%s" %
                                            self.options["format"])

        if self.options["format"].upper() == "PDF":
            self.canvas = FigureCanvasPdf(self.figure)
        else:
            self.canvas = FigureCanvasAgg(self.figure)

        self.canvas.print_figure(path,
                                 dpi=self.options["dpi"],
                                 bbox_extra_artists=self.extra_artists,
                                 bbox_inches='tight')

        if show and not self.suppress_show:
            open_with_os(path)
Beispiel #19
0
def quickPlot(filename,
              path,
              datalist,
              xlabel="x",
              ylabel="y",
              xrange=["auto", "auto"],
              yrange=["auto", "auto"],
              yscale="linear",
              xscale="linear",
              col=["r", "b"]):
    """Plots Data to .pdf File in Plots Folder Using matplotlib"""
    if "plots" not in os.listdir(path):
        os.mkdir(os.path.join(path, "plots"))
    coltab = col * 10
    seaborn.set_context("notebook", rc={"lines.linewidth": 1.0})
    formatter = ScalarFormatter(useMathText=True)
    formatter.set_scientific(True)
    formatter.set_powerlimits((-2, 3))
    fig = Figure(figsize=(6, 6))
    ax = fig.add_subplot(111)
    for i, ydata in enumerate(datalist[1:]):
        ax.plot(datalist[0], ydata, c=coltab[i])
    ax.set_title(filename)
    ax.set_yscale(yscale)
    ax.set_xscale(xscale)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if xrange[0] != "auto":
        ax.set_xlim(xmin=xrange[0])
    if xrange[1] != "auto":
        ax.set_xlim(xmax=xrange[1])
    if yrange[0] != "auto":
        ax.set_ylim(ymin=yrange[0])
    if yrange[1] != "auto":
        ax.set_ylim(ymax=yrange[1])
    if yscale == "linear":
        ax.yaxis.set_major_formatter(formatter)
    ax.xaxis.set_major_formatter(formatter)
    canvas = FigureCanvasPdf(fig)
    canvas.print_figure(os.path.join(path, "plots", filename + ".pdf"))
    return
Beispiel #20
0
 def plot(self, gridspec=None, figsize=(11, 8.5), filetype="pdf"):
     if gridspec is None:
         gridspec = dict(left=0.05, right=0.94, wspace=0.05)
     nplots = len(self.plotspecs)
     fig = mpl.figure.Figure(figsize=figsize)
     # We have to create a canvas in order to be able to save the figure,
     # even if we don't assign the object to anything.
     # FigureCanvasBase.__init__ calls figure.set_canvas for us.
     if filetype.lower() == "pdf":
         FigureCanvasPdf(fig)
     elif filetype.lower() == "svg":
         FigureCanvasSVG(fig)
     else:
         raise ValueError("Unknown filetype: %s" % filetype)
     if self.title:
         fig.suptitle(self.title)
     gs = GridSpec(nplots, 1)
     gs.update(**gridspec)
     for i in xrange(0, nplots):
         self.plotspecs[i].plot(fig, gs, i)
     fig.set_size_inches(figsize)
     fig.savefig(self.filename + "." + filetype,
                 format=filetype.lower(),
                 facecolor="none")
Beispiel #21
0
    def save(self, fname=None, sigma_clip=None):
        r"""Saves the most recently rendered image of the Scene to disk.

        Once you have created a scene and rendered that scene to an image
        array, this saves that image array to disk with an optional filename.
        If an image has not yet been rendered for the current scene object,
        it forces one and writes it out.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            The file format is inferred from the filename's suffix. Supported
            fomats are png, pdf, eps, and ps.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)

        Returns
        -------
            Nothing

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # Modify camera, sources, etc...
        >>> sc.render()
        >>> sc.save('test.png', sigma_clip=4)

        Or alternatively:

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # save with different sigma clipping values
        >>> sc.save('raw.png')
        >>> sc.save('clipped_2.png', sigma_clip=2)
        >>> sc.save('clipped_4.png', sigma_clip=4)

        """
        if fname is None:
            sources = list(itervalues(self.sources))
            rensources = [s for s in sources if isinstance(s, RenderSource)]
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, string_types):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == '':
            suffix = '.png'
            fname = '%s%s' % (fname, suffix)

        self.render()

        mylog.info("Saving render %s", fname)
        # We can render pngs natively but for other formats we defer to
        # matplotlib.
        if suffix == '.png':
            self._last_render.write_png(fname, sigma_clip=sigma_clip)
        else:
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_pdf import \
                FigureCanvasPdf
            from matplotlib.backends.backend_ps import \
                FigureCanvasPS
            shape = self._last_render.shape
            fig = Figure((shape[0] / 100., shape[1] / 100.))
            if suffix == '.pdf':
                canvas = FigureCanvasPdf(fig)
            elif suffix in ('.eps', '.ps'):
                canvas = FigureCanvasPS(fig)
            else:
                raise NotImplementedError(
                    "Unknown file suffix '{}'".format(suffix))
            ax = fig.add_axes([0, 0, 1, 1])
            ax.set_axis_off()
            out = self._last_render
            nz = out[:, :, :3][out[:, :, :3].nonzero()]
            max_val = nz.mean() + sigma_clip * nz.std()
            alpha = 255 * out[:, :, 3].astype('uint8')
            out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255
            out = np.concatenate([out.astype('uint8'), alpha[..., None]],
                                 axis=-1)
            # not sure why we need rot90, but this makes the orientation
            # match the png writer
            ax.imshow(np.rot90(out), origin='lower')
            canvas.print_figure(fname, dpi=100)
Beispiel #22
0
def split_schrodinger_graph_potentials(schrodinger_result,
                                       trim_levels_beyond=1e-2,
                                       linewidth=1,
                                       scale=0.3,
                                       suppress_invert=False,
                                       probability_density=False,
                                       wfalpha=0.8,
                                       potentialalpha=0.8,
                                       **kwargs):
    defaults = {
        'step': 0.002,
        'margin': 0.02,
        'pdf': True,
        'show': False,
        'dpi': 100,
        'fontsize': 12,
        'figsize': (7, 6)
    }
    options = copy.copy(defaults)
    options["square"] = False

    defaults.update(kwargs)
    potentials = schrodinger_result["potentials"]
    wavefunctions = schrodinger_result["wavefunctions"]
    energy_levels = schrodinger_result["E"]
    x = schrodinger_result["x"]

    # This is used when doing the 4x4 kp calculation rather than the single band calculation
    if 'EU' in energy_levels.keys():
        energy_levels['Ehh'] = energy_levels['EU']
        energy_levels['Elh'] = energy_levels['EU']
        wavefunctions["psi_hh"] = wavefunctions["psi_g1"]
        wavefunctions["psi_lh"] = wavefunctions["psi_g2"]

    fig, (ax1, ax2) = plt.subplots(nrows=2,
                                   ncols=1,
                                   figsize=defaults['figsize'],
                                   dpi=defaults['dpi'])

    ax1.plot(x * 1e9, potentials["Ve"] / q, 'k', linewidth=2, label='Ve')
    ax1.set_ylabel('Energy (eV)', fontsize=defaults["fontsize"])
    ax1.tick_params(labelsize=defaults["fontsize"])
    ax1.grid(color='grey', linestyle='--', linewidth=0.5)

    ax2.plot(x * 1e9, potentials["Vlh"] / q, 'k--', linewidth=2, label="Vlh"),
    ax2.plot(x * 1e9, potentials["Vhh"] / q, 'k', linewidth=2, label="Vhh")
    ax2.set_ylabel('Energy (eV)', fontsize=defaults["fontsize"])
    ax2.set_xlabel('Possition (nm)', fontsize=defaults["fontsize"])
    ax2.tick_params(labelsize=defaults["fontsize"])
    ax2.grid(color='grey', linestyle='--', linewidth=0.5)

    e_data = prepare_wavefunction_data_only(x,
                                            energy_levels["Ee"] / q,
                                            wavefunctions["psi_e"],
                                            trim_levels_beyond,
                                            linewidth,
                                            "blue",
                                            0.03 / q,
                                            suppress_invert,
                                            alpha=wfalpha,
                                            square=probability_density)
    hh_data = prepare_wavefunction_data_only(x,
                                             energy_levels["Ehh"] / q,
                                             wavefunctions["psi_hh"],
                                             trim_levels_beyond,
                                             linewidth,
                                             "green",
                                             0.03 / q,
                                             suppress_invert,
                                             alpha=wfalpha,
                                             square=probability_density)
    lh_data = prepare_wavefunction_data_only(x,
                                             energy_levels["Elh"] / q,
                                             wavefunctions["psi_lh"],
                                             trim_levels_beyond,
                                             linewidth,
                                             "red",
                                             0.03 / q,
                                             suppress_invert,
                                             alpha=wfalpha,
                                             square=probability_density)

    for x, y in e_data:
        ax1.plot(x * 1e9, y, 'blue', linewidth=2, label='e')
    for x, y in hh_data:
        ax2.plot(x * 1e9, y, 'green', linewidth=2, label='hh')
    for x, y in lh_data:
        ax2.plot(x * 1e9, y, 'red', linewidth=2, label='lh')

    if defaults["show"]:
        plt.tight_layout()
        plt.show()

    if defaults["pdf"]:
        handle, path = tempfile.mkstemp(prefix="tmp_solcore_",
                                        suffix=".%s" %
                                        graph_defaults["format"])
        canvas = FigureCanvasPdf(fig)
        canvas.print_figure(path, dpi=defaults["dpi"], bbox_inches='tight')
        open_with_os(path)
Beispiel #23
0
def split_schrodinger_graph_LDOS(schrodinger_result, **kwargs):
    defaults = {
        'step': 0.001,
        'margin': 0.02,
        'pdf': True,
        'show': False,
        'dpi': 100,
        'fontsize': 12,
        'figsize': (7, 6)
    }
    defaults.update(kwargs)

    effective_masses = schrodinger_result["effective_masses"]
    potentials = schrodinger_result["potentials"]
    wavefunctions = schrodinger_result["wavefunctions"]
    energy_levels = schrodinger_result["E"]
    x = schrodinger_result["x"]

    if 'EU' in energy_levels.keys():
        energy_levels['Ehh'] = energy_levels['EU']
        energy_levels['Elh'] = energy_levels['EU']
        wavefunctions["psi_hh"] = wavefunctions["psi_g1"]
        wavefunctions["psi_lh"] = wavefunctions["psi_g2"]

    Ee, LDOSe = LDOS1D_e(x, energy_levels, wavefunctions, effective_masses,
                         defaults['step'], defaults['margin'])
    Eh, LDOSh = LDOS1D_h(x, energy_levels, wavefunctions, effective_masses,
                         defaults['step'], defaults['margin'])

    fig, (ax1, ax2) = plt.subplots(nrows=2,
                                   ncols=1,
                                   figsize=defaults['figsize'],
                                   dpi=defaults['dpi'])

    ax1.contourf(x * 1e9,
                 Ee / q,
                 LDOSe,
                 100,
                 cmap='gnuplot2_r',
                 vmin=0,
                 vmax=max(LDOSe.flatten()) * 1.2)
    ax1.plot(x * 1e9, potentials["Ve"] / q, 'k', linewidth=2, label='Ve')
    ax1.set_ylabel('Energy (eV)', fontsize=defaults["fontsize"])
    ax1.tick_params(labelsize=defaults["fontsize"])

    ax2.contourf(x * 1e9,
                 Eh / q,
                 LDOSh,
                 100,
                 cmap='gnuplot2_r',
                 vmin=0,
                 vmax=max(LDOSh.flatten()) * 1.2)
    ax2.plot(x * 1e9, potentials["Vlh"] / q, 'k--', linewidth=2, label="Vlh"),
    ax2.plot(x * 1e9, potentials["Vhh"] / q, 'k', linewidth=2, label="Vhh")
    ax2.set_ylabel('Energy (eV)', fontsize=defaults["fontsize"])
    ax2.set_xlabel('Possition (nm)', fontsize=defaults["fontsize"])
    ax2.tick_params(labelsize=defaults["fontsize"])

    if defaults["show"]:
        plt.tight_layout()
        plt.show()

    if defaults["pdf"]:
        handle, path = tempfile.mkstemp(prefix="tmp_solcore_",
                                        suffix=".%s" %
                                        graph_defaults["format"])
        canvas = FigureCanvasPdf(fig)
        canvas.print_figure(path, dpi=defaults["dpi"], bbox_inches='tight')
        open_with_os(path)

    return Ee, LDOSe, Eh, LDOSh
Beispiel #24
0
    def figure(self, name, coverage, exons=Gr(), codingexons=Gr(), amplicons=Gr(), depth=None):
        figure = Figure(figsize=(11.7, 4.15))
        FigureCanvasPdf(figure)
        ax = figure.gca()
        
        allblocks = amplicons.combined_with(exons).merged
        xscale = Scale()
        xticklabels = []
        xticks = []
        yscale = self._yscale
        for chrom in sorted(allblocks.keys(), key=chromosome_order):
            blocks = allblocks[chrom]
            xscale.initialse(blocks)
            
            # coverage
            if coverage:
                xy = [(xscale(blocks[0].start), yscale(0))]
                bisect = bisect_left(coverage[chrom], blocks[0].start) # leftmost coverage.stop >= entry.start
                for cstart, cstop, cdepth in coverage[chrom][bisect:]:
                    xy.append((xscale(max(blocks[0].start, cstart)), yscale(cdepth)))
                    if cstop >= blocks[-1].stop:
                        xy.append((xscale(blocks[-1].stop), yscale(cdepth)))
                        break
                xy.append((xscale(blocks[-1].stop), yscale(0)))
                xs, ys = zip(*xy)
                ax.plot(list(xs), list(ys), "-", drawstyle="steps-post", color="dodgerblue", linewidth=1)

            # amplicons
            for amplicon, y in zip(amplicons.get(chrom, ()), cycle((-0.04, 0))):
                ax.add_patch(Rectangle((xscale(amplicon.start), y), amplicon.stop-amplicon.start+1, 0.04, edgecolor="black", facecolor="black", zorder=100))

            # exons
            _xticks = []
            for exon in exons.get(chrom, ()):
                ax.add_patch(Rectangle((xscale(exon.start), -0.3), exon.stop-exon.start+1, 0.2, edgecolor="black", facecolor="darkgrey"))
                _xticks += [xscale((exon.start+exon.stop)//2)]
            for exon in codingexons.get(chrom, ()):
                ax.add_patch(Rectangle((xscale(exon.start), -0.3), exon.stop-exon.start+1, 0.2, edgecolor="black", facecolor="black"))
            xticklabels.extend(range(len(_xticks), 0, -1) if exons and next(iter(exons)).strand == "-" else range(1, len(_xticks)+1))
            xticks.extend(_xticks)
            ## variants       
            #if "variants_mutation" in panel:
                #if "depth" in panel:
                    #yvar = panel.depth
                #else:
                    #yvar = 0
                #x = [scale((variant.start+variant.stop)//2) for variant in plot_area.overlapped_by(panel.variants_mutation)]
                #y = [log(yvar)] * len(x)
                #ax.plot(x, y, "x", color="black")

        # depth        
        if depth:
            ax.axhline(yscale(depth), color="black", linewidth=0.5, linestyle=":")

        border = xscale(blocks[-1].stop) * 6/100
        minx = -border
        maxx = xscale(blocks[-1].stop) + border
        if exons and next(iter(exons)).strand == "-":
            minx, maxx = (maxx, minx)

        ax.set_xlim(minx, maxx)
        ax.spines["bottom"].set_visible(False)

        step = (len(xticks) // 20) + 1
        ax.set_xticks(xticks[::step])
        ax.set_xticklabels(xticklabels[::step], fontsize=8)
        ax.tick_params(axis="x",length=0)
        
        ax.set_ylim(-0.3, 4.5)
        ax.set_yticks([0, 1, 2, 3, 4])
        if yscale == log:
            ax.set_yticklabels(["0", "10", "100", "1000", "10,000"], fontsize=8)
            ax.set_ylabel("Read Depth (log scale)", fontsize=10)
        else:
            ax.set_yticklabels(["0", "1000", "2000", "3000", "4000"], fontsize=8)
            ax.set_ylabel("Read Depth", fontsize=10)
        
        ax.axhline(-0.2, color="black", linewidth=2, zorder=0)
        #ax.set_xlabel("Exon", fontsize=10)
        ax.set_title(self._title, fontsize=12)
        ax.add_patch(Rectangle((minx, 4.25), maxx-minx, 0.25, edgecolor="black", facecolor="bisque", zorder=100))
        ax.text((minx+maxx)//2, 4.355, name, zorder=101, ha="center", va="center")
        
        self._pdf.savefig(figure)#, bbox_inches='tight')
 def ariadne_run(self):
     d = dict(rand=[],
              rand_split=[],
              rand_merge=[],
              F_info=[],
              F_info_split=[],
              F_info_merge=[],
              vi=[],
              vi_split=[],
              vi_merge=[])
     gt = []
     detected = []
     counts = []
     for tgt in self.input():
         with tgt.open("r") as fd:
             data = json.load(fd)
         for key in d:
             d[key].append(data[key])
         gt.append(data["pairs"]["gt"])
         detected.append(data["pairs"]["detected"])
         counts.append(data["pairs"]["counts"])
     for key in d:
         d[key] = np.array(d[key])
     #
     # Rollup the statistics
     #
     matrix = coo_matrix((np.hstack(counts),
                          (np.hstack(gt), np.hstack(detected))))
     matrix.sum_duplicates()
     matrix = matrix.tocsr()
     #
     # The contingency table for the VI calculation is the fractional
     # component of each gt /detected pair.
     # The order for the vi code is [seg, gt], which is why we transpose
     #
     contingency_table = matrix.transpose() / matrix.sum()
     gt, detected = matrix.nonzero()
     counts = matrix[gt, detected].A1
     gt_counts = np.bincount(gt, counts)
     gt_counts = gt_counts[gt_counts > 0]
     detected_counts = np.bincount(detected, counts)
     detected_counts = detected_counts[detected_counts > 0]
     frac_counts = counts.astype(float) / counts.sum()
     frac_gt = gt_counts.astype(float) / gt_counts.sum()
     frac_detected = detected_counts.astype(float) / detected_counts.sum()
     tot_vi_merge, tot_vi_split = bits_to_nats(split_vi(contingency_table))
     tot_vi = tot_vi_merge + tot_vi_split
     tot_rand = Rand(frac_counts, frac_gt, frac_detected, .5)
     tot_rand_split = Rand(frac_counts, frac_gt, frac_detected, 0)
     tot_rand_merge = Rand(frac_counts, frac_gt, frac_detected, 1)
     tot_f_info = f_info(frac_counts, frac_gt, frac_detected, .5)
     tot_f_info_split = f_info(frac_counts, frac_gt, frac_detected, 0)
     tot_f_info_merge = f_info(frac_counts, frac_gt, frac_detected, 1)
     #
     # Draw it
     #
     figure = matplotlib.figure.Figure()
     figure.set_size_inches(8, 11)
     columns = filter(lambda _:not _.startswith("vi"), sorted(d.keys()))
     vi_data = d['vi']
     vis_data = d['vi_split']
     vim_data = d['vi_merge']
     ax = figure.add_axes((0.05, 0.1, 0.55, 0.70))
     ax.boxplot([d[c][~ np.isnan(d[c])] for c in columns])
     ax.set_xticklabels(columns, rotation=15)
     ax.set_yticks(np.linspace(0, 1.0, 11))
     ax.set_xlim(.5, len(columns)+1)
     for i, mean in enumerate([d[c].mean() for c in columns]):
         ann = ax.annotate("%.2f" % mean, 
                     xy=(i+1, mean),
                     xytext=(i+1.4, mean),
                     bbox=dict(boxstyle="round", fc="white", ec="gray"),
                     arrowprops=dict(arrowstyle="->", color="gray"))
         matplotlib.pyplot.setp(ann, fontsize=6)
     vi_ax = figure.add_axes((0.65, 0.1, 0.30, 0.70))
     vi_ax.boxplot([_[~np.isnan(_)] for _ in vi_data, vim_data, vis_data],
                   labels=['VI\n(bits)', 'Merge', 'Split'])
     for i, data in enumerate([vi_data, vim_data, vis_data]):
         ann = vi_ax.annotate(
             "%.2f" % data.mean(),
             xy=(i+1, data.mean()),
             xytext=(i+1.2, data.mean()+.1),
             bbox=dict(boxstyle="round", fc="white", ec="gray"),
             arrowprops=dict(arrowstyle="->", color="gray"))
         matplotlib.pyplot.setp(ann, fontsize=6)
     for a in ax, vi_ax:
         matplotlib.pyplot.setp(a.get_xmajorticklabels(), fontsize=8)
         matplotlib.pyplot.setp(a.get_ymajorticklabels(), fontsize=6)
         totals = "Total /split / merge VI=%.2f / %.2f / %.2f\n" %\
             (tot_vi, tot_vi_split, tot_vi_merge)
         totals += "Rand=%.2f / %.2f / %.2f\n" % \
             (tot_rand, tot_rand_split, tot_rand_merge)
         totals += "F info=%.2f / %.2f / %.2f" % \
             (tot_f_info, tot_f_info_split, tot_f_info_merge)
     figure.text(.5, .90, "Segmentation accuracy\n"+totals,
                 ha='center', va='top',
                 size='x-large')
     canvas = FigureCanvasPdf(figure)
     figure.savefig(self.pdf_location)
Beispiel #26
0
def plot_service(results, target_stop_name, target_date, outfile):
    HOURS = 24

    fig_format = outfile[-3:]

    fig = Figure(figsize=(12, 6), dpi=300)
    if fig_format == 'pdf':
        canvas = FigureCanvasPdf(fig)
    elif fig_format == 'svg':
        canvas = FigureCanvasSVG(fig)
    ax = fig.add_subplot(111, xlim=(0, 24))
    fig.subplots_adjust(bottom=0.2, left=0.05, right=0.98)

    pos = np.arange(HOURS)
    width = 0.40

    color_dups = Counter()
    hatch = ["/", ".", "x", "*", "+"]

    values_0 = np.array(np.zeros(HOURS))
    values_1 = np.array(np.zeros(HOURS))

    for route_id, route_data in results.items():
        bar_args = {}
        if route_data['route_color'] and route_data['route_color'] != '':
            bar_args['color'] = '#' + route_data['route_color']
        else:
            bar_args['color'] = '#000000'
            bar_args['edgecolor'] = '#444444'
        color_dups[bar_args['color']] += 1
        if color_dups[bar_args['color']] > 1:
            (hatch_dup, hatch_id) = divmod(color_dups[bar_args['color']] - 2,
                                           len(hatch))
            bar_args['hatch'] = hatch[hatch_id] * (hatch_dup + 1)
        route_data['plot_0'] = ax.bar(pos,
                                      route_data['bins_0'],
                                      width,
                                      bottom=values_0,
                                      **bar_args)
        route_data['plot_1'] = ax.bar(pos + width,
                                      route_data['bins_1'],
                                      width,
                                      bottom=values_1,
                                      **bar_args)

        make_labels(route_data['plot_0'], ax,
                    '#' + contrasting_color(bar_args['color'][1:]))
        make_labels(route_data['plot_1'], ax,
                    '#' + contrasting_color(bar_args['color'][1:]))

        values_0 += np.array(route_data['bins_0'])
        values_1 += np.array(route_data['bins_1'])

    if len(results) > 1:
        last_route_data = results.values()[-1]
        make_top_labels(last_route_data['plot_0'], ax, values_0)
        make_top_labels(last_route_data['plot_1'], ax, values_1)

    maxtph = (math.ceil(max(max(values_0), max(values_1)) / 10.0) * 10) + 5

    ax.set_ylim(0, maxtph)
    ax.set_xlabel('Hour')
    ax.set_ylabel(
        mode_string([route['route_type'] for route in results.values()]))
    ax.set_title('Service at %s on %s' %
                 (target_stop_name, target_date.strftime("%Y-%m-%d")))
    ax.set_yticks(np.arange(0, maxtph, 4))
    ax.set_xticks(pos + width)
    ax.set_xticklabels([str(i) for i in range(0, HOURS)])
    ax.legend([route_data['plot_0'][0] for route_data in results.values()],
              [route_data['route_name'] for route_data in results.values()],
              prop={'size': 'small'},
              ncol=2)

    headsigns_0 = set()
    headsigns_1 = set()

    for route in results.values():
        headsigns_0.update(route['headsigns_0'].keys())
        headsigns_1.update(route['headsigns_1'].keys())

    d0 = textwrap.fill("Direction 0 is: %s" % (", ".join(headsigns_0)),
                       150,
                       subsequent_indent='    ')
    d1 = textwrap.fill("Direction 1 is: %s" % (", ".join(headsigns_1)),
                       150,
                       subsequent_indent='    ')

    fig.text(0.05, 0.05, d0 + "\n" + d1, size="small")

    fig.savefig(outfile, format=fig_format)
Beispiel #27
0
    def save_annotated(self,
                       fname=None,
                       label_fmt=None,
                       text_annotate=None,
                       dpi=100,
                       sigma_clip=None):
        r"""Saves the most recently rendered image of the Scene to disk,
        including an image of the transfer function and and user-defined
        text.

        Once you have created a scene and rendered that scene to an image
        array, this saves that image array to disk with an optional filename.
        If an image has not yet been rendered for the current scene object,
        it forces one and writes it out.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as a bitmap to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)
        dpi: integer, optional
            By default, the resulting image will be the same size as the camera
            parameters.  If you supply a dpi, then the image will be scaled
            accordingly (from the default 100 dpi)
        label_fmt : str, optional
           A format specifier (e.g., label_fmt="%.2g") to use in formatting 
           the data values that label the transfer function colorbar. 
        text_annotate : list of iterables
           Any text that you wish to display on the image.  This should be an
           list containing a tuple of coordinates (in normalized figure 
           coordinates), the text to display, and, optionally, a dictionary of 
           keyword/value pairs to pass through to the matplotlib text() 
           function.

           Each item in the main list is a separate string to write.


        Returns
        -------
            Nothing


        Examples
        --------

        >>> sc.save_annotated("fig.png", 
        ...                   text_annotate=[[(0.05, 0.05),
        ...                                   "t = {}".format(ds.current_time.d),
        ...                                   dict(horizontalalignment="left")],
        ...                                  [(0.5,0.95),
        ...                                   "simulation title",
        ...                                   dict(color="y", fontsize="24",
        ...                                        horizontalalignment="center")]])

        """
        from yt.visualization._mpl_imports import \
            FigureCanvasAgg, FigureCanvasPdf, FigureCanvasPS
        sources = list(itervalues(self.sources))
        rensources = [s for s in sources if isinstance(s, RenderSource)]

        if fname is None:
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, string_types):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == '':
            suffix = '.png'
            fname = '%s%s' % (fname, suffix)

        self.render()

        # which transfer function?
        rs = rensources[0]
        tf = rs.transfer_function
        label = rs.data_source.ds._get_field_info(rs.field).get_label()

        ax = self._show_mpl(self._last_render.swapaxes(0, 1),
                            sigma_clip=sigma_clip,
                            dpi=dpi)
        self._annotate(ax.axes, tf, rs, label=label, label_fmt=label_fmt)

        # any text?
        if text_annotate is not None:
            f = self._render_figure
            for t in text_annotate:
                xy = t[0]
                string = t[1]
                if len(t) == 3:
                    opt = t[2]
                else:
                    opt = dict()

                # sane default
                if "color" not in opt:
                    opt["color"] = "w"

                ax.axes.text(xy[0],
                             xy[1],
                             string,
                             transform=f.transFigure,
                             **opt)

        suffix = get_image_suffix(fname)

        if suffix == ".png":
            canvas = FigureCanvasAgg(self._render_figure)
        elif suffix == ".pdf":
            canvas = FigureCanvasPdf(self._render_figure)
        elif suffix in (".eps", ".ps"):
            canvas = FigureCanvasPS(self._render_figure)
        else:
            mylog.warning("Unknown suffix %s, defaulting to Agg", suffix)
            canvas = self.canvas

        self._render_figure.canvas = canvas
        self._render_figure.tight_layout()
        self._render_figure.savefig(fname, facecolor='black', pad_inches=0)
Beispiel #28
0
 def pdfData(self, fig):
     canvas = FigureCanvasPdf(fig)
     imdata = StringIO()
     canvas.print_pdf(imdata)
     return imdata.getvalue()
           mfc='w',
           ms=5,
           label='non-relaxed, tight parameters')
ax2.loglog(N[-3:],
           e2_fixed,
           c='k',
           ls='-',
           lw=0.5,
           marker='+',
           ms=5,
           label='non-relaxed, loose parameters')
ax2.loglog(N[-3:],
           e2_relaxed,
           c='k',
           ls='-',
           lw=0.5,
           marker='x',
           ms=5,
           label='relaxed, loose parameters')

ax2.set_xlabel('$N$', fontsize=10)
ax2.legend(loc=1, fontsize=6.5)
ax2.set_yticklabels([])
ax2.grid('on')
ax2.set_title('2nd-kind', fontsize=10)

fig.subplots_adjust(left=0.15, bottom=0.15, right=0.87, top=0.92)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceConvergence.pdf', dpi=80)
Beispiel #30
0
    def save(self, fname=None, sigma_clip=None, render=True):
        r"""Saves a rendered image of the Scene to disk.

        Once you have created a scene, this saves an image array to disk with
        an optional filename. This function calls render() to generate an
        image array, unless the render parameter is set to False, in which case
        the most recently rendered scene is used if it exists.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            The file format is inferred from the filename's suffix. Supported
            fomats are png, pdf, eps, and ps.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)
        render: boolean, optional
            If True, will always render the scene before saving.
            If False, will use results of previous render if it exists.
            Default: True

        Returns
        -------
            Nothing

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # Modify camera, sources, etc...
        >>> sc.save('test.png', sigma_clip=4)

        When saving multiple images without modifying the scene (camera,
        sources,etc.), render=False can be used to avoid re-rendering when a scene is saved.
        This is useful for generating images at a range of sigma_clip values:

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # save with different sigma clipping values
        >>> sc.save('raw.png')  # The initial render call happens here
        >>> sc.save('clipped_2.png', sigma_clip=2, render=False)
        >>> sc.save('clipped_4.png', sigma_clip=4, render=False)

        """
        if fname is None:
            sources = list(self.sources.values())
            rensources = [s for s in sources if isinstance(s, RenderSource)]
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, str):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == "":
            suffix = ".png"
            fname = "%s%s" % (fname, suffix)

        render = self._sanitize_render(render)
        if render:
            self.render()
        mylog.info("Saving rendered image to %s", fname)

        # We can render pngs natively but for other formats we defer to
        # matplotlib.
        if suffix == ".png":
            self._last_render.write_png(fname, sigma_clip=sigma_clip)
        else:
            from matplotlib.backends.backend_pdf import FigureCanvasPdf
            from matplotlib.backends.backend_ps import FigureCanvasPS
            from matplotlib.figure import Figure

            shape = self._last_render.shape
            fig = Figure((shape[0] / 100.0, shape[1] / 100.0))
            if suffix == ".pdf":
                canvas = FigureCanvasPdf(fig)
            elif suffix in (".eps", ".ps"):
                canvas = FigureCanvasPS(fig)
            else:
                raise NotImplementedError("Unknown file suffix '{}'".format(suffix))
            ax = fig.add_axes([0, 0, 1, 1])
            ax.set_axis_off()
            out = self._last_render
            nz = out[:, :, :3][out[:, :, :3].nonzero()]
            max_val = nz.mean() + sigma_clip * nz.std()
            alpha = 255 * out[:, :, 3].astype("uint8")
            out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255
            out = np.concatenate([out.astype("uint8"), alpha[..., None]], axis=-1)
            # not sure why we need rot90, but this makes the orientation
            # match the png writer
            ax.imshow(np.rot90(out), origin="lower")
            canvas.print_figure(fname, dpi=100)