Esempio n. 1
0
def plot_factor_in_subtype(cad_factors, factor_id, factor_annotation,
                           clinical_annotation, clinical_var, out, stats_out):
    factor_da = xr.open_dataset(cad_factors)['factors']
    with open(factor_annotation) as f:
        factor_index = only(
            [i for i, v in yaml.load(f).items() if v['id'] == factor_id])
    factor = factor_da.sel(factor=factor_index).load()
    factor.name = factor_id

    clin = xr.open_dataset(clinical_annotation)[clinical_var].load()
    factor, clin = xr.align(factor[factor.notnull()], clin[clin.notnull()])

    with plot.subplots(figsize=(3.5, 3.5)) as (fig, ax):
        plot.boxplot(
            clin,
            factor,
            title="",
            xlabel=clin_display_names[clinical_var],
            ylabel=f"Factor {factor_index+1}",
            ax=ax,
        )
        fig.savefig(out, format='svg')

    factor_by_clin = split_by(factor.values, clin.values)
    h, p = scipy.stats.kruskal(*factor_by_clin.values())
    with open(stats_out, 'w') as f:
        f.write(f"h: {h:.6e}\n")
        f.write(f"p: {p:.6e}\n")
Esempio n. 2
0
def plot_fa_variance_explained(mri_features, out):
    mri_data_set = xr.open_dataset(mri_features).load()
    mri = read_mri(mri_data_set)
    mri = adjust_scale(mri)

    pca = sklearn.decomposition.PCA()
    mri_a = (mri / mri.std('case')).values
    pca.fit(mri_a)

    total_var = np.sum(pca.explained_variance_)

    with plot.subplots(3, 1, sharex=True, figsize=(3, 3)) as (fig, axs):

        axs[0].plot(
            range(1,
                  len(pca.explained_variance_) + 1),
            100 * np.cumsum(pca.explained_variance_) / total_var,
            clip_on=False,
            zorder=100,
        )
        axs[0].set_ylim(top=100.0)
        axs[0].set_ylabel("$\Sigma$EV (%)")
        axs[1].plot(
            range(1,
                  len(pca.explained_variance_) + 1),
            100 * pca.explained_variance_ / total_var,
            clip_on=False,
            zorder=100,
        )
        axs[1].set_ylim(bottom=0.0)
        axs[1].set_ylabel("EV (%)")
        axs[2].plot(
            range(2,
                  len(pca.explained_variance_) + 1),
            100 *
            abs(pca.explained_variance_[1:] - pca.explained_variance_[:-1]) /
            total_var,
            clip_on=False,
            zorder=100,
        )
        axs[2].set_ylim(bottom=0.0)
        axs[2].set_ylabel("$\Delta$EV (%)")

        for ax in axs:
            ax.spines['right'].set_visible(False)
            ax.spines['top'].set_visible(False)
            ax.spines['left'].set_position(('outward', 10))
            ax.axvline(7, ls='-', lw=0.5, color='grey')

        axs[2].set_xlabel("Principal Component")
        axs[2].set_xlim(1, len(pca.explained_variance_))
        axs[2].set_xticks([1, 6, 11, 16, 21])
        axs[2].set_xticks([7], minor=True)
        axs[0].set_xticklabels('', minor=True)
        axs[1].set_xticklabels('', minor=True)
        axs[2].set_xticklabels(['7'], {'fontsize': 8}, minor=True)

        fig.savefig(out, format="svg")
def plot_mri_cad_factor_correlation(mri_features, out):
    mri_ds = xr.open_dataset(mri_features)
    del mri_ds['Comment']
    del mri_ds['MultiFocal']
    mri = mri_ds.to_array('cad_feature', 'mri_cad_features')
    mri_ds.close()
    mri = mri.isel(case=np.where(mri.isnull().sum('cad_feature') == 0)[0])
    mri = mri.transpose('case', 'cad_feature')

    assert all(f.item() in feature_order for f in mri['cad_feature'].values)
    mri = mri.reindex(cad_feature=feature_order)

    cor = xr.DataArray(
        data=np.corrcoef(mri.values, rowvar=False),
        dims=('cad_feature', 'cad_feature'),
        coords={'cad_feature': mri.coords['cad_feature']},
    )
    cor.name = 'correlation'

    with plot.subplots(figsize=(3.5, 3.5)) as (fig, ax):
        c = plot.heatmap(
            cor,
            mask=np.tri(cor.shape[0]) < 0.5,
            aspect='equal',
            xlabel="MR Feature",
            ylabel="MR Feature",
            xticklabels=[''] * cor.shape[0],
            yticklabels=[
                feature_display_names[f]
                for f in cor.coords['cad_feature'].values
            ],
            cbar=False,
            ax=ax,
        )
        cax = fig.add_axes([.7, .5, .05, .25])
        cbar = fig.colorbar(c, cax=cax)
        cbar.set_ticks([-1.0, -0.5, 0.0, 0.5, 1.0])
        cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=9)
        cbar.ax.set_title("Pearson Correlation", fontsize=10)
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        fig.savefig(out, format="svg")
Esempio n. 4
0
def plot_mri_cad_factors(cad_factors, out):
    fa_dataset = xr.open_dataset(cad_factors).load()

    assert all(f in feature_order for f in fa_dataset['cad_feature'].values)
    fa_dataset = fa_dataset.reindex(cad_feature=feature_order)

    with plot.subplots(figsize=(3.5, 3.5)) as (fig, ax):
        plot.heatmap(
            fa_dataset['loadings'].T,
            aspect='equal',
            xlabel="MRI Factor",
            ylabel="MRI Feature",
            yticklabels=[
                feature_display_names[f]
                for f in fa_dataset.coords['cad_feature'].values
            ],
            zlabel="Loading",
            ax=ax,
        )

        fig.savefig(out, format="svg")
Esempio n. 5
0
def plot_factor_in_subtype(mri_features, feature_id, clinical_annotation,
                           clinical_var, out, stats_out):
    mri_ds = xr.open_dataset(mri_features)
    feature = mri_ds[feature_id]

    clin = xr.open_dataset(clinical_annotation)[clinical_var].load()
    feature, clin = xr.align(feature[feature.notnull()], clin[clin.notnull()])

    with plot.subplots(figsize=(3.5, 3.5)) as (fig, ax):
        plot.boxplot(
            clin,
            feature,
            title="",
            xlabel=clin_display_names[clinical_var],
            ylabel=feature_display_names[feature_id],
            ax=ax,
        )
        fig.savefig(out, format='svg')

    feature_by_clin = split_by(feature.values, clin.values)
    h, p = scipy.stats.kruskal(*feature_by_clin.values())
    with open(stats_out, 'w') as f:
        f.write(f"h: {h:.6e}\n")
        f.write(f"p: {p:.6e}\n")
def megaplot(ctsets,studyname,emisfops=None,labels=["$10^9$","$10^8$","$10^7$","$10^6$"],axlabel='Primaries [nr]'):

	if len(ctsets) == 4:
		f, ((ax1,ax2),(ax3,ax4)) = plot.subplots(nrows=2, ncols=2, sharex=False, sharey=False)

		auger.plot_all_ranges_CTONLY(ax1,ctsets[0])
		auger.plot_all_ranges_CTONLY(ax2,ctsets[1])
		auger.plot_all_ranges_CTONLY(ax3,ctsets[2])
		auger.plot_all_ranges_CTONLY(ax4,ctsets[3])
		if not 'Primaries' in axlabel:
			ax1.set_title(labels[0])
			ax2.set_title(labels[1])
			ax3.set_title(labels[2])
			ax4.set_title(labels[3])
		f.subplots_adjust(hspace=.5)
		ax1.set_xlabel('')
		ax2.set_xlabel('')
		ax2.set_ylabel('')
		ax4.set_ylabel('')
		f.savefig(studyname+'-'+typ+'-FOP.pdf', bbox_inches='tight')
		plot.close('all')

	#############################################################################################

	# print 'FOP shift distributions'

	# from mpl_toolkits.mplot3d import Axes3D
	# import matplotlib.pyplot as plt

	# fig = plt.figure()
	# ax1 = plt.axes(projection='3d')
	# ax1.view_init(30, -50)

	# for i,ctset in enumerate(ctsets):
	# 	auger.plotfodiffdist(ax1,ctset,i,emisfops,labels,axlabel)
	# 	if not emisfops == None:
	# 		fopshifts=[]
	# 		for fopset in emisfops:
	# 			fopshifts.append( fopset[-1]-fopset[0] )
	# 		ax1.set_xlim3d(np.mean(fopshifts)-20,np.mean(fopshifts)+20)
	# if emisfops is not None and len(emisfops) == 1:
	# 	ax1.set_title(studyname+', $Shift_{em}$ = '+str(emisfops[0][-1]-emisfops[0][0]), y=1.08)

	# #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
	# fig.savefig(studyname+'-'+typ+'-FOP-shift.pdf')#, bbox_inches='tight')
	# plt.close('all')


	#############################################################################################

	# print 'FOP FOW Contrast DE averages over 10e9 ctset'
	
	f, (ax1,ax2,ax3) = plot.subplots(nrows=3, ncols=1, sharex=False, sharey=False)
	x=ctsets[0]['ct']['x']
	y=ctsets[0]['ct']['av']
	if 'iba' in ctsets[0]['name']: # ctset['name'] == typ
		mm=4/0.8
	if 'ipnl' in ctsets[0]['name']:
		mm=8
	falloff_pos,g_fwhm,contrast = auger.get_fop_fow_contrast(x,y,plot='wut',ax=ax1,ax2=ax2,ax3=ax3,smooth=0.2,filename=ctsets[0]['ct']['path'],contrast_divisor=ctsets[0]['nprim']*len(ctsets[0]['ct']['files'])*mm)
	print "NPRIM", ctsets[0]['nprim'],"NJOBS",len(ctsets[0]['ct']['files']),"MM",mm

	#gebruiken deze falloff_pos niet. we doen contrast en fow over de average van 50 batches wegens smoothe curve. daardoor geen sigma
	
	res=[typ,ctsets[0]['ct']['fopmu'],ctsets[0]['ct']['fopsigma'],g_fwhm,contrast,ctsets[0]['detyieldmu'],ctsets[0]['detyieldsigma']]
	
	resultstable.append(res)
	
	f.savefig(studyname+'-'+typ+'-FOW.pdf', bbox_inches='tight')
	plot.close('all')
	
	#############################################################################################

	from mpl_toolkits.mplot3d import Axes3D
	import matplotlib.pyplot as plt

	print 'FOP distributions'

	fig = plt.figure()
	ax1 = plt.axes(projection='3d')
	ax1.view_init(30, -50)

	for i,ctset in enumerate(ctsets):
		auger.plotfodist_CTONLY(ax1,ctset,i,emisfops,labels,axlabel)
	if emisfops is not None and len(emisfops) == 1:
		ax1.set_title(studyname+', $CT_{FOP_{em}}$ = '+str(emisfops[0][0])[:5]+', $RPCT_{FOP_{em}}$ = '+str(emisfops[0][1])[:5], y=1.08)

	#plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

	#plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
	plt.savefig(studyname+'-'+typ+'-FOP-dist.pdf')#, bbox_inches='tight')
	plt.close('all')
    #res = [3.13,2.18]
    #yerr = [1.16,0.89]
    labels = ["Iso-energy","Iso-depth"]
    ind = np.arange(len(res))
    margin = 0.2
    width = (1.-2.*margin)
    xdata = ind-width/2.
    ax.bar(xdata, res, width, yerr=yerr,color='k',ecolor='k',lw=0,fill=False)#,capsize=5)#, markeredgewidth=1)
    #ax.bar(xdata, res, width, yerr=yerr, xerr=0.03,color='k',ecolor='k',lw=0,fill=False)
    ax.errorbar(xdata+width/2.,res,yerr=yerr,color='black',fmt='.',lw=1,capsize=5, markeredgewidth=1)
    ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(range(len(res))))
    #ax.set_xticklabels(['']+labels, fontsize=8, rotation=15, ha='center')
    ax.set_xticklabels(labels, fontsize=8, rotation=15, ha='center')

