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 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 #3
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 #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)
Beispiel #5
0
def plotPolygon(tri, polyPoints, nodeID, xRange, yRange):
    """Plots the voronoi polygon around a single node."""
    fig = Figure(figsize=(4,4))
    canvas = FigureCanvas(fig)
    fig.subplots_adjust(left=0.15, bottom=0.13,wspace=0.25, right=0.95)
    ax = fig.add_subplot(111, aspect='equal')
    
    ax.plot(tri.x, tri.y, '.k', ms=1)
    ax.plot(tri.x[nodeID], tri.y[nodeID],'.r', ms=2)
    # print polyPoints[nodeID]
    patch = matplotlib.patches.Polygon(polyPoints[nodeID], closed=True, fill=True, lw=1)
    ax.add_patch(patch)
    # ax.plot(tri.x, tri.y, '.k')
    ax.set_xlim(xRange)
    ax.set_ylim(yRange)
    canvas.print_figure("cell", dpi=300.)
Beispiel #6
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 #7
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 #8
0
def run():
    args = get_args()
    roofile = up.open(args.input_file)
    outdir = args.output_dir
    if not path.isdir(outdir):
        mkdir(outdir)

    for name, hist in roofile.items():
        short_name = name.decode('utf-8').split(';')[0]
        print(f'drawing {short_name}')
        # set up canvas and figure
        fig = Figure(figsize=(5, 3))
        can = FigCanvas(fig)
        ax = fig.add_subplot(1, 1, 1)

        # add a plot
        vals, edges = hist.numpy
        centers = (edges[:-1] + edges[1:]) / 2
        ax.plot(centers, vals)
        ax.set_yscale('log')
        can.print_figure(f'{outdir}/{short_name}.pdf')
N_8cells = array([16384, 65536])
it_8cells = array([61, 66])

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(7,4), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
bar1 = ax.semilogx(N_2048,cells_2048,c='k',marker='o', ls='-', mfc='w', ms=5, label='')
bar2 = ax.semilogx(N_8192,cells_8192,c='k',marker='o', ls=':', mfc='w', ms=5, label='')
bar3 = ax.semilogx(N_32768,cells_32768,c='k',marker='o', ls='-.', mfc='w', ms=5, label='')
bar4 = ax.semilogx(N_2cells,it_2cells,c='r',marker='o', ls='-', mfc='w', ms=5, label='')
bar5 = ax.semilogx(N_4cells,it_4cells,c='r',marker='o', ls=':', mfc='w', ms=5, label='')
bar6 = ax.semilogx(N_8cells,it_8cells,c='r',marker='o', ls='-.', mfc='w', ms=5, label='')
rc('font',**font)

# axis labels
ax.set_ylabel('Iterations', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.legend( (bar1[0],bar2[0],bar3[0],bar4[0],bar5[0],bar6[0]), ('2048 per cell','8192 per cell','32768 per cell','2 cells','4 cells','8cells'),loc=2)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)



# plot to pdf
canvas.print_figure('EthrocyteMultipleCellIterations.pdf',dpi=80)

Beispiel #10
0
# open the result file
result = open(sys.argv[1])

# set up data
N, t = numpy.loadtxt(result, dtype=float, unpack=True)

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)


# plot log-log
ax.loglog(N,t,color='k',marker='o', ms=5, mfc='w')
ax.loglog(N,N/20000,color='k', ls=':', ms=5, mfc='w')
loc = (3*N[0]+N[1])/4

# text of plot
tex_loc = numpy.array((loc,N[0]*t[0]/loc)) * 1.2
tex_angle = numpy.arctan2(numpy.log(abs(N[-1]/10000-N[0]/10000)),numpy.log(abs(N[-1]-N[0])))*180/numpy.pi
ax.text(tex_loc[0], 6.5*tex_loc[1],r'$O(N)$',fontsize=10,rotation=tex_angle,rotation_mode='anchor')

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('FMMScaling.pdf',dpi=80)
Beispiel #11
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)
N = array([128, 512, 2048, 8192, 32768, 131072])
e = array([1.84e-1, 9.27e-2, 4.61e-2, 2.41e-2, 1.14e-2, 5.80e-3])

line_sqrtN = 1 / np.sqrt(N)

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.loglog(N,e,c='k',marker='o', ls='-', mfc='w', ms=5, label='')
ax.loglog(N,line_sqrtN,c='k',ls='--', mfc='w', ms=5, label='')
rc('font',**font)
loc = (3*N[0]+N[1])/4