# MPS, KES, (ABC)
f, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)

#Dose & 2.47 & 1.60 & 6.40 & 4.07 & 6.40 & 6.40
ax1.axhline(2.47, xmin= 0, xmax=0.5 , color='indianred', ls='-',lw=1)#, alpha=0.5)
ax1.axhline(1.60, xmin= 0.5, xmax=1 , color='indianred', ls='-',lw=1)#, alpha=0.5)

ax2.axhline(6.40, xmin= 0, xmax=0.5 , color='indianred', ls='-',lw=1)#, alpha=0.5)
ax2.axhline(4.07, xmin= 0.5, xmax=1 , color='indianred', ls='-',lw=1)#, alpha=0.5)

ax3.axhline(6.40, xmin= 0, xmax=0.5 , color='indianred', ls='-',lw=1)#, alpha=0.5)
ax3.axhline(6.40, xmin= 0.5, xmax=1 , color='indianred', ls='-',lw=1)#, alpha=0.5)

ax4.axhline(2.47, xmin= 0, xmax=0.5 , color='indianred', ls='-',lw=1)#, alpha=0.5)
ax4.axhline(1.60, xmin= 0.5, xmax=1 , color='indianred', ls='-',lw=1)#, alpha=0.5)

ax5.axhline(6.40, xmin= 0, xmax=0.5 , color='indianred', ls='-',lw=1)#, alpha=0.5)
Esempio n. 8
0
for i, spot in enumerate(data):
    #if i == 61:
    #dose3dCT.imdata = spot*mask
    #dose3dCT.imdata = dose3dCT.imdata.astype(np.float32,copy=False)
    #dose3dCT.saveas('TEST')
    rmse.append(np.sqrt(np.mean(np.square(spot * mask))))
    #rmse.append(np.sqrt(np.mean(np.square(spot))))
    nprim.append(newspots[i][4])
    E.append(newspots[i][1])

Eh, Ehbin = np.histogram(E, bins=30)
nprimh, nprimhbin = plot.getloghist(nprim, 30)

f, ((ax1, ax2), (ax3, ax4)) = plot.subplots(nrows=2,
                                            ncols=2,
                                            sharex=False,
                                            sharey=False)

ax1.set_title('Dose Diff (nprim)')
ax1.set_xlabel('Number of Primaries')
ax1.set_ylabel('Dose Diff [RMSE]')
plot.texax(ax1)

ax2.set_title('Dose Diff (E)')
ax2.set_xlabel('Energy [MeV]')
ax2.set_ylabel('Dose Diff [RMSE]')
plot.texax(ax2)

ax3.set_title('Dose Diff (nprim)')
ax3.set_xlabel('Number of Primaries')
ax3.set_ylabel('Dose Diff [RMSE]')
def megaplot(ctsets,
             studyname,
             emisfops=None,
             labels=["$10^9$", "$10^8$", "$10^7$", "$10^6$"],
             axlabel='Primaries [nr]'):

    if len(ctsets) == 4:
        f, ((ax1, ax2), (ax3, ax4)) = plot.subplots(nrows=2,
                                                    ncols=2,
                                                    sharex=False,
                                                    sharey=False)

        auger.plot_all_ranges_CTONLY(ax1, ctsets[0])
        auger.plot_all_ranges_CTONLY(ax2, ctsets[1])
        auger.plot_all_ranges_CTONLY(ax3, ctsets[2])
        auger.plot_all_ranges_CTONLY(ax4, ctsets[3])
        if not 'Primaries' in axlabel:
            ax1.set_title(labels[0])
            ax2.set_title(labels[1])
            ax3.set_title(labels[2])
            ax4.set_title(labels[3])
        f.subplots_adjust(hspace=.5)
        ax1.set_xlabel('')
        ax2.set_xlabel('')
        ax2.set_ylabel('')
        ax4.set_ylabel('')
        f.savefig(studyname + '-' + typ + '-FOP.pdf', bbox_inches='tight')
        plot.close('all')

    #############################################################################################

    # print 'FOP shift distributions'

    # from mpl_toolkits.mplot3d import Axes3D
    # import matplotlib.pyplot as plt

    # fig = plt.figure()
    # ax1 = plt.axes(projection='3d')
    # ax1.view_init(30, -50)

    # for i,ctset in enumerate(ctsets):
    # 	auger.plotfodiffdist(ax1,ctset,i,emisfops,labels,axlabel)
    # 	if not emisfops == None:
    # 		fopshifts=[]
    # 		for fopset in emisfops:
    # 			fopshifts.append( fopset[-1]-fopset[0] )
    # 		ax1.set_xlim3d(np.mean(fopshifts)-20,np.mean(fopshifts)+20)
    # if emisfops is not None and len(emisfops) == 1:
    # 	ax1.set_title(studyname+', $Shift_{em}$ = '+str(emisfops[0][-1]-emisfops[0][0]), y=1.08)

    # #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    # fig.savefig(studyname+'-'+typ+'-FOP-shift.pdf')#, bbox_inches='tight')
    # plt.close('all')

    f, (ax1, ax2, ax3) = plot.subplots(nrows=3,
                                       ncols=1,
                                       sharex=False,
                                       sharey=False)

    x = ctsets[0]['rpct']['x']
    y = ctsets[0]['ct']['av']
    auger.get_fow(x,
                  y,
                  plot='wut',
                  ax=ax1,
                  ax2=ax2,
                  ax3=ax3,
                  smooth=0.2,
                  filename=ctsets[0]['ct']
                  ['path'])  #since high statistics, no smoothing needed
    # ax1.set_title('FOP = '+str(falloff_pos), fontsize=8)
    f.savefig(studyname + '-' + typ + '-FOW.pdf', bbox_inches='tight')
    plot.close('all')

    #############################################################################################

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    print 'FOP distributions'

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    for i, ctset in enumerate(ctsets):
        auger.plotfodist_CTONLY(ax1, ctset, i, emisfops, labels, axlabel)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname + ', $CT_{FOP_{em}}$ = ' +
                      str(emisfops[0][0])[:5] + ', $RPCT_{FOP_{em}}$ = ' +
                      str(emisfops[0][1])[:5],
                      y=1.08)

    #plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    plt.savefig(studyname + '-' + typ +
                '-FOP-dist.pdf')  #, bbox_inches='tight')
    plt.close('all')
Esempio n. 10
0
def fieldseries(df, fname):
    assert (isinstance(df, pd.DataFrame))

    sns.set_style(style="whitegrid")
    sns.set(font_scale=1.1)
    f, ((ax1, ax2), (ax3, ax4)) = plot.subplots(nrows=2,
                                                ncols=2,
                                                sharex=False,
                                                sharey=False)

    df = df.query(
        "Setname=='5cm' or Setname=='10cm' or Setname=='15cm' or Setname=='20cm'"
    )
    # df.to_csv(fname+".tussendump.csv")

    sns.lineplot(x="Distance to isoc [mm]",
                 y="Dose [cGy]",
                 hue="Setname",
                 data=df.query("Axis=='X'"),
                 style="Generator",
                 ax=ax1,
                 lw=1)
    sns.lineplot(x="Distance to isoc [mm]",
                 y="Dose [cGy]",
                 hue="Setname",
                 data=df.query("Axis=='Y'"),
                 style="Generator",
                 ax=ax2,
                 lw=1)
    sns.lineplot(x="Distance to isoc [mm]",
                 y="Dose [cGy]",
                 hue="Setname",
                 data=df.query("Axis=='ratY'"),
                 ax=ax3,
                 lw=1)
    # sns.lineplot(x="Distance to isoc [mm]", y="Dose [cGy]", hue="Setname", data=df.query("Axis=='relY'"), style="Generator", ax=ax3, lw=1)
    sns.lineplot(x="Distance to isoc [mm]",
                 y="Dose [cGy]",
                 hue="Setname",
                 data=df.query("Axis=='Z'"),
                 style="Generator",
                 ax=ax4,
                 lw=1)

    ax1.set_xlim(-170, 170)
    # ax2.set_xlim(-170,170)
    ax3.set_xlim(-170, 170)
    ax4.set_xlim(-170, 170)

    # ax3.set_ylim(-.25,0.5)
    ax3.set_ylim(0, 2)

    ax1.set_title("X (BLD:Jaw)")
    ax2.set_title("Y")
    # ax3.set_title("reldiff X") #relY is relative y over X axis
    ax3.set_title("ratio X")  #relY is relative y over X axis
    ax4.set_title("Z (BLD:MLC)")

    ax3.set_ylabel("Relative Dose")
    ax3.set_ylabel("Dose Ratio")

    ax1.legend(title="Fieldsize",
               loc='upper right',
               bbox_to_anchor=(1.4, 1.),
               frameon=False)
    ax2.legend_.remove()  #.legend().set_title('Fieldsize')
    ax3.legend(title="Fieldsize",
               loc='upper right',
               bbox_to_anchor=(1.4, 1.),
               frameon=False)
    ax4.legend_.remove()  #.legend().set_title('Fieldsize')

    f.subplots_adjust(hspace=.6, wspace=.5)
    f.savefig(fname + '.pdf', bbox_inches='tight')
    f.savefig(fname + '.png', bbox_inches='tight', dpi=300)