# text on plot
# 1 / sqrt(N)
tex_loc = np.array((loc,N[0]*e[0]/loc))
tex_angle = math.atan2(np.log(np.abs(line_sqrtN[-1]-line_sqrtN[0])),np.log(np.abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1]/3.5,r'$O(1/\sqrt{N})$',fontsize=8,rotation=tex_angle-10,rotation_mode='anchor')
# axis labels
ax.set_ylabel('Relative Error', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesConvergence.pdf',dpi=80)

print(t_relax, t_fixed)
print(speedup)
# plot log-log
bar1 = ax.bar(ind,
              t_fixed,
              width,
              fill=False,
              edgecolor='k',
              hatch='..' * 2,
              linewidth=1)
bar2 = ax.bar(ind + width,
              t_relax,
              width,
              fill=False,
              edgecolor='k',
              hatch='/' * 4,
              linewidth=1)

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('p', fontsize=10)
ax.set_xticks(ind + width)
ax.set_xticklabels(('5', '8', '10', '12', '15'))
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
ax.legend((bar1[0], bar2[0]), ('fixed p', 'Relaxed'), loc=2, fontsize='small')
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceRelaxationP.pdf', dpi=80)
Beispiel #14
0
output_figs.append(fig2)

fig3, ax = plt.subplots(1, 2, figsize = (35,15))
plt.subplots_adjust(wspace=0.05)

multi_map_total = stats[['% of reads unmapped: other', 'rep', 'tissue']]
multi_map_total.loc[:,'% of reads unmapped: other'] = multi_map_total['% of reads unmapped: other'].apply(lambda value: float(value.replace('%','')) / 100)
sns.heatmap(multi_map_total.pivot(columns = 'rep', values = '% of reads unmapped: other', index = 'tissue'), robust = True, cmap = 'viridis', ax = ax[0])
labels = list(multi_map_total.pivot(columns = 'rep', values = '% of reads unmapped: other', index = 'tissue').index)
ax[0].yaxis.set(ticks=np.arange(0.5, len(labels)), ticklabels=labels)
ax[0].set_title('fraction of reads unmapped: other', fontsize=20)

multi_map_rate = stats[['% of reads unmapped: too short', 'rep', 'tissue']]
multi_map_rate.loc[:,'% of reads unmapped: too short'] = multi_map_rate['% of reads unmapped: too short'].apply(lambda value: float(value.replace('%','')) / 100)
sns.heatmap(multi_map_rate.pivot(columns = 'rep', values = '% of reads unmapped: too short', index = 'tissue'), robust = True, cmap = 'viridis', vmin = 0, ax = ax[1])

ax[1].yaxis.set()
ax[1].set_title('fraction of reads unmapped: too short', fontsize=20)

fig3.text(.8, .05, 'Missing values are indicated by blanks. This means no RNAseq data of this tissue is available from this particular horse', ha='right', fontsize = 15)
output_figs.append(fig3)

print("Saving to output...")

from matplotlib.backends.backend_pdf import FigureCanvasPdf, PdfPages
with PdfPages(snakemake.output['pdf']) as pages:
    for i in output_figs:
        canvas = FigureCanvasPdf(i)
        canvas.print_figure(pages)

stats.to_csv(snakemake.output['csv'], index = False)
ax1.loglog(N[-3:], e1_relaxed, c='k', ls='-', lw=0.5, marker='x',
           ms=5, label='relaxed, loose parameters')

ax1.set_xlabel('$N$', fontsize=10)
ax1.set_ylabel('Relative Error')
ax1.legend(loc=1, fontsize=6.5)
ax1.grid('on')
ax1.set_title('1st-kind', fontsize=10)

# right plot: 2nd-kind
ax2 = fig.add_subplot(122)

ax2.loglog(N, e2, c='k', ls='-', lw=1.0, marker='o', 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)
# plot log-log
ax.loglog(N, e, c='k', ls='-', lw=1.0, marker='o', mfc='w', 
	      ms=5, label='non-relaxed, tight parameters')
ax.loglog(N[1:], e_fixed, c='k', ls='-', lw=0.5, marker='+',
           ms=5, label='non-relaxed, loose parameters')
ax.loglog(N[1:], e_relaxed, c='k', ls='-', lw=0.5, marker='x',
           ms=5, label='relaxed, loose parameters')

# referece line
ax.loglog(N, line_sqrtN, c='k',ls='--')

# text on plot
scale2 = 0.6    # for plot adjustment
loc = (3*N[0]+N[1])/4
tex_loc = numpy.array((loc, N[0]*e[0]/loc)) * scale2
tex_angle = - 23
ax.text(tex_loc[0], tex_loc[1]/3.5, r'$O(1/\sqrt{N})$', 
	    fontsize=8, rotation=tex_angle, rotation_mode='anchor')

# axis labels
ax.set_ylabel('Relative Error', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.set_ylim(5e-4, 1e0)
ax.legend(loc=3, fontsize=6)

fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.92)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteConvergence.pdf',dpi=80)
Beispiel #17
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)
Beispiel #18
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_neumann_surface.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
Beispiel #19
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_twosphere_dirichlet.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
Beispiel #20
0
res = numpy.array([2.64378e-02, 2.31630e-02, 2.47985e-02, 2.00446e-02, 2.27640e-02, 2.30615e-02, 2.30037e-02, 2.30257e-02])

speedup = t_fixed / t_relax

print(t_relax, t_fixed)
print(speedup)

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.plot(tol,speedup,c='k',marker='o', ls='-', mfc='w', ms=5, label='')

# axis labels
#pyplot.xlim(5, 50)
#pyplot.ylim(1, 4)
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('tolerance', fontsize=10)
ax.set_xscale('log')

pyplot.axhline(y=1.0, linestyle='dashed', color='k')