Esempio n. 11
0
all = dump.get2D(dosephs, ['X', 'Y'])

doseim_ = image.image(doseim, type='yield')
doseuncim_ = image.image(doseuncim, type='relunc')
doseuncim_.imdata = doseuncim_.imdata.squeeze() * 100.

dosetleim_ = image.image(dosetleim, type='yield')
dosetleuncim_ = image.image(dosetleuncim, type='relunc')
dosetleuncim_.imdata = dosetleuncim_.imdata.squeeze() * 100.

unc_axis = np.linspace(0, 50, 50)

f, ((ax1, ax2, ax3), (ax4, ax5,
                      ax6)) = plot.subplots(nrows=2,
                                            ncols=3,
                                            sharex=False,
                                            sharey=False)  #,figsize=(28,10))

#f.subplots_adjust(hspace=.5)
#f.subplots_adjust(wspace=.5)
f.suptitle('Runtime: ' + runtime + 's', fontsize=10)
ax1.set_title("PhS, X,Y")
ax2.set_title("Dose")
ax3.set_title("Dose TLE")
ax4.set_title("PhS, rel. unc")
ax5.set_title("Dose, rel. unc")
ax6.set_title("Dose TLE, rel. unc")

# BIN EDGES!
xbins = np.linspace(-410 / 2., 410 / 2., 256 + 1)
ybins = np.linspace(-410 / 2., 410 / 2., 256 + 1)
                                'Ekine',
                                ParticleName='gamma',
                                Primary=True,
                                Transmission=False)
    phot_other_E = dump.get1D(rootfile,
                              'Ekine',
                              ParticleName='gamma',
                              Primary=False)
    nonphot_E = dump.get1D(rootfile, 'Ekine', ParticleName='not_gamma')

    partname = dump.get1D(rootfile, 'ParticleName')

    f, ((ax1, ax2, ax3, ax4, ax5), (ax6, ax7, ax8, ax9, ax10),
        (ax11, ax12, ax13,
         ax14, ax15)) = plot.subplots(nrows=3,
                                      ncols=5,
                                      sharex=False,
                                      sharey=False)  #,figsize=(28,10))

    f.subplots_adjust(hspace=.5)
    f.subplots_adjust(wspace=.5)

    ax1.set_title("Total Counts")
    ax2.set_title("Prim Trans")
    ax3.set_title("Prim Scat")
    ax4.set_title("Secon Phot")
    ax5.set_title("Nonphot")

    # BIN EDGES!
    xbins = np.linspace(-410 / 2., 410 / 2., 256 + 1)
    ybins = np.linspace(-410 / 2., 410 / 2., 256 + 1)
Esempio n. 13
0
#electronprod = glob.glob(indir+"/**/epid-entry.root")[0]

all = dump.get2D(dosephs,['X','Y'])

doseim_ = image.image(doseim,type='yield')
doseuncim_ = image.image(doseuncim,type='relunc')
doseuncim_.imdata = doseuncim_.imdata.squeeze()*100.

dosetleim_ = image.image(dosetleim,type='yield')
dosetleuncim_ = image.image(dosetleuncim,type='relunc')
dosetleuncim_.imdata = dosetleuncim_.imdata.squeeze()*100.

unc_axis = np.linspace(0,50,50)

f, ((ax1 ,ax2, ax3 ),(ax4, ax5, ax6))= plot.subplots(nrows=2, ncols=3, sharex=False, sharey=False)#,figsize=(28,10))

#f.subplots_adjust(hspace=.5)
#f.subplots_adjust(wspace=.5)
f.suptitle('Runtime: '+runtime+'s', fontsize=10)
ax1.set_title("PhS, X,Y")
ax2.set_title("Dose")
ax3.set_title("Dose TLE")
ax4.set_title("PhS, rel. unc")
ax5.set_title("Dose, rel. unc")
ax6.set_title("Dose TLE, rel. unc")

# BIN EDGES!
xbins = np.linspace(-410/2.,410/2.,256+1)
ybins = np.linspace(-410/2.,410/2.,256+1)
Esempio n. 14
0
def megaplot(ctsets,studyname,emisfops=None,labels=["$10^9$","$10^8$","$10^7$","$10^6$"],axlabel='Primaries [nr]'):
    #if emisfops is not None:
        #for emisfop in emisfops:
            #emisfop[0]+=15.863
            #emisfop[1]+=15.863
    print 'FOP shift all overlaid'
    
    #if len(ctsets) == 3:
        #f, (ax1,ax2,ax3) = plot.subplots(nrows=1, ncols=3, sharex=False, sharey=False)
        #auger.plot_all_ranges(ax1,ctsets[0])
        #auger.plot_all_ranges(ax2,ctsets[1])
        #auger.plot_all_ranges(ax3,ctsets[2])
        #f.savefig(studyname+'-'+typ+'-FOP.pdf', bbox_inches='tight')
        #plot.close('all')
        #f.subplots_adjust(hspace=.5)
        #ax2.set_ylabel('')
        #ax3.set_ylabel('')

    if len(ctsets) > 2:
        f, ((ax1,ax2),(ax3,ax4)) = plot.subplots(nrows=2, ncols=2, sharex=False, sharey=False)
        ax1.set_xlabel('')
        ax2.set_xlabel('')
        ax2.set_ylabel('')
        ax4.set_ylabel('')
    elif len(ctsets) == 2:
        f, (ax1,ax2) = plot.subplots(nrows=1, ncols=2, sharex=False, sharey=False)
        ax2.set_xlabel('')
        
    f.subplots_adjust(hspace=0.7,wspace=0.5)
    
    auger.plot_all_ranges(ax1,ctsets[0])
    auger.plot_all_ranges(ax2,ctsets[1])
    if len(ctsets) > 2:
        try:
            auger.plot_all_ranges(ax3,ctsets[2])
        except:
            ax3.axis('off')
        try:
            auger.plot_all_ranges(ax4,ctsets[3])
        except:
            ax4.axis('off')
    
    #auger.plot_single_range(ax1,ctsets[0])
    #auger.plot_single_range(ax2,ctsets[1])
    #auger.plot_single_range(ax3,ctsets[2])
    #auger.plot_single_range(ax4,ctsets[3])
    
    if not 'Primaries' in axlabel:
        ax1.set_title(labels[0])
        ax2.set_title(labels[1])
        #ax3.set_title(labels[2])
        #ax4.set_title(labels[3])
    
    #if 'waterbox' in studyname:
        #import matplotlib
        #matplotlib.pyplot.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
        #f.subplots_adjust(wspace=.3)
        
        #x0 = []
        #y1 = []
        #y1std = []
        #y2 = []
        #y2std = []
        #for ct in ctsets:
            #x0.append(1./sqrt(ct['nprim']))
            #y1.append(ct['ct']['fopsigma'])
            #y2.append(ct['rpct']['fopsigma'])
            #y1std.append( ct['ct']['fopsigma']/sqrt(2*(len(ct['ct']['falloff'])-1)) )
            #y2std.append( ct['rpct']['fopsigma']/sqrt(2*(len(ct['rpct']['falloff'])-1)) )
        #plot.plot_errorbands(ax4,x0,y1,y1std,color='steelblue')
        #plot.plot_errorbands(ax4,x0,y2,y2std,color='indianred')
        ##ax4.set_xlim(x[0],x[-1])
        ##ax4.set_ylim(y[0],y[-1])
        #ax4.set_title('CNR check', fontsize=8)
        #ax4.set_xlabel('1/sqrt(N$_{prim}$)', fontsize=8)
        ##ax4.set_ylabel('sqrt(background)/signal', fontsize=8)
        #ax4.set_ylabel('$\sigma_{FOP} [mm]$', fontsize=8)
        #plot.texax(ax4)
    
    f.savefig(studyname+'-'+typ+'-FOP.pdf', bbox_inches='tight')
    plot.close('all')

    #############################################################################################

    print 'FOP shift distributions'

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    tmpprim=0
    center=0
    for ctset in ctsets:
        if ctset['nprim'] > tmpprim:
            tmpprim = ctset['nprim']
            center= ctset['fodiffmu']
    
    for i,ctset in enumerate(ctsets):
        auger.plotfodiffdist(ax1,ctset,i,emisfops,labels,axlabel,center)
        if not emisfops == None:
            fopshifts=[]
            for fopset in emisfops:
                fopshifts.append( fopset[-1]-fopset[0] )
            ax1.set_xlim3d(np.mean(fopshifts)-20,np.mean(fopshifts)+20)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname+', $Shift_{em}$ = '+str(emisfops[0][-1]-emisfops[0][0]), y=1.08)
        pass
        
    #fig.suptitle('FOP shifts', fontsize=10)
    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    fig.savefig(studyname+'-'+typ+'-FOP-shift.pdf')#, bbox_inches='tight')
    plt.close('all')

    #############################################################################################

    print 'FOP distributions'

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)
    
    tmpprim=0
    center=0
    for ctset in ctsets:
        if ctset['nprim'] > tmpprim:
            tmpprim = ctset['nprim']
            center= ( ctset['ct']['fopmu'] + ctset['rpct']['fopmu'] ) /2.
    
    for i,ctset in enumerate(ctsets):
        auger.plotfodist(ax1,ctset,i,emisfops,labels,axlabel,center)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname+', $CT_{FOP_{em}}$ = '+str(emisfops[0][0])[:5]+', $RPCT_{FOP_{em}}$ = '+str(emisfops[0][1])[:5], y=1.08)

    #plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    #fig.suptitle('FOP distributions', fontsize=10)
    plt.savefig(studyname+'-'+typ+'-FOP-dist.pdf')#, bbox_inches='tight')
    plt.close('all')
Esempio n. 15
0
#!/usr/bin/env python
import plot,numpy as np

### plot loss of PGs
f, ax = plot.subplots(nrows=1, ncols=1)

# numbers = [4.00E+10,2.00E+08,4.60E+07,1.80E+06,3.40E+04,1.60E+04,4E+03]
protons = [2.00E+08,0,0,0,0,0]
pgs = [0,4.60E+07,1.80E+06,3.40E+04,1.60E+04,8E+03]
pgs = [0,4.60E+07,1.80E+06,3.40E+04,3.40E+04*.66,3.40E+04*.66*.66]
ax.set_ylim([5e3,5e8])
ind = np.arange(len(pgs))
margin = 0.2
width = (1.-2.*margin)
xdata = ind- width/2.
labels = ["Primaries","PGs Exiting patient","Solid angle detector","Post-collimator","Detector Efficiency ?","Reconstruction Eff. ?"]

p1 = ax.bar(xdata, protons, width, color='k',lw=0)
p2 = ax.bar(xdata, pgs, width, color='r',bottom=protons,lw=0)

#ax.set_xticklabels(labels, fontsize=8, rotation=15, ha='left')
ax.set_xticklabels(['']+labels, fontsize=8, rotation=15, ha='center')
ax.legend((p1[0], p2[0]), ('Protons', 'Prompt Gammas'),frameon=False)

ax.set_ylabel('Counts')
#ax.set_title('Progressive loss of Prompt Gammas')
ax.set_yscale('log')
ax.set_ylim([5e3,5e8])
f.savefig('lossofpgs.pdf', bbox_inches='tight')
f.savefig('lossofpgs.png', bbox_inches='tight',dpi=300)
plot.close('all')
Esempio n. 16
0
                         ) + glob.glob(indir + "/**/epiddose-tle-Dose.mhd")
    imuncs = glob.glob(
        indir + "/**/epiddose-trans-tle-Dose-Uncertainty.mhd") + glob.glob(
            indir + "/**/epiddose-nontrans-tle-Dose-Uncertainty.mhd"
        ) + glob.glob(indir + "/**/epiddose-tle-Dose-Uncertainty.mhd")

print imyields

labels = ['nontransmission', 'transmission', 'total dose'
          ]  #(non) transmission swapped, because IT IS KILLED BY THE ACTOR!!!!

fracties_totaal = []
fracties_isocentrum = []

f, axes = plot.subplots(nrows=len(imyields) + 1,
                        ncols=4,
                        sharex=False,
                        sharey=False)  #,figsize=(28,10))

for axrow, yim, uim, label in zip(axes, imyields, imuncs, labels):
    print yim, uim, label
    yim_ = image.image(yim, type='yield')
    uim_ = image.image(
        uim, type='relunc'
    )  #the doseactor outputs relative uncertainties as per Chetty, see GateImageWithStatistic
    #uim_.applymask(mask90pc)
    uim_.imdata = uim_.imdata.squeeze() * 100.  #fractions to percentages
    fracties_isocentrum.append(yim_.getcenter().mean())
    fracties_totaal.append(yim_.imdata.sum())
    axrow[0].imshow(yim_.imdata.squeeze(), extent=[0, 41, 0, 41], cmap='gray')
    axrow[0].set_title(label + '\n$\sum$ Dose: ' +
                       plot.sn(fracties_totaal[-1]))
Esempio n. 17
0
imyields = glob.glob(indir+"/**/epiddose-trans-Dose.mhd")+glob.glob(indir+"/**/epiddose-nontrans-Dose.mhd")+glob.glob(indir+"/**/epiddose-Dose.mhd")
imuncs = glob.glob(indir+"/**/epiddose-trans-Dose-Uncertainty.mhd")+glob.glob(indir+"/**/epiddose-nontrans-Dose-Uncertainty.mhd")+glob.glob(indir+"/**/epiddose-Dose-Uncertainty.mhd")

if args.tle:
    outname = 'epid_tle_plot.pdf'
    imyields = glob.glob(indir+"/**/epiddose-trans-tle-Dose.mhd")+glob.glob(indir+"/**/epiddose-nontrans-tle-Dose.mhd")+glob.glob(indir+"/**/epiddose-tle-Dose.mhd")
    imuncs = glob.glob(indir+"/**/epiddose-trans-tle-Dose-Uncertainty.mhd")+glob.glob(indir+"/**/epiddose-nontrans-tle-Dose-Uncertainty.mhd")+glob.glob(indir+"/**/epiddose-tle-Dose-Uncertainty.mhd")

print imyields

labels = ['nontransmission','transmission','total dose'] #(non) transmission swapped, because IT IS KILLED BY THE ACTOR!!!!

fracties_totaal = []
fracties_isocentrum = []

f, axes = plot.subplots(nrows=len(imyields)+1, ncols=4, sharex=False, sharey=False)#,figsize=(28,10))

for axrow,yim,uim,label in zip(axes,imyields,imuncs,labels):
    print yim,uim,label
    yim_ = image.image(yim,type='yield')
    uim_ = image.image(uim,type='relunc') #the doseactor outputs relative uncertainties as per Chetty, see GateImageWithStatistic
    #uim_.applymask(mask90pc)
    uim_.imdata = uim_.imdata.squeeze()*100. #fractions to percentages
    fracties_isocentrum.append( yim_.getcenter().mean() )
    fracties_totaal.append( yim_.imdata.sum() )
    axrow[0].imshow( yim_.imdata.squeeze() , extent = [0,41,0,41], cmap='gray')
    axrow[0].set_title(label + '\n$\sum$ Dose: '+ plot.sn(fracties_totaal[-1]))
    
    axrow[1].set_title(label + ' Profile')
    axrow[1].plot(*yim_.getprofile('y'), color = 'steelblue' , label='x')
    axrow[1].plot(*yim_.getprofile('x'), color = 'indianred' , label='y')
Esempio n. 18
0
def megaplot(ctsets,
             studyname,
             emisfops=None,
             labels=["$10^9$", "$10^8$", "$10^7$", "$10^6$"],
             axlabel='Primaries [nr]'):

    f, (ax1, ax2) = plot.subplots(nrows=2, ncols=1, sharex=False, sharey=False)
    x = ctsets[0]['ct']['x']
    y = ctsets[0]['ct']['av']
    if 'iba' in ctsets[0]['name']:  # ctset['name'] == typ
        mm = 4 / 0.8
    if 'ipnl' in ctsets[0]['name']:
        mm = 8
    falloff_pos, g_fwhm, contrast = auger.get_fop_fow_contrast(
        x,
        y,
        plot='wut',
        ax=ax1,
        ax2=ax2,
        smooth=0.2,
        filename=ctsets[0]['ct']['path'],
        contrast_divisor=ctsets[0]['nprim'] * len(ctsets[0]['ct']['files']) *
        mm,
        fitlines=False)

    # some cosmetics
    maxyrounded = int(math.ceil(max(y) / 100.0)) * 100
    ticks = np.arange(0, maxyrounded, 100)
    if len(ticks) > 10:
        ticks = np.arange(0, maxyrounded + 100, 200)
    if len(ticks) > 10:
        ticks = np.arange(0, maxyrounded + 200, 400)
    if len(ticks) > 10:
        ticks = np.arange(0, maxyrounded + 400, 800)
    ax1.set_yticks(ticks)

    minor_locator = AutoMinorLocator(2)
    minor_locator1 = AutoMinorLocator(2)
    ax1.xaxis.set_minor_locator(minor_locator)
    ax2.xaxis.set_minor_locator(minor_locator)
    ax2.yaxis.set_minor_locator(minor_locator1)

    if PHYSDET_PROFILE_IBA != None and 'iba' in ctsets[0]['name']:
        ax1.scatter(x,
                    PHYSDET_PROFILE_IBA,
                    color='lightgrey',
                    marker="x",
                    clip_on=False)
    if PHYSDET_PROFILE_IPNL != None and 'ipnl' in ctsets[0]['name']:
        ax1.scatter(x,
                    PHYSDET_PROFILE_IPNL,
                    color='lightgrey',
                    marker="x",
                    clip_on=False)

    print "NPRIM", ctsets[0]['nprim'], "NJOBS", len(
        ctsets[0]['ct']['files']), "MM", mm

    #gebruiken deze falloff_pos niet. we doen contrast en fow over de average van 50 batches wegens smoothe curve. daardoor geen sigma

    f.savefig(studyname + '-' + typ + str(ctsets[0]['nprim']) + '-FOW.pdf',
              bbox_inches='tight')
    plot.close('all')

    #############################################################################################

    # results table

    for ctset in ctsets:
        res = [
            typ, ctset['nprim'], ctset['ct']['fopmu'], ctset['ct']['fopsigma'],
            g_fwhm, contrast, ctset['detyieldmu'], ctset['detyieldsigma'],
            ctset['detcount'], ctset['detcount']
        ]

        if ctset['nprim'] == 10**9:
            if 'iba' in typ:
                #res.append(pgprod_1mev_iba*ctset['nprim'])
                res[-1] = res[-1] / (pgprod_1mev_iba * ctset['nprim'])
            if 'ipnl' in typ:
                #res.append(pgprod_1mev_ipnl*ctset['nprim'])
                res[-1] = res[-1] / (pgprod_1mev_ipnl * ctset['nprim'])
        else:
            res[-1] = ''

        if precolli:
            res.extend(
                [ctset['precollidetyieldmu'], ctset['precollidetyieldsigma']])

        resultstable.append(res)

    #############################################################################################

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    print 'FOP distributions'

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    for i, ctset in enumerate(ctsets):
        auger.plotfodist_CTONLY(ax1, ctset, i, emisfops, labels, axlabel)

    # plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

    # plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    plt.savefig(studyname + '-' + typ +
                '-FOP-dist.pdf')  #, bbox_inches='tight')
    plt.close('all')
Esempio n. 19
0
from collections import Counter

clrs=plot.colors

#plot depth dose of some particles.

files = {
'Electron (20 MeV)':'output/dose-e--20-Dose.root',
'Photon (6 MeV)':'output/dose-gamma-6-Dose.root',
'Helium (700 MeV)':'output/dose-alpha-700-Dose.root',
'Proton (177 MeV)':'output/dose-proton-177-Dose.root',
'Pion^{+} (84 MeV)':'output/dose-pi+-84-Dose.root',
'Carbon (4 Gev)':'output/dose-ion-4000-Dose.root'
}

f, ax1 = plot.subplots(nrows=1, ncols=1, sharex=False, sharey=False)

for index,(key,val) in enumerate(files.iteritems()):
	data = dump.thist2np(val)['histo']
	maxi=max(data)
	plot.plot([x/maxi for x in data], label=key)

ax1.set_ylabel('Dose (normalized)')
ax1.set_xlabel('Depth (mm)')
ax1.set_title('Dose as function of depth for some particles')
plot.texax(ax1)
ax1.legend(loc='upper right', bbox_to_anchor=(1.3, 1.),frameon=False)
f.savefig('depthdose.pdf', bbox_inches='tight')
plot.close('all')