pyplot.ylim(0,4)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSpeedupTolerance.pdf',dpi=80)
speedup_1st = speedup[:len(speedup)//2]
speedup_2nd = speedup[len(speedup)//2:]

print(speedup_1st, speedup_2nd) # values in table

# set up plot
ind = numpy.arange(len(speedup)/2)
width = 0.35

fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
bar1 = ax.bar(ind, speedup_1st, width, fill=False,
	          edgecolor='k', hatch='..'*2, linewidth=1)
bar2 = ax.bar(ind+width, speedup_2nd, width, fill=False,
	          edgecolor='k', hatch='/'*3, linewidth=1)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('$N$', fontsize=10)
ax.set_xticks(ind+width)
ax.set_xticklabels( ('8192','32768','131072') )
ax.legend((bar1[0], bar2[0]), ('1st-kind', '2nd-kind'),
	      loc='upper left', fontsize='small')
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceSpeedupRelaxation.pdf',dpi=80)
Beispiel #22
0
def store_2ddata(data,
                 fname,
                 pltitle='',
                 dir='./',
                 fits=False,
                 plot=True,
                 plrange=(None, None),
                 log=False,
                 rollaxes=False,
                 cmap='RdYlBu',
                 xlab='X [pix]',
                 ylab='Y [pix]',
                 cbarlab=None,
                 hdr=(),
                 ident=True):
    """
	Store **data** to disk as FITS and/or plot as annotated plot in PDF.

	@param [in] data 2D data array to show
	@param [in] fname Filename base to use (also fallback for plot title)
	@param [in] pltitle Plot title (if given)
	@param [in] dir Output directory
	@param [in] fits Toggle FITS output
	@param [in] plot Toggle 2D plot output as PDF
	@param [in] plrange Use this range for plotting in imshow() (None for autoscale)
	@param [in] log Take logarithm of data before storing.
	@param [in] rollaxes Roll axes for PDF plot such that (0,0) is the center
	@param [in] cmap Colormap to use for PDF
	@param [in] xlab X-axis label
	@param [in] ylab Y-axis label
	@param [in] cbarlab Colorbar label (for units)
	@param [in] hdr Additional FITS header items, give a list of tuples: [(key1, val1), (key2, val2)]
	@param [in] ident Add identification string to plots
	@returns Tuple of (fitsfile path, plotfile path)
	"""

    # Do not store empty data
    if (len(data) <= 0):
        return

    data_arr = np.asanyarray(data)
    if (log):
        data_arr = np.log10(data_arr)
    extent = None
    if (rollaxes):
        sh = data_arr.shape
        extent = (-sh[1] / 2., sh[1] / 2., -sh[0] / 2., sh[0] / 2.)

    # Check if dir exists, or create
    if (not os.path.isdir(dir)):
        os.makedirs(dir)

    fitsfile = filenamify(fname) + '.fits'
    fitspath = os.path.join(dir, fitsfile)
    plotfile = filenamify(fname) + '.pdf'
    plotpath = os.path.join(dir, plotfile)

    if (fits):
        # Generate some metadata. Also store plot settings here
        hdr_dict = dict({
            'filename': fitsfile,
            'desc': fname,
            'title': pltitle,
            'plxlab': xlab,
            'plylab': ylab,
            'pllog': log,
            'plrlxs': rollaxes,
            'plcmap': cmap,
            'plrng0': plrange[0] if plrange[0] else 0,
            'plrng1': plrange[1] if plrange[1] else 0,
        }.items() + dict(hdr).items())
        hdr = mkfitshdr(hdr_dict)
        # Store data to disk
        pyfits.writeto(fitspath,
                       data_arr,
                       header=hdr,
                       clobber=True,
                       checksum=True)

    if (plot):
        #plot_from_fits(fitspath)
        pltit = fname
        if (pltitle):
            pltit = pltitle

        # Plot without GUI, using matplotlib internals
        fig = Figure(figsize=(6, 6))
        ax = fig.add_subplot(111)
        # Make margin smaller
        fig.subplots_adjust(left=0.15, right=0.95, top=0.9, bottom=0.1)
        img = 0
        # Colormaps
        # plus min: cmap=cm.get_cmap('RdYlBu')
        # linear: cmap=cm.get_cmap('YlOrBr')
        # gray: cmap=cm.get_cmap('gray')
        img = ax.imshow(data_arr,
                        interpolation='nearest',
                        cmap=cm.get_cmap(cmap),
                        aspect='equal',
                        extent=extent,
                        vmin=plrange[0],
                        vmax=plrange[1])
        ax.set_title(pltit)
        ax.set_xlabel(xlab)
        ax.set_ylabel(ylab)
        # dimension 0 is height, dimension 1 is width
        # When the width is equal or more than the height, use a horizontal bar, otherwise use vertical
        if (data_arr.shape[0] / data_arr.shape[1] >= 1.0):
            cbar = fig.colorbar(img,
                                orientation='vertical',
                                aspect=30,
                                pad=0.05,
                                shrink=0.8)
        else:
            cbar = fig.colorbar(img,
                                orientation='horizontal',
                                aspect=30,
                                pad=0.12,
                                shrink=0.8)
        if (cbarlab):
            cbar.set_label(cbarlab)

        # Add ID string
        if (ident):
            # Make ID string
            datestr = datetime.datetime.utcnow().isoformat() + 'Z'
            # Put this in try-except because os.getlogin() fails in screen(1)
            try:
                idstr = "%s@%s %s %s" % (os.getlogin(), os.uname()[1], datestr,
                                         sys.argv[0])
            except OSError:
                idstr = "%s@%s %s %s" % (getpass.getuser(), os.uname()[1],
                                         datestr, sys.argv[0])

            ax.text(0.01, 0.01, idstr, fontsize=7, transform=fig.transFigure)

        canvas = FigureCanvas(fig)
        #canvas.print_figure(plotfile, bbox_inches='tight')
        canvas.print_figure(plotpath)

    return (fitspath, plotpath)
Beispiel #23
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_dirichlet_surface.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
t_relax = numpy.array([1.6450, 2.3425, 4.0652, 5.7684, 8.1425, 1.0105e+01, 1.2244e+01])
t_fixed = numpy.array([3.1261, 4.7109, 7.9344, 9.8651, 1.2510e+01, 1.6292e+01, 1.7878e+01])

speedup = t_fixed / t_relax

print(t_relax, t_fixed)
print(speedup)

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.plot(tol,speedup,c='k',marker='o', ls='-', mfc='w', ms=5, label='')

# axis labels
#pyplot.xlim(5, 50)
#pyplot.ylim(1, 4)
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('tolerance', fontsize=10)
ax.set_xscale('log')

pyplot.axhline(y=1.0, linestyle='dashed', color='k')

pyplot.ylim(0,2.5)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceSpeedupTolerance.pdf',dpi=80)
time = numpy.mean(numpy.array(temp).reshape(-1,3), axis=1)

# calculate speedup
speedup = time[::2] / time[1::2]
print("Speedup: ", speedup)
print("fixed-p: ", time[::2])
print("relaxed-p: ", time[1::2])

ind = numpy.arange(len(speedup))
width = 0.3

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot
bar = ax.bar(ind+0.1, speedup, width, fill=False, edgecolor='k', hatch='..'*2, linewidth=1)

# axis labels
ax.set_xticks(ind+0.1+width/2)
ax.set_xlim(-0.4, 3)
ax.set_ylim(0, numpy.ceil(numpy.max(speedup)))
ax.set_xticklabels( ('8192','32768','131072') )
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSpeedupRelaxation.pdf',dpi=80)
xbar = ybar = 0.0
colors = ['#377eb8', '#ff7f00', '#4daf4a']
for th, c in zip(thetas, colors):
    beta = 2*th #  shear phase
    ax1.arrow(0.0, 0.0, length*np.cos(th), length*np.sin(th), width=0.02, head_width=0.02, length_includes_head=True, color=c)
    ax1.arrow(0.0, 0.0, -length*np.cos(th), -length*np.sin(th), width=0.02, head_width=0.02, length_includes_head=True, color=c)
    ax2.arrow(0.0, 0.0, length*np.cos(beta), length*np.sin(beta), width=0.02, head_width=0.1, length_includes_head=True, color=c)
    xbar += np.cos(beta)
    ybar += np.sin(beta)

xbar /= len(thetas)
ybar /= len(thetas)

ax2.arrow(0.0, 0.0, length*xbar, length*ybar, width=0.02, head_width=0.1, color='k')

for ax in [ax1, ax2]:
    ax.set_xlim(-1.2, 1.2)
    ax.set_ylim(-1.2, 1.2)
    ax.axhline(0.0, c='k', lw=0.5)
    ax.axvline(0.0, c='k', lw=0.5)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.add_patch(Ellipse((0.0, 0.0), 2*length, 2*length, fill=False, ec='k'))

ax1.set_title("Headless position angles")
ax2.set_title("Shear phases")

canvas = FigureCanvasPdf(fig)
fig.set_tight_layout(True)
canvas.print_figure("angularSpread.pdf", dpi=100)
Beispiel #27
0
font = {'family': 'serif', 'size': 10}
fig = Figure(figsize=(3, 2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.semilogx(N, speedup, c='k', marker='o', ls='-', mfc='w', ms=5, label='')
rc('font', **font)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSpeedupRelaxation.pdf', dpi=80)

# text on scaling plot
#fig = Figure(figsize=(3,2), dpi=80)
#ax = fig.add_subplot(111)
#asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
#ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
#ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
#loc = (3*N[0]+N[1])/4
#tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
#tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
#ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
#rc('font',**font)
#ax.set_ylabel('Total time [s]', fontsize=10)
#ax.set_xlabel('Number of elements', fontsize=10)
#fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
# set up plot
font = {'family': 'serif', 'size': 10}
fig = Figure(figsize=(3, 2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.loglog(N, e, c='k', marker='o', ls='-', mfc='w', ms=5, label='')
ax.loglog(N, line_sqrtN, c='k', ls='--', mfc='w', ms=5, label='')
rc('font', **font)
loc = (3 * N[0] + N[1]) / 4

# text on plot
# 1 / sqrt(N)
tex_loc = np.array((loc, N[0] * e[0] / loc))
tex_angle = math.atan2(np.log(np.abs(line_sqrtN[-1] - line_sqrtN[0])),
                       np.log(np.abs(N[-1] - N[0]))) * 180 / math.pi
ax.text(tex_loc[0],
        tex_loc[1] / 3.5,
        r'$O(1/\sqrt{N})$',
        fontsize=8,
        rotation=tex_angle - 10,
        rotation_mode='anchor')
# axis labels
ax.set_ylabel('Relative Error', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesConvergence.pdf', dpi=80)
N = 5
t_relax = numpy.array([3.9448, 6.1992, 9.0813, 12.696, 22.055])
t_fixed = numpy.array([7.5261, 12.376, 19.960, 25.412, 37.766])

speedup = t_fixed / t_relax
ind = numpy.arange(N, dtype=int)
width = 0.35

# set up plot
font = {'family':'serif','size':10}
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

print(t_relax,t_fixed)
print(speedup)
# plot log-log
bar1 = ax.bar(ind, t_fixed, width, fill=False, edgecolor='k', hatch='..'*2, linewidth=1)
bar2 = ax.bar(ind+width, t_relax, width, fill=False, edgecolor='k', hatch='/'*4, linewidth=1)

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('p', fontsize=10)
ax.set_xticks(ind+width)
ax.set_xticklabels( ('5','8','10','12','15') )
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
ax.legend( (bar1[0], bar2[0]), ('fixed p', 'Relaxed'), loc=2, fontsize='small' )
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceRelaxationP.pdf',dpi=80)
# plot bars
bar1 = ax.bar(ind, p2p, width, color='r')
bar2 = ax.bar(ind+width, m2l, width, color='b')
rc('font',**font)

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('Iteration', fontsize=10)
xticks(arange(min(ind), max(ind)+1, 5.0))
# ax.set_xticklabels( ('8192','32768','131072') )
ax.legend( (bar1[0], bar2[0]), ('P2P', 'M2L'), loc=1 )
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSolveBreakdown.pdf',dpi=80)

# text on scaling plot
#fig = Figure(figsize=(3,2), dpi=80)
#ax = fig.add_subplot(111)
#asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
#ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
#ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
#loc = (3*N[0]+N[1])/4
#tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
#tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
#ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
#rc('font',**font)
#ax.set_ylabel('Total time [s]', fontsize=10)
#ax.set_xlabel('Number of elements', fontsize=10)
#fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
Beispiel #31
0
fig = pyplot.figure(figsize=(9, 4), dpi=80)
ax = fig.add_subplot(111)

# plot bars
bar1 = ax.bar(ind,
              p2p,
              width,
              fill=False,
              edgecolor='k',
              hatch='.' * 3,
              linewidth=1)
bar2 = ax.bar(ind + width,
              m2l,
              width,
              fill=False,
              edgecolor='k',
              hatch='/' * 10,
              linewidth=1)

# axis labels
ax.set_ylabel('Time (s)', fontsize=14)
ax.set_xlabel('Iteration', fontsize=14)
pyplot.xticks(numpy.arange(min(ind), max(ind), 5.0))
ax.legend((bar1[0], bar2[0]), ('P2P', 'M2L'), loc=1, fontsize=10)

fig.subplots_adjust(left=0.065, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSolveBreakdown.pdf', dpi=80)
Beispiel #32
0
def plotAllPolygons(tri, polyPoints, xRange, yRange):
    """docstring for plotAllPolygons"""
    fig = Figure(figsize=(4,4))
    canvas = FigureCanvas(fig)
    fig.subplots_adjust(left=0.15, bottom=0.13,wspace=0.25, right=0.95)
    ax = fig.add_subplot(111, aspect='equal')
    
    ax.plot(tri.x, tri.y, '.k', ms=2)
    for nodeID, points in polyPoints.iteritems():
        patch = matplotlib.patches.Polygon(points, closed=True, fill=False, lw=1)
        ax.add_patch(patch)
    
    ax.plot(tri.x[tri.hull], tri.y[tri.hull], '.r', ms=3)
    for edge in tri.edge_db:
        p1 = (tri.x[edge[0]], tri.y[edge[0]])
        p2 = (tri.x[edge[1]], tri.y[edge[1]])
        patch = matplotlib.patches.Polygon((p1,p2), lw=0.5, color='g', zOrder=1000)
        ax.add_patch(patch)
    
    pHull = []
    for ii in tri.hull:
        pHull.append((tri.x[ii],tri.y[ii]))
    patch = matplotlib.patches.Polygon(pHull, closed=True, fill=False, lw=0.8, color='b')
    ax.add_patch(patch)
    
    # for iNode in tri.hull:
        # print "Lead:"
        # leadingNode = getLeadingNode(iNode, tri)
        # pcLead = getCircumcentreOfCommonTriangle(iNode, leadingNode, tri)
        # print pcLead
        # pdLead = makeExteriorPoint(iNode, leadingNode, pcLead, tri, xRange, yRange)
        # print pdLead
        # 
        # # print "Trail:"
        # # trailingNode = getTrailingNode(iNode, tri)
        # # pcTrail = getCircumcentreOfCommonTriangle(iNode, trailingNode, tri)
        # # pdTrail = makeExteriorPoint(iNode, trailingNode, pcTrail, tri, xRange, yRange)
        # 
        # # Get coordinates of the two points that define convex hull line seg
        # p1 = (tri.x[iNode], tri.y[iNode])
        # p2 = (tri.x[leadingNode], tri.y[leadingNode])
        # # Get slope of that line
        # m = (p2[1]-p1[1]) / (p2[0]-p1[0])
        # # Get perpendicular slope; that of the voronoi cell edge
        # mPerp = -1./m
        # print "mPerp plot %.2f" % mPerp
        # xt = numpy.linspace(min(xRange), max(xRange), 100)
        # yt = mPerp*(xt-pcLead[0]) + pcLead[1]
        # ax.plot(xt, yt, '--m')
        # 
        # # Get the point pi where the voronoi cell line intersects the convex hull line
        # xi = (pcLead[1]-p1[1] + m*p1[0] - mPerp*pcLead[0]) / (m - mPerp)
        # yi = m * (xi - p1[0]) + p1[1]
        # ax.plot([xi], [yi], 'xm', ms=5, zorder=1000)
        # 
        # ax.plot(tri.x[iNode], tri.y[iNode], 'oy', ms=4, zorder=1000)
        # ax.plot([pcLead[0]], [pcLead[1]], 'om', ms=5, zorder=1000)
        # ax.plot([pcLead[0],pdLead[0]], [pcLead[1],pdLead[1]], '-mo')
        # # ax.plot([pcTrail[0]], [pcTrail[1]], '+c', ms=7, zorder=1100)
        # break
    for iNode in xrange(len(tri.x)):
        patch = matplotlib.patches.Polygon(polyPoints[iNode], closed=True, fill=True, lw=0.5)
        ax.add_patch(patch)
    
    width = xRange[1]-xRange[0]
    height = yRange[1]-yRange[0]
    ax.set_xlim(xRange[0]-0.25*width, xRange[1]+0.25*width)
    ax.set_ylim(yRange[0]-0.25*height, yRange[1]+0.25*height)
    canvas.print_figure("cell", dpi=300.)
ax = fig.add_subplot(111)

# plot log-log
line1 = ax.semilogy(it1,
                    r,
                    c='k',
                    marker='',
                    ls='-',
                    mfc='w',
                    ms=5,
                    label='Fixed p')
line2 = ax.semilogy(it2,
                    r2,
                    c='k',
                    marker='',
                    ls=':',
                    mfc='w',
                    ms=5,
                    label='Relaxed')
rc('font', **font)

# axis labels
ax.set_ylabel('Residual', fontsize=10)
ax.set_xlabel('Iteration', fontsize=10)
ax.legend((line1, line2), ('Fixed p', 'Relaxed'))
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesResidualHistory.pdf', dpi=80)
    1.770e-05, 1.462e-05, 1.367e-05, 1.137e-05, 1.054e-05, 9.2166e-06])

r2 = array([1.985e-03, 4.820e-04, 3.696e-04, 2.394e-04, 1.812e-04, 1.708e-04, 1.423e-04,
    1.366e-04, 1.242e-04, 1.111e-04, 9.853e-05, 8.041e-05, 6.692e-05, 5.988e-05,
    4.896e-05, 4.433e-05, 3.768e-05, 3.500e-05, 2.768e-05, 2.620e-05, 2.231e-05,
    1.997e-05, 1.744e-05, 1.623e-05, 1.419e-05, 1.245e-05, 1.006e-05, 8.2839e-06])

it1 = arange(size(r))
it2 = arange(size(r2))

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
line1 = ax.semilogy(it1,r,c='k',marker='', ls='-', mfc='w', ms=5, label='Fixed p')
line2 = ax.semilogy(it2,r2,c='k',marker='', ls=':', mfc='w', ms=5, label='Relaxed')
rc('font',**font)

# axis labels
ax.set_ylabel('Residual', fontsize=10)
ax.set_xlabel('Iteration', fontsize=10)
ax.legend( (line1, line2), ('Fixed p', 'Relaxed') )
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesResidualHistory.pdf',dpi=80)

speedup = data_fixed / data_relax

print speedup

ind = arange(N)
width = 0.3

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(4,3), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
bar1 = ax.bar(ind, speedup[:,0], width, color='r')
bar2 = ax.bar(ind+width, speedup[:,1],width,color='b')
bar3 = ax.bar(ind+2*width,speedup[:,2],width,color='g')
# bar2 = ax.bar(ind+width, speedup_2nd, width, color='b')
rc('font',**font)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.set_xticks(ind+1.5*width)
ax.set_xticklabels( ('2048','8192','32768','131072') )
ax.legend( (bar1[0], bar2[0], bar3[0]), ('2048 panels/cell', '8192 panels/cell', '32768 panels/cell'), loc=2 )
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteMultipleCellSpeedup.pdf',dpi=80)
Beispiel #36
0
def store_2ddata(data, fname, pltitle='', dir='./', fits=False, plot=True, plrange=(None, None), log=False, rollaxes=False, cmap='RdYlBu', xlab='X [pix]', ylab='Y [pix]', cbarlab=None, hdr=(), ident=True):
	"""
	Store **data** to disk as FITS and/or plot as annotated plot in PDF.

	@param [in] data 2D data array to show
	@param [in] fname Filename base to use (also fallback for plot title)
	@param [in] pltitle Plot title (if given)
	@param [in] dir Output directory
	@param [in] fits Toggle FITS output
	@param [in] plot Toggle 2D plot output as PDF
	@param [in] plrange Use this range for plotting in imshow() (None for autoscale)
	@param [in] log Take logarithm of data before storing.
	@param [in] rollaxes Roll axes for PDF plot such that (0,0) is the center
	@param [in] cmap Colormap to use for PDF
	@param [in] xlab X-axis label
	@param [in] ylab Y-axis label
	@param [in] cbarlab Colorbar label (for units)
	@param [in] hdr Additional FITS header items, give a list of tuples: [(key1, val1), (key2, val2)]
	@param [in] ident Add identification string to plots
	@returns Tuple of (fitsfile path, plotfile path)
	"""

	# Do not store empty data
	if (len(data) <= 0):
		return

	data_arr = np.asanyarray(data)
	if (log):
		data_arr = np.log10(data_arr)
	extent = None
	if (rollaxes):
		sh = data_arr.shape
		extent = (-sh[1]/2., sh[1]/2., -sh[0]/2., sh[0]/2.)

	# Check if dir exists, or create
	if (not os.path.isdir(dir)):
		os.makedirs(dir)

	fitsfile = filenamify(fname)+'.fits'
	fitspath = os.path.join(dir, fitsfile)
	plotfile = filenamify(fname)+'.pdf'
	plotpath = os.path.join(dir, plotfile)

	if (fits):
		# Generate some metadata. Also store plot settings here
		hdr_dict = dict({'filename':fitsfile, 
				'desc':fname, 
				'title':pltitle,
				'plxlab': xlab,
				'plylab': ylab,
				'pllog': log,
				'plrlxs': rollaxes,
				'plcmap': cmap,
				'plrng0': plrange[0] if plrange[0] else 0,
				'plrng1': plrange[1] if plrange[1] else 0,
				}.items()
				+ dict(hdr).items())
		hdr = mkfitshdr(hdr_dict)
		# Store data to disk
		pyfits.writeto(fitspath, data_arr, header=hdr, clobber=True, checksum=True)

	if (plot):
		#plot_from_fits(fitspath)
		pltit = fname
		if (pltitle):
			pltit = pltitle

		# Plot without GUI, using matplotlib internals
		fig = Figure(figsize=(6,6))
		ax = fig.add_subplot(111)
		# Make margin smaller
		fig.subplots_adjust(left=0.15, right=0.95, top=0.9, bottom=0.1)
		img=0
		# Colormaps
		# plus min: cmap=cm.get_cmap('RdYlBu')
		# linear: cmap=cm.get_cmap('YlOrBr')
		# gray: cmap=cm.get_cmap('gray')
		img = ax.imshow(data_arr, interpolation='nearest', cmap=cm.get_cmap(cmap), aspect='equal', extent=extent, vmin=plrange[0], vmax=plrange[1])
		ax.set_title(pltit)
		ax.set_xlabel(xlab)
		ax.set_ylabel(ylab)
		# dimension 0 is height, dimension 1 is width
		# When the width is equal or more than the height, use a horizontal bar, otherwise use vertical
		if (data_arr.shape[0]/data_arr.shape[1] >= 1.0):
			cbar = fig.colorbar(img, orientation='vertical', aspect=30, pad=0.05, shrink=0.8)
		else:
			cbar = fig.colorbar(img, orientation='horizontal', aspect=30, pad=0.12, shrink=0.8)
		if (cbarlab):
			cbar.set_label(cbarlab)

		# Add ID string
		if (ident):
			# Make ID string
			datestr = datetime.datetime.utcnow().isoformat()+'Z'
			# Put this in try-except because os.getlogin() fails in screen(1)
			try:
				idstr = "%s@%s %s %s" % (os.getlogin(), os.uname()[1], datestr, sys.argv[0])
			except OSError:
				idstr = "%s@%s %s %s" % (getpass.getuser(), os.uname()[1], datestr, sys.argv[0])

			ax.text(0.01, 0.01, idstr, fontsize=7, transform=fig.transFigure)

		canvas = FigureCanvas(fig)
		#canvas.print_figure(plotfile, bbox_inches='tight')
		canvas.print_figure(plotpath)

	return (fitspath, plotpath)
Beispiel #37
0
# plot log-log
bar1 = ax.bar(ind, speedup_1st, width, color='r')
bar2 = ax.bar(ind + width, speedup_2nd, width, color='b')
rc('font', **font)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.set_xticks(ind + width)
ax.set_xticklabels(('8192', '32768', '131072'))
ax.legend((bar1[0], bar2[0]), ('1st-kind', '2nd-kind'), loc=4)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceSpeedupRelaxation.pdf', dpi=80)

# text on scaling plot
#fig = Figure(figsize=(3,2), dpi=80)
#ax = fig.add_subplot(111)
#asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
#ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
#ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
#loc = (3*N[0]+N[1])/4
#tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
#tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
#ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
#rc('font',**font)
#ax.set_ylabel('Total time [s]', fontsize=10)
#ax.set_xlabel('Number of elements', fontsize=10)
#fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
Beispiel #38
0
N = array([512, 2048, 8192, 32768])
e = array([0.2893, 0.1439, 0.0716, 0.0345])

line_sqrtN = 1 / np.sqrt(N)

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.loglog(N,e,c='k',marker='o', ls='-', mfc='w', ms=5, label='')
ax.loglog(N,line_sqrtN,c='k',ls='--', mfc='w', ms=5, label='')
rc('font',**font)
loc = (3*N[0]+N[1])/4

# text on plot
# 1 / sqrt(N)
tex_loc = np.array((loc,N[0]*e[0]/loc))
tex_angle = math.atan2(np.log(np.abs(line_sqrtN[-1]-line_sqrtN[0])),np.log(np.abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1]/3.5,r'$O(1/\sqrt{N})$',fontsize=8,rotation=tex_angle, rotation_mode='anchor')
# axis labels
ax.set_ylabel('Relative Error', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteConvergence.pdf',dpi=80)

Beispiel #39
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_molecule_neumann.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
dy = np.random.uniform(0.75, 1, len(x))
y = model + np.random.normal(scale=dy)

#$ begin makeFigure
fig = matplotlib.figure.Figure()
#$end

#$ begin plot_axes_sin
axes = fig.add_axes((0.1, 0.1, 0.85, 0.80))

# plot the data
axes.plot(x, y, "b.", label="My data points")
axes.errorbar(x, y, xerr=None, yerr=dy, fmt=None, color='b')
axes.plot(x, model, "r:", label="Model")

# axis limits
axes.set_xlim(-1, 10)

# labels
axes.set_xlabel("x")
axes.set_ylabel("y")
axes.set_title("Clever Title")
#$ end

#$ begin plotToCanvas
from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigCanvas

canvas = FigCanvas(fig)
canvas.print_figure("foo.png")  # a PNG file this time
#$ end
Beispiel #41
0
import os
import numpy as np
from numpy import *
from matplotlib import *
from matplotlib.pyplot import *
from matplotlib.backends.backend_pdf import PdfFile, PdfPages, FigureCanvasPdf
import sys
import math

# set up data
N = array([128, 512, 2048, 8192, 32768, 32768 * 4])
it = array([19, 24, 32, 37, 37, 36])

# set up plot
font = {'family': 'serif', 'size': 10}
fig = Figure(figsize=(3, 2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.semilogx(N, it, c='k', marker='o', ls='-', mfc='w', ms=5, label='')
rc('font', **font)

# axis labels
ax.set_ylabel('Iterations', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteSingleCellIterations.pdf', dpi=80)
Beispiel #42
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)
              linewidth=1)
bar2 = ax.bar(ind + width,
              s_8192,
              width,
              fill=False,
              edgecolor='k',
              hatch='//' * 2,
              linewidth=1)
bar3 = ax.bar(ind + 2 * width,
              s_32768,
              width,
              fill=False,
              edgecolor='k',
              hatch='x' * 3,
              linewidth=1)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.set_xticks(ind + 1.5 * width)
ax.set_xticklabels(('2048', '8192', '32768', '131072'))
ax.legend((bar1[0], bar2[0], bar3[0]),
          ('2048 panels/cell', '8192 panels/cell', '32768 panels/cell'),
          loc=2,
          fontsize='small')
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteMultipleCellSpeedup.pdf', dpi=80)
Beispiel #44
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 #45
0
r = array([
    1.016e-02, 2.123e-03, 6.290e-04, 2.550e-04, 1.638e-04, 1.247e-04,
    8.260e-05, 7.000e-05, 4.220e-05, 2.883e-05, 2.372e-05, 1.888e-05,
    1.394e-05, 1.168e-05, 9.4244e-06
])

it = size(p)
ind = arange(it)

# set up plot
font = {'family': 'serif', 'size': 10}
fig = Figure(figsize=(3.7, 2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.semilogy(ind, r, c='k', marker='', ls='-', mfc='w', ms=5, label='')
rc('font', **font)

ax2 = ax.twinx()
ax2.plot(ind, p, c='k', marker='o', ls=':', mfc='w', ms=5, label='')

# axis labels
ax.set_ylabel('Residual', fontsize=10)
ax.set_xlabel('Iterations', fontsize=10)
ax2.set_ylabel('p', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceResidualIterations.pdf', dpi=80)
Beispiel #46
0
rc('font',**font)
loc = (3*N[0]+N[1])/4

# text of plot
tex_loc = array((loc,N[0]*t[0]/loc))
tex_angle = math.atan2(log(abs(N[-1]/10000-N[0]/10000)),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], 6.5*tex_loc[1],r'$O(N)$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('FMMScaling.pdf',dpi=80)

# text on scaling plot
#fig = Figure(figsize=(3,2), dpi=80)
#ax = fig.add_subplot(111)
#asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
#ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
#ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
#loc = (3*N[0]+N[1])/4
#tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
#tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
#ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
#rc('font',**font)
#ax.set_ylabel('Total time [s]', fontsize=10)
#ax.set_xlabel('Number of elements', fontsize=10)
#fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
           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 #48
0
t_fixed = numpy.array(
    [3.1261, 4.7109, 7.9344, 9.8651, 1.2510e+01, 1.6292e+01, 1.7878e+01])

speedup = t_fixed / t_relax

print(t_relax, t_fixed)
print(speedup)

# set up plot
fig = pyplot.figure(figsize=(3, 2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.plot(tol, speedup, c='k', marker='o', ls='-', mfc='w', ms=5, label='')

# axis labels
#pyplot.xlim(5, 50)
#pyplot.ylim(1, 4)
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('tolerance', fontsize=10)
ax.set_xscale('log')

pyplot.axhline(y=1.0, linestyle='dashed', color='k')

pyplot.ylim(0, 2.5)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceSpeedupTolerance.pdf', dpi=80)