Esempio n. 20
0
def megaplot(ctsets,
             studyname,
             emisfops=None,
             labels=["$10^9$", "$10^8$", "$10^7$", "$10^6$"],
             axlabel='Primaries [nr]'):

    if len(ctsets) == 4:
        f, ((ax1, ax2), (ax3, ax4)) = plot.subplots(nrows=2,
                                                    ncols=2,
                                                    sharex=False,
                                                    sharey=False)

        auger.plot_all_ranges_CTONLY(ax1, ctsets[0])
        auger.plot_all_ranges_CTONLY(ax2, ctsets[1])
        auger.plot_all_ranges_CTONLY(ax3, ctsets[2])
        #auger.plot_all_ranges_CTONLY(ax4,ctsets[3])
        if not 'Primaries' in axlabel:
            ax1.set_title(labels[0])
            ax2.set_title(labels[1])
            ax3.set_title(labels[2])
            #ax4.set_title(labels[3])
        f.subplots_adjust(hspace=.5)
        ax1.set_xlabel('')
        ax2.set_xlabel('')
        ax2.set_ylabel('')
        #ax4.set_ylabel('')
        f.savefig(studyname + '-' + typ + '-FOP.pdf', bbox_inches='tight')
        plot.close('all')

    #############################################################################################

    # print 'FOP shift distributions'

    # from mpl_toolkits.mplot3d import Axes3D
    # import matplotlib.pyplot as plt

    # fig = plt.figure()
    # ax1 = plt.axes(projection='3d')
    # ax1.view_init(30, -50)

    # for i,ctset in enumerate(ctsets):
    # 	auger.plotfodiffdist(ax1,ctset,i,emisfops,labels,axlabel)
    # 	if not emisfops == None:
    # 		fopshifts=[]
    # 		for fopset in emisfops:
    # 			fopshifts.append( fopset[-1]-fopset[0] )
    # 		ax1.set_xlim3d(np.mean(fopshifts)-20,np.mean(fopshifts)+20)
    # if emisfops is not None and len(emisfops) == 1:
    # 	ax1.set_title(studyname+', $Shift_{em}$ = '+str(emisfops[0][-1]-emisfops[0][0]), y=1.08)

    # #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    # fig.savefig(studyname+'-'+typ+'-FOP-shift.pdf')#, bbox_inches='tight')
    # plt.close('all')

    #############################################################################################

    # print 'FOP FOW Contrast DE averages over 10e9 ctset'
    # removed 2nd deriv from plot

    f, (ax1, ax2) = plot.subplots(nrows=2, ncols=1, sharex=False, sharey=False)
    x = ctsets[0]['ct']['x']  # 0 should be one with nprim=1e9
    y = ctsets[0]['ct']['av']
    if 'iba' in ctsets[0]['name']:  # ctset['name'] == typ
        mm = 4 / 0.8
    if 'ipnl' in ctsets[0]['name']:
        mm = 8
    falloff_pos, g_fwhm, contrast = auger.get_fop_fow_contrast(
        x,
        y,
        plot='wut',
        ax=ax1,
        ax2=ax2,
        smooth=0.2,
        filename=ctsets[0]['ct']['path'],
        contrast_divisor=ctsets[0]['nprim'] * len(ctsets[0]['ct']['files']) *
        mm,
        fitlines=False)

    # some cosmetics
    maxyrounded = int(math.ceil(max(y) / 100.0)) * 100
    ticks = np.arange(0, maxyrounded, 100)
    if len(ticks) > 10:
        ticks = np.arange(0, maxyrounded + 100, 200)
    if len(ticks) > 10:
        ticks = np.arange(0, maxyrounded + 200, 400)
    ax1.set_yticks(ticks)

    minor_locator = AutoMinorLocator(2)
    minor_locator1 = AutoMinorLocator(2)
    ax1.xaxis.set_minor_locator(minor_locator)
    ax2.xaxis.set_minor_locator(minor_locator)
    ax2.yaxis.set_minor_locator(minor_locator1)

    print "NPRIM", ctsets[0]['nprim'], "NJOBS", len(
        ctsets[0]['ct']['files']), "MM", mm

    #gebruiken deze falloff_pos niet. we doen contrast en fow over de average van 50 batches wegens smoothe curve. daardoor geen sigma

    f.savefig(studyname + '-' + typ + '-FOW.pdf', bbox_inches='tight')
    plot.close('all')

    #############################################################################################

    # results table
    print 'Computing pgprod ratios...'
    pgprod_1mev = dump.count_ekine_in_phasespace(
        "/home/brent/phd/art2_lyso_box/stage2_box15_docker/output/pgprod-worldframe.root",
        1.)
    pgprod_3mev = dump.count_ekine_in_phasespace(
        "/home/brent/phd/art2_lyso_box/stage2_box15_docker/output/pgprod-worldframe.root",
        3.)
    print 'done.'

    for ctset in ctsets:
        res = [
            typ, ctset['nprim'], ctset['ct']['fopmu'], ctset['ct']['fopsigma'],
            g_fwhm, contrast, ctset['detyieldmu'], ctset['detyieldsigma'],
            ctset['detcount']
        ]

        if ctset['nprim'] == 10**9:
            if pgexit and '3' in typ:
                res[-1] = res[-1] / pgprod_3mev
            elif pgexit and '1' in typ:
                res[-1] = res[-1] / pgprod_1mev
        else:
            res[-1] = ''

        if precolli:
            res.extend(
                [ctset['precollidetyieldmu'], ctset['precollidetyieldsigma']])

        resultstable.append(res)

    #############################################################################################

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    print 'FOP distributions'

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    for i, ctset in enumerate(ctsets):
        auger.plotfodist_CTONLY(ax1, ctset, i, emisfops, labels, axlabel)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname + ', $CT_{FOP_{em}}$ = ' +
                      str(emisfops[0][0])[:5] + ', $RPCT_{FOP_{em}}$ = ' +
                      str(emisfops[0][1])[:5],
                      y=1.08)

    #plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    plt.savefig(studyname + '-' + typ +
                '-FOP-dist.pdf')  #, bbox_inches='tight')
    plt.close('all')
def megaplot(ctsets,
             studyname,
             emisfops=None,
             labels=["$10^9$", "$10^8$", "$10^7$", "$10^6$"],
             axlabel='Primaries [nr]'):

    # print 'FOP FOW Contrast DE averages over 10e9 ctset'
    # removed 2nd deriv from plot

    f, (ax1, ax2) = plot.subplots(nrows=2, ncols=1, sharex=False, sharey=False)
    x = ctsets[0]['ct']['x']
    y = ctsets[0]['ct']['av']
    if 'iba' in ctsets[0]['name']:  # ctset['name'] == typ
        mm = 4 / 0.8
    if 'ipnl' in ctsets[0]['name']:
        mm = 8
    falloff_pos, g_fwhm, contrast = auger.get_fop_fow_contrast(
        x,
        y,
        plot='wut',
        ax=ax1,
        ax2=ax2,
        smooth=0.2,
        filename=ctsets[0]['ct']['path'],
        contrast_divisor=ctsets[0]['nprim'] * len(ctsets[0]['ct']['files']) *
        mm,
        fitlines=False)

    # some cosmetics
    maxyrounded = int(math.ceil(max(y) / 100.0)) * 100
    ticks = np.arange(0, maxyrounded, 100)
    if len(ticks) > 10:
        ticks = np.arange(0, maxyrounded + 100, 200)
    if len(ticks) > 10:
        ticks = np.arange(0, maxyrounded + 200, 400)
    ax1.set_yticks(ticks)

    minor_locator = AutoMinorLocator(2)
    minor_locator1 = AutoMinorLocator(2)
    ax1.xaxis.set_minor_locator(minor_locator)
    ax2.xaxis.set_minor_locator(minor_locator)
    ax2.yaxis.set_minor_locator(minor_locator1)

    print "NPRIM", ctsets[0]['nprim'], "NJOBS", len(
        ctsets[0]['ct']['files']), "MM", mm

    #gebruiken deze falloff_pos niet. we doen contrast en fow over de average van 50 batches wegens smoothe curve. daardoor geen sigma

    f.savefig(studyname + '-' + typ + str(ctsets[0]['nprim']) + '-FOW.pdf',
              bbox_inches='tight')
    plot.close('all')

    #############################################################################################

    # results table

    for ctset in ctsets:
        res = [
            typ, ctset['nprim'], ctset['ct']['fopmu'], ctset['ct']['fopsigma'],
            g_fwhm, contrast, ctset['detyieldmu'], ctset['detyieldsigma'],
            ctset['detcount']
        ]

        if ctset['nprim'] == 10**9:
            if 'iba' in typ:
                #res.append(pgprod_1mev_iba*ctset['nprim'])
                res[-1] = res[-1] / (pgprod_1mev_iba * ctset['nprim'])
            if 'ipnl' in typ:
                #res.append(pgprod_1mev_ipnl*ctset['nprim'])
                res[-1] = res[-1] / (pgprod_1mev_ipnl * ctset['nprim'])
        else:
            res[-1] = ''

        if precolli:
            res.extend(
                [ctset['precollidetyieldmu'], ctset['precollidetyieldsigma']])

        resultstable.append(res)
#!/usr/bin/env python
import argparse, numpy as np, matplotlib, dump, plot

parser = argparse.ArgumentParser(description='Plot 2D hist from ROOT TTree.')
parser.add_argument('files', nargs='*')
args = parser.parse_args()
rootfiles = args.files

for rootfile in rootfiles:
    all = dump.get2D(rootfile, ['X', 'Y'])

    f, (ax1, ax2) = plot.subplots(nrows=1, ncols=2, sharex=False,
                                  sharey=False)  #,figsize=(28,10))

    f.subplots_adjust(hspace=.5)
    f.subplots_adjust(wspace=.5)

    ax1.set_title("X,Y")
    ax2.set_title("unc histo")

    # BIN EDGES!
    xbins = np.linspace(-410 / 2., 410 / 2., 256 + 1)
    ybins = np.linspace(-410 / 2., 410 / 2., 256 + 1)

    counts = plot.plot2dhist(ax1,
                             all['X'],
                             all['Y'],
                             xbins=xbins,
                             ybins=ybins,
                             log=True)
Esempio n. 23
0
	return nr[:3]+'\%'

def plotprof(ax,xax,emit,dete,name, **kwargs):
	if name == 'CT':
		color='steelblue'
	elif name == 'RPCT':
		color='indianred'
	else:
		color='black'
	ax.step(xax,emit, color=color,lw=1., alpha=1, label=name+', yield: '+yld(emit), where='mid')
	#ax.step(xax,dete, color=color,lw=1., alpha=0.5, label=name+' PSF', where='mid')
	return ax

###########################################################################################################

f, (ax1,ax2) = plot.subplots(nrows=1, ncols=2, sharex=True, sharey=False)

plotprof(ax1,pgsrc_ct_x,pgelay.imdata,detprof_pgelay,'CT')
plotprof(ax1,pgsrc_ct_x,rppgelay.imdata,detprof_rppgelay,'RPCT')
ax1.set_title('Iso-energy layer, PG shift: '+str(rppgelay_fo-pgelay_fo)[:4]+' mm', fontsize=10)
ax1.legend(frameon = False,loc='upper left')
ax1.set_xlim(-80,60)
ax1.set_ylim(0,0.003)
ax1.set_ylabel('Cumulative PG emission per proton')
plot.texax(ax1)

plotprof(ax2,pgsrc_ct_x,pggeolay.imdata,detprof_pggeolay,'CT')
plotprof(ax2,pgsrc_ct_x,rppggeolay.imdata,detprof_rppggeolay,'RPCT')
ax2.set_title('Iso-depth layer, PG shift: '+str(rppggeolay_fo-pggeolay_fo)[:4]+' mm', fontsize=10)
ax2.legend(frameon = False,loc='upper left')
#ax2.set_xlim(-80,70)
#!/usr/bin/env python
import plot, numpy as np, auger, image, rtplan
from scipy.ndimage.filters import gaussian_filter

###########################################################################################################

#volume_offset=-141.59+7.96#spot sources
volume_offset = 150 - 141.59 + 7.96  #spot sources

###########################################################################################################

# BOTTOM ROW IBA

f, ((ax4, ax5, ax6), (ax1, ax2, ax3)) = plot.subplots(nrows=2,
                                                      ncols=3,
                                                      sharex=True,
                                                      sharey=False)

typ = 'iba-auger-notof-3.root'

yield_av = auger.plot_all_ranges_2(ax1,
                                   auger.getctset(
                                       840964615,
                                       'fromclus-sorted/layers-beide/run.e8ai',
                                       'fromclus-sorted/layers-beide/run.96ra',
                                       typ,
                                       manualshift=volume_offset),
                                   firstcolor='steelblue',
                                   secondcolor=None)
yield_av = auger.plot_all_ranges_2(ax1,
                                   auger.getctset(
Esempio n. 25
0
def megaplot(ctsets,
             studyname,
             emisfops=None,
             labels=["$10^9$", "$10^8$", "$10^7$", "$10^6$"],
             axlabel='Primaries [nr]'):
    # if emisfops is not None:
    # 	for emisfop in emisfops:
    # 		emisfop[0]+=15.863
    # 		emisfop[1]+=15.863
    # print 'FOP shift all overlaid'

    if len(ctsets) == 4:
        f, ((ax1, ax2), (ax3, ax4)) = plot.subplots(nrows=2,
                                                    ncols=2,
                                                    sharex=False,
                                                    sharey=False)

        auger.plot_all_ranges(ax1, ctsets[0])
        auger.plot_all_ranges(ax2, ctsets[1])
        auger.plot_all_ranges(ax3, ctsets[2])
        auger.plot_all_ranges(ax4, ctsets[3])
        if not 'Primaries' in axlabel:
            ax1.set_title(labels[0])
            ax2.set_title(labels[1])
            ax3.set_title(labels[2])
            ax4.set_title(labels[3])
        f.subplots_adjust(hspace=.5)
        ax1.set_xlabel('')
        ax2.set_xlabel('')
        ax2.set_ylabel('')
        ax4.set_ylabel('')
        f.savefig(studyname + '-' + typ + '-FOP.pdf', bbox_inches='tight')
        plot.close('all')

    #############################################################################################

    print 'FOP shift distributions'

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    for i, ctset in enumerate(ctsets):
        auger.plotfodiffdist(ax1, ctset, i, emisfops, labels, axlabel)
        if not emisfops == None:
            fopshifts = []
            for fopset in emisfops:
                fopshifts.append(fopset[-1] - fopset[0])
            ax1.set_xlim3d(np.mean(fopshifts) - 20, np.mean(fopshifts) + 20)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname + ', $Shift_{em}$ = ' +
                      str(emisfops[0][-1] - emisfops[0][0]),
                      y=1.08)

    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    fig.savefig(studyname + '-' + typ +
                '-FOP-shift.pdf')  #, bbox_inches='tight')
    plt.close('all')

    #############################################################################################

    print 'FOP distributions'

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    for i, ctset in enumerate(ctsets):
        auger.plotfodist(ax1, ctset, i, emisfops, labels, axlabel)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname + ', $CT_{FOP_{em}}$ = ' +
                      str(emisfops[0][0])[:5] + ', $RPCT_{FOP_{em}}$ = ' +
                      str(emisfops[0][1])[:5],
                      y=1.08)

    #plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    plt.savefig(studyname + '-' + typ +
                '-FOP-dist.pdf')  #, bbox_inches='tight')
    plt.close('all')
#typ='ipnl-auger-notof-1.root'
#typ='iba-auger-tof-3.root'
typ='iba-auger-notof-3.root'

#nieuwe sums. distal layer
#22 , 4 ,
#4 : 65802598.6018 , 7 : 88235302.6706 , 10 : 67298112.2064 , 43 : 64073566.2641 , 

ctset_4 = auger.getctset(65802598,'run.4Zh8','run.8Yoh',typ)
ctset_7 = auger.getctset(88235302,'run.MjnN','run.a5rv',typ)
ctset_10 = auger.getctset(67298112,'run.XXMy','run.btzm',typ)#XXMy + 3x HyIv
ctset_43 = auger.getctset(64073566,'run.iohj','run.hDu1',typ)

ctset_sum_0 = auger.sumctset('sum',ctset_4,ctset_7,ctset_10,ctset_43)

f, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plot.subplots(nrows=2, ncols=3, sharex=False, sharey=False)

auger.plotrange(ax1,ctset_4)
auger.plotrange(ax2,ctset_7)
auger.plotrange(ax3,ctset_10)
auger.plotrange(ax4,ctset_43)
ax5.axis('off')
auger.plotrange(ax6,ctset_sum_0)

f.savefig(typ+'-spotsums-0.pdf', bbox_inches='tight')
plot.close('all')

#nieuwe sums. distal-1 layer
#18 , 5 , 
#6 : 58325030.5789 , 9 : 65802598.6018 , 28 : 54600663.4 , 32 : 66406212.2432 , 39 : 42230305.0377 , 
Esempio n. 27
0
#!/usr/bin/env python
import seaborn as sns,pandas as pd,plot

df = pd.read_csv("results.tsv",sep='\t',nrows=6,skiprows=[1])

print df

sns.set_style(style="whitegrid")
sns.set(font_scale=1.1)
f, ax1 = plot.subplots(nrows=1, ncols=1)

sns.lineplot(x="nprim", y="fopsigma", hue="typ", markers=True, data=df, ax=ax1)
ax1.set_title("Fall-off Retrieval position (FRP)")
ax1.set_ylabel("FRP (mm)")
ax1.set_xlabel("Number of primary protons")
ax1.semilogx()

new_labels = ['Camera', 'MPS', 'KES']
for t, l in zip(ax1.get_legend().texts, new_labels): t.set_text(l)


f.savefig('amv_frp_plot.pdf', bbox_inches='tight')
Esempio n. 28
0
MSW=[]
for spot in rtplan.spots:
    MSW.append(spot[-1])

#spot_weight_mean = np.median(MSW)
spot_weight_mean = np.mean(MSW)

nrfields=len(rtplan.fields)

fontsize=6
mpl.rcParams['xtick.labelsize'] = fontsize
mpl.rcParams['ytick.labelsize'] = fontsize
mpl.rcParams['axes.titlesize'] = fontsize
mpl.rcParams['axes.labelsize'] = fontsize

plotke = plot.subplots(nrows=2, ncols=nrfields, sharex='col', sharey='row')
plotke[0].get_axes()[0].annotate('Total nr. of primaries: '+plot.sn(rtplan.TotalMetersetWeight)+'. Mean spot weight: '+plot.sn(spot_weight_mean), (0.5, 0.975), xycoords='figure fraction', ha='center', fontsize=fontsize)

if nrfields == 1:
    spotaxes = [plotke[-1][0]] #0 is eerste kolom
    layaxes = [plotke[-1][1]] #0 is eerste kolom
    spotloop= [spotdata[0]]
    layloop = [layerdata[0]]
else:
    spotaxes = plotke[-1][0] #0 is eerste kolom
    layaxes = plotke[-1][1] #0 is eerste kolom
    spotloop = spotdata
    layloop = layerdata

first = True
layer_min_y = 1e10
#!/usr/bin/env python
import argparse,numpy as np,matplotlib,dump,plot

parser = argparse.ArgumentParser(description='Plot 2D hist from ROOT TTree.')
parser.add_argument('files', nargs='*')
args = parser.parse_args()
rootfiles = args.files

for rootfile in rootfiles:
    all = dump.scaletreefast(rootfile,['X','Y'])
    
    f, ((ax1 ,ax2), (ax3,ax4)) = plot.subplots(nrows=2, ncols=2, sharex=False, sharey=False)#,figsize=(28,10))
    
    f.subplots_adjust(hspace=.5,wspace=.5)
    
    ax1.set_title("Positions")
    ax2.set_title("Cutout")
    
    panelsize = 410. #mm
    numpix = 256
    
    pixsize = panelsize/numpix #mm
    
    xbins = np.linspace(-panelsize/2.,panelsize/2.,numpix+1)
    ybins = xbins
    xbins2 = plot.chopcentral(xbins,5)
    ybins2 = xbins2
    xbins3 = np.linspace(-5,5,10+1)
    ybins3 = xbins3
    xbins4 = np.linspace(-10,0,10+1)
    ybins4 = xbins4
Esempio n. 30
0
#!/usr/bin/env python
import image,numpy as np,auger,plot,dump
from scipy.ndimage.filters import gaussian_filter

np.random.seed(65983146)

f, ((ax1,ax2),(ax3,ax4)) = plot.subplots(nrows=2, ncols=2, sharex=False, sharey=False)

#spot 29 CT

filen = 'run.pMSA/output.2391740/ipnl-auger-tof-1.root'
auger.testfit(filen,1e9,ax1)

filen = 'run.EPjL/output.2391621/ipnl-auger-tof-1.root'
auger.testfit(filen,1e7,ax2)

filen = 'run.pMSA/output.2391740/iba-auger-notof-3.root'
auger.testfit(filen,1e9,ax3)

filen = 'run.EPjL/output.2391621/iba-auger-notof-3.root'
auger.testfit(filen,1e7,ax4)


#ax1.set_title(labels[0])
#ax2.set_title(labels[1])
#ax3.set_title(labels[2])
#ax4.set_title(labels[3])
#f.subplots_adjust(hspace=.5)
ax1.set_xlabel('')
ax2.set_xlabel('')
ax2.set_ylabel('')
def megaplot(ctsets,
             studyname,
             emisfops=None,
             labels=["$10^9$", "$10^8$", "$10^7$", "$10^6$"],
             axlabel='Primaries [nr]'):

    if len(ctsets) == 4:
        f, ((ax1, ax2), (ax3, ax4)) = plot.subplots(nrows=2,
                                                    ncols=2,
                                                    sharex=False,
                                                    sharey=False)

        auger.plot_all_ranges_CTONLY(ax1, ctsets[0])
        auger.plot_all_ranges_CTONLY(ax2, ctsets[1])
        auger.plot_all_ranges_CTONLY(ax3, ctsets[2])
        #auger.plot_all_ranges_CTONLY(ax4,ctsets[3])
        if not 'Primaries' in axlabel:
            ax1.set_title(labels[0])
            ax2.set_title(labels[1])
            ax3.set_title(labels[2])
            #ax4.set_title(labels[3])
        f.subplots_adjust(hspace=.5)
        ax1.set_xlabel('')
        ax2.set_xlabel('')
        ax2.set_ylabel('')
        #ax4.set_ylabel('')
        f.savefig(studyname + '-' + typ + '-FOP.pdf', bbox_inches='tight')
        plot.close('all')

    #############################################################################################

    # print 'FOP shift distributions'

    # from mpl_toolkits.mplot3d import Axes3D
    # import matplotlib.pyplot as plt

    # fig = plt.figure()
    # ax1 = plt.axes(projection='3d')
    # ax1.view_init(30, -50)

    # for i,ctset in enumerate(ctsets):
    # 	auger.plotfodiffdist(ax1,ctset,i,emisfops,labels,axlabel)
    # 	if not emisfops == None:
    # 		fopshifts=[]
    # 		for fopset in emisfops:
    # 			fopshifts.append( fopset[-1]-fopset[0] )
    # 		ax1.set_xlim3d(np.mean(fopshifts)-20,np.mean(fopshifts)+20)
    # if emisfops is not None and len(emisfops) == 1:
    # 	ax1.set_title(studyname+', $Shift_{em}$ = '+str(emisfops[0][-1]-emisfops[0][0]), y=1.08)

    # #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    # fig.savefig(studyname+'-'+typ+'-FOP-shift.pdf')#, bbox_inches='tight')
    # plt.close('all')

    #############################################################################################

    # print 'FOP FOW Contrast DE averages over 10e9 ctset'

    f, (ax1, ax2, ax3) = plot.subplots(nrows=3,
                                       ncols=1,
                                       sharex=False,
                                       sharey=False)
    x = ctsets[0]['ct']['x']
    y = ctsets[0]['ct']['av']
    if 'iba' in ctsets[0]['name']:  # ctset['name'] == typ
        mm = 4 / 0.8
    if 'ipnl' in ctsets[0]['name']:
        mm = 8
    falloff_pos, g_fwhm, contrast = auger.get_fop_fow_contrast(
        x,
        y,
        plot='wut',
        ax=ax1,
        ax2=ax2,
        ax3=ax3,
        smooth=0.2,
        filename=ctsets[0]['ct']['path'],
        contrast_divisor=ctsets[0]['nprim'] * len(ctsets[0]['ct']['files']) *
        mm,
        fitlines=False)
    print "NPRIM", ctsets[0]['nprim'], "NJOBS", len(
        ctsets[0]['ct']['files']), "MM", mm

    #gebruiken deze falloff_pos niet. we doen contrast en fow over de average van 50 batches wegens smoothe curve. daardoor geen sigma

    f.savefig(studyname + '-' + typ + '-FOW.pdf', bbox_inches='tight')
    plot.close('all')

    #############################################################################################

    # results table

    for ctset in ctsets:
        res = [
            typ, ctset['nprim'], ctset['ct']['fopmu'], ctset['ct']['fopsigma'],
            g_fwhm, contrast, ctset['detyieldmu'], ctset['detyieldsigma']
        ]

        if precolli:
            res.extend(
                [ctset['precollidetyieldmu'], ctset['precollidetyieldsigma']])

        resultstable.append(res)
        if pgexit and '3' in typ:
            res[-2] = res[-2] * pgprod_ratio_3mev
        elif pgexit and '1' in typ:
            res[-2] = res[-2] * pgprod_ratio_1mev

    #############################################################################################

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    print 'FOP distributions'

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    for i, ctset in enumerate(ctsets):
        auger.plotfodist_CTONLY(ax1, ctset, i, emisfops, labels, axlabel)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname + ', $CT_{FOP_{em}}$ = ' +
                      str(emisfops[0][0])[:5] + ', $RPCT_{FOP_{em}}$ = ' +
                      str(emisfops[0][1])[:5],
                      y=1.08)

    #plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    plt.savefig(studyname + '-' + typ +
                '-FOP-dist.pdf')  #, bbox_inches='tight')
    plt.close('all')
def megaplot(ctsets,studyname,emisfops=None,labels=["$10^9$","$10^8$","$10^7$","$10^6$"],axlabel='Primaries [nr]'):
	if emisfops is not None:
		for emisfop in emisfops:
			emisfop[0]+=15.863
			emisfop[1]+=15.863
	print 'FOP shift all overlaid'

	if len(ctsets) == 4:
		f, ((ax1,ax2),(ax3,ax4)) = plot.subplots(nrows=2, ncols=2, sharex=False, sharey=False)

		auger.plot_all_ranges(ax1,ctsets[0])
		auger.plot_all_ranges(ax2,ctsets[1])
		auger.plot_all_ranges(ax3,ctsets[2])
		auger.plot_all_ranges(ax4,ctsets[3])
		if not 'Primaries' in axlabel:
			ax1.set_title(labels[0])
			ax2.set_title(labels[1])
			ax3.set_title(labels[2])
			ax4.set_title(labels[3])
		f.subplots_adjust(hspace=.5)
		ax1.set_xlabel('')
		ax2.set_xlabel('')
		ax2.set_ylabel('')
		ax4.set_ylabel('')
		f.savefig(studyname+'-'+typ+'-FOP.pdf', bbox_inches='tight')
		plot.close('all')

	#############################################################################################

	print 'FOP shift distributions'

	from mpl_toolkits.mplot3d import Axes3D
	import matplotlib.pyplot as plt

	fig = plt.figure()
	ax1 = plt.axes(projection='3d')
	ax1.view_init(30, -50)

	for i,ctset in enumerate(ctsets):
		auger.plotfodiffdist(ax1,ctset,i,emisfops,labels,axlabel)
		if not emisfops == None:
			fopshifts=[]
			for fopset in emisfops:
				fopshifts.append( fopset[-1]-fopset[0] )
			ax1.set_xlim3d(np.mean(fopshifts)-20,np.mean(fopshifts)+20)
	if emisfops is not None and len(emisfops) == 1:
		ax1.set_title(studyname+', $Shift_{em}$ = '+str(emisfops[0][-1]-emisfops[0][0]), y=1.08)
	
	#plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
	fig.savefig(studyname+'-'+typ+'-FOP-shift.pdf')#, bbox_inches='tight')
	plt.close('all')

	#############################################################################################

	print 'FOP distributions'

	fig = plt.figure()
	ax1 = plt.axes(projection='3d')
	ax1.view_init(30, -50)

	for i,ctset in enumerate(ctsets):
		auger.plotfodist(ax1,ctset,i,emisfops,labels,axlabel)
	if emisfops is not None and len(emisfops) == 1:
		ax1.set_title(studyname+', $CT_{FOP_{em}}$ = '+str(emisfops[0][0])[:5]+', $RPCT_{FOP_{em}}$ = '+str(emisfops[0][1])[:5], y=1.08)

	#plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

	#plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
	plt.savefig(studyname+'-'+typ+'-FOP-dist.pdf')#, bbox_inches='tight')
	plt.close('all')
for rootfile in rootfiles:
    all = dump.get2D(rootfile,['X','Y'])
    phot_trans = dump.get2D(rootfile,['X','Y'],ParticleName='gamma',Primary=True,Transmission=True) #transmission implies primary and gamma but anyway
    phot_scatter = dump.get2D(rootfile,['X','Y'],ParticleName='gamma',Primary=True,Transmission=False)
    phot_other = dump.get2D(rootfile,['X','Y'],ParticleName='gamma',Primary=False)
    nonphot = dump.get2D(rootfile,['X','Y'],ParticleName='not_gamma')
    
    all_E = dump.get1D(rootfile,'Ekine')
    phot_trans_E = dump.get1D(rootfile,'Ekine',ParticleName='gamma',Primary=True,Transmission=True)
    phot_scatter_E = dump.get1D(rootfile,'Ekine',ParticleName='gamma',Primary=True,Transmission=False)
    phot_other_E = dump.get1D(rootfile,'Ekine',ParticleName='gamma',Primary=False)
    nonphot_E = dump.get1D(rootfile,'Ekine',ParticleName='not_gamma')
    
    partname = dump.get1D(rootfile,'ParticleName')
    
    f, ((ax1 ,ax2 ,ax3 ,ax4, ax5),(ax6, ax7 ,ax8, ax9 ,ax10),(ax11 ,ax12, ax13, ax14, ax15))= plot.subplots(nrows=3, ncols=5, sharex=False, sharey=False)#,figsize=(28,10))
    
    f.subplots_adjust(hspace=.5)
    f.subplots_adjust(wspace=.5)
    
    ax1.set_title("Total Counts")
    ax2.set_title("Prim Trans")
    ax3.set_title("Prim Scat")
    ax4.set_title("Secon Phot")
    ax5.set_title("Nonphot")
    
    # BIN EDGES!
    xbins = np.linspace(-410/2.,410/2.,256+1)
    ybins = np.linspace(-410/2.,410/2.,256+1)
    
    a = plot.plot2dhist( ax1, all['X'], all['Y'], xbins=xbins,ybins=ybins, log=True)
def megaplot(ctsets,studyname,emisfops=None,labels=["$10^9$","$10^8$","$10^7$","$10^6$"],axlabel='Primaries [nr]'):

	if len(ctsets) == 4:
		f, ((ax1,ax2),(ax3,ax4)) = plot.subplots(nrows=2, ncols=2, sharex=False, sharey=False)

		auger.plot_all_ranges_CTONLY(ax1,ctsets[0])
		auger.plot_all_ranges_CTONLY(ax2,ctsets[1])
		auger.plot_all_ranges_CTONLY(ax3,ctsets[2])
		auger.plot_all_ranges_CTONLY(ax4,ctsets[3])
		if not 'Primaries' in axlabel:
			ax1.set_title(labels[0])
			ax2.set_title(labels[1])
			ax3.set_title(labels[2])
			ax4.set_title(labels[3])
		f.subplots_adjust(hspace=.5)
		ax1.set_xlabel('')
		ax2.set_xlabel('')
		ax2.set_ylabel('')
		ax4.set_ylabel('')
		f.savefig(studyname+'-'+typ+'-FOP.pdf', bbox_inches='tight')
		plot.close('all')

	#############################################################################################

	# print 'FOP shift distributions'

	# from mpl_toolkits.mplot3d import Axes3D
	# import matplotlib.pyplot as plt

	# fig = plt.figure()
	# ax1 = plt.axes(projection='3d')
	# ax1.view_init(30, -50)

	# for i,ctset in enumerate(ctsets):
	# 	auger.plotfodiffdist(ax1,ctset,i,emisfops,labels,axlabel)
	# 	if not emisfops == None:
	# 		fopshifts=[]
	# 		for fopset in emisfops:
	# 			fopshifts.append( fopset[-1]-fopset[0] )
	# 		ax1.set_xlim3d(np.mean(fopshifts)-20,np.mean(fopshifts)+20)
	# if emisfops is not None and len(emisfops) == 1:
	# 	ax1.set_title(studyname+', $Shift_{em}$ = '+str(emisfops[0][-1]-emisfops[0][0]), y=1.08)

	# #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
	# fig.savefig(studyname+'-'+typ+'-FOP-shift.pdf')#, bbox_inches='tight')
	# plt.close('all')


	f, (ax1,ax2,ax3) = plot.subplots(nrows=3, ncols=1, sharex=False, sharey=False)

	x=ctsets[0]['rpct']['x']
	y=ctsets[0]['ct']['av']
	auger.get_fow(x,y,plot='wut',ax=ax1,ax2=ax2,ax3=ax3,smooth=0.2,filename=ctsets[0]['ct']['path']) #since high statistics, no smoothing needed
    # ax1.set_title('FOP = '+str(falloff_pos), fontsize=8)
	f.savefig(studyname+'-'+typ+'-FOW.pdf', bbox_inches='tight')
	plot.close('all')

	#############################################################################################

	from mpl_toolkits.mplot3d import Axes3D
	import matplotlib.pyplot as plt

	print 'FOP distributions'

	fig = plt.figure()
	ax1 = plt.axes(projection='3d')
	ax1.view_init(30, -50)

	for i,ctset in enumerate(ctsets):
		auger.plotfodist_CTONLY(ax1,ctset,i,emisfops,labels,axlabel)
	if emisfops is not None and len(emisfops) == 1:
		ax1.set_title(studyname+', $CT_{FOP_{em}}$ = '+str(emisfops[0][0])[:5]+', $RPCT_{FOP_{em}}$ = '+str(emisfops[0][1])[:5], y=1.08)

	#plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

	#plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
	plt.savefig(studyname+'-'+typ+'-FOP-dist.pdf')#, bbox_inches='tight')
	plt.close('all')
Esempio n. 35
0
def megaplot(ctsets,
             studyname,
             emisfops=None,
             labels=["$10^9$", "$10^8$", "$10^7$", "$10^6$"],
             axlabel='Primaries [nr]'):
    #if emisfops is not None:
    #for emisfop in emisfops:
    #emisfop[0]+=15.863
    #emisfop[1]+=15.863
    print 'FOP shift all overlaid'

    #if len(ctsets) == 3:
    #f, (ax1,ax2,ax3) = plot.subplots(nrows=1, ncols=3, sharex=False, sharey=False)
    #auger.plot_all_ranges(ax1,ctsets[0])
    #auger.plot_all_ranges(ax2,ctsets[1])
    #auger.plot_all_ranges(ax3,ctsets[2])
    #f.savefig(studyname+'-'+typ+'-FOP.pdf', bbox_inches='tight')
    #plot.close('all')
    #f.subplots_adjust(hspace=.5)
    #ax2.set_ylabel('')
    #ax3.set_ylabel('')

    if len(ctsets) > 2:
        f, ((ax1, ax2), (ax3, ax4)) = plot.subplots(nrows=2,
                                                    ncols=2,
                                                    sharex=False,
                                                    sharey=False)
        ax1.set_xlabel('')
        ax2.set_xlabel('')
        ax2.set_ylabel('')
        ax4.set_ylabel('')
    elif len(ctsets) == 2:
        f, (ax1, ax2) = plot.subplots(nrows=1,
                                      ncols=2,
                                      sharex=False,
                                      sharey=False)
        ax2.set_xlabel('')

    f.subplots_adjust(hspace=0.7, wspace=0.5)

    auger.plot_all_ranges(ax1, ctsets[0])
    auger.plot_all_ranges(ax2, ctsets[1])
    if len(ctsets) > 2:
        try:
            auger.plot_all_ranges(ax3, ctsets[2])
        except:
            ax3.axis('off')
        try:
            auger.plot_all_ranges(ax4, ctsets[3])
        except:
            ax4.axis('off')

    #auger.plot_single_range(ax1,ctsets[0])
    #auger.plot_single_range(ax2,ctsets[1])
    #auger.plot_single_range(ax3,ctsets[2])
    #auger.plot_single_range(ax4,ctsets[3])

    if not 'Primaries' in axlabel:
        ax1.set_title(labels[0])
        ax2.set_title(labels[1])
        #ax3.set_title(labels[2])
        #ax4.set_title(labels[3])

    #if 'waterbox' in studyname:
    #import matplotlib
    #matplotlib.pyplot.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
    #f.subplots_adjust(wspace=.3)

    #x0 = []
    #y1 = []
    #y1std = []
    #y2 = []
    #y2std = []
    #for ct in ctsets:
    #x0.append(1./sqrt(ct['nprim']))
    #y1.append(ct['ct']['fopsigma'])
    #y2.append(ct['rpct']['fopsigma'])
    #y1std.append( ct['ct']['fopsigma']/sqrt(2*(len(ct['ct']['falloff'])-1)) )
    #y2std.append( ct['rpct']['fopsigma']/sqrt(2*(len(ct['rpct']['falloff'])-1)) )
    #plot.plot_errorbands(ax4,x0,y1,y1std,color='steelblue')
    #plot.plot_errorbands(ax4,x0,y2,y2std,color='indianred')
    ##ax4.set_xlim(x[0],x[-1])
    ##ax4.set_ylim(y[0],y[-1])
    #ax4.set_title('CNR check', fontsize=8)
    #ax4.set_xlabel('1/sqrt(N$_{prim}$)', fontsize=8)
    ##ax4.set_ylabel('sqrt(background)/signal', fontsize=8)
    #ax4.set_ylabel('$\sigma_{FOP} [mm]$', fontsize=8)
    #plot.texax(ax4)

    f.savefig(studyname + '-' + typ + '-FOP.pdf', bbox_inches='tight')
    plot.close('all')

    #############################################################################################

    print 'FOP shift distributions'

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    tmpprim = 0
    center = 0
    for ctset in ctsets:
        if ctset['nprim'] > tmpprim:
            tmpprim = ctset['nprim']
            center = ctset['fodiffmu']

    for i, ctset in enumerate(ctsets):
        auger.plotfodiffdist(ax1, ctset, i, emisfops, labels, axlabel, center)
        if not emisfops == None:
            fopshifts = []
            for fopset in emisfops:
                fopshifts.append(fopset[-1] - fopset[0])
            ax1.set_xlim3d(np.mean(fopshifts) - 20, np.mean(fopshifts) + 20)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname + ', $Shift_{em}$ = ' +
                      str(emisfops[0][-1] - emisfops[0][0]),
                      y=1.08)
        pass

    #fig.suptitle('FOP shifts', fontsize=10)
    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    fig.savefig(studyname + '-' + typ +
                '-FOP-shift.pdf')  #, bbox_inches='tight')
    plt.close('all')

    #############################################################################################

    print 'FOP distributions'

    fig = plt.figure()
    ax1 = plt.axes(projection='3d')
    ax1.view_init(30, -50)

    tmpprim = 0
    center = 0
    for ctset in ctsets:
        if ctset['nprim'] > tmpprim:
            tmpprim = ctset['nprim']
            center = (ctset['ct']['fopmu'] + ctset['rpct']['fopmu']) / 2.

    for i, ctset in enumerate(ctsets):
        auger.plotfodist(ax1, ctset, i, emisfops, labels, axlabel, center)
    if emisfops is not None and len(emisfops) == 1:
        ax1.set_title(studyname + ', $CT_{FOP_{em}}$ = ' +
                      str(emisfops[0][0])[:5] + ', $RPCT_{FOP_{em}}$ = ' +
                      str(emisfops[0][1])[:5],
                      y=1.08)

    #plt.legend()#shadow = True,frameon = True,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'lower right')

    #plt.tight_layout(rect = [-0.1, 0.0, 1.0, 1.1])#L,B,R,T
    #fig.suptitle('FOP distributions', fontsize=10)
    plt.savefig(studyname + '-' + typ +
                '-FOP-dist.pdf')  #, bbox_inches='tight')
    plt.close('all')
Esempio n. 36
0
#!/usr/bin/env python3
import numpy as np, matplotlib as mpl, plot, sys, re

clrs = plot.colors

f, ax1 = plot.subplots(nrows=1, ncols=1, sharex=False, sharey=False)

x = [1, 2, 3, 7]

cpu = [174.116, 124.691, 128.150, 133.497]
gpu = [133.161, 102.820, 94.058, 90.751]
#cpu_cost = ['CPU (Threadripper 1920X)']*657
#gpu_cost = ['GPU (Quadro M6000 12GB)']*2406
#ratio_cost = ['Ratio']*2406

ax1.set_title('GPUMCD runtimes')
ax1.set_xlabel('Streams')
ax1.set_ylabel('Runtime [s]')
ax1.plot(x, cpu, color=clrs[0], lw=1, label='CPU (2x XeonE5-2630v3)')
ax1.plot(x, gpu, color=clrs[1], lw=1, label='GPU (1x TitanXp)')
ax2 = ax1.twinx()
ax2.plot(x, [i / j * 100. - 100. for i, j in zip(cpu, gpu)],
         color=clrs[2],
         lw=1,
         label='GPU speed advantage')
ax2.set_ylabel('Speed up (+%)')
ax1.legend(loc='upper left', frameon=False)
ax2.legend(loc='upper right', bbox_to_anchor=(1., 1.), frameon=False)
ax1.set_ylim(bottom=0.)

#ax9.set_title('Cost')