def get_unc(ax1,dataset,refdata,ax,typ='parodi'): colors = plot.colors color_index=0 #asume voxels are 2mm if 'Z' in ax and 'parodi' in typ: x_axis = np.linspace(0,222,111) if 'Y' in ax and 'head' in typ: x_axis = np.linspace(0,170,85) if 'E' in ax: x_axis = np.linspace(0,10,250) for key, valuee in iter(sorted(dataset.iteritems())): value = valuee[ax] ax1.step(x_axis,[x*100. for x in value['unc']], label=plot.sn_mag(key)+' primaries', color=colors[color_index]) color_index+=1 refdata = refdata[ax] ax1.step(x_axis,[x*100. for x in refdata['unc']], label='Reference', color='k') ax1.semilogy() ax1.autoscale(axis='x',tight=True) #ax1.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.0f%%')) #PG falloff line spectcutoff = [1,8] if ax == 'E': ax1.set_xlim(spectcutoff) # if ax == 'E': # ax1.axvline(spectcutoff[0], color='#999999', ls='--') # ax1.axvline(spectcutoff[1], color='#999999', ls='--') plot.texax(ax1)
def get_reluncconv(ax1,xlist,ylist,func=None): colors = 'rk' labels = ['vpgTLE','Analog'] get_reluncconv.color_index+=1 #set default fit 1/sqrt(x) if func is None: def func(x,b):#var, params return b/np.sqrt(x) # return a+b/np.sqrt(x) parameter, covariance_matrix = curve_fit(func, xlist, ylist) threshold = fsolve(lambda x: func(x,*parameter)-.02, 1e1) #initial guess at 1e3 x = np.linspace(min(xlist), max([threshold,max(xlist)]), 1e5) y = func(x, *parameter) #'Fit: '+plot.sn(parameter[0])+'+\n'+plot.sn(parameter[1])+'/$\sqrt{runtime}$' fitlabel = labels[get_reluncconv.color_index]+', Fit:\n'+r'$\frac{%s}{\sqrt{t}}$'%plot.snS(parameter[0]) ax1.scatter(xlist, [100*i for i in ylist],marker='x',s=100,color=colors[get_reluncconv.color_index]) ax1.plot(x, 100*y, 'b-',label=fitlabel,color=colors[get_reluncconv.color_index]) ax1.autoscale(axis='x',tight=True) ax1.autoscale(axis='y',tight=True) ax1.axhline(100*0.02, color='#666666', ls='--') ax1.axvline(threshold, color='#999999', ls='--') plot.texax(ax1) print "Crossing 2pc threshold at %.2e"%threshold return threshold
def plot_all_ranges(ax1,ct): for i in range(len(ct['ct']['data'])): x,y,fo=ct['ct']['x'],ct['ct']['data'][i],ct['ct']['falloff'][i] ax1.step(x, y, label=ct['name']+'ct', color='steelblue', lw=1, where='mid',clip_on=False, alpha=0.5) ax1.axvline(fo, color='steelblue', ls='-',lw=1, alpha=0.5) ax1.set_xlabel('Depth [mm]', fontsize=FONTSIZE) ax1.set_ylabel('PG detected [counts]', fontsize=FONTSIZE) ax1.set_title(plot.sn(ct['nprim'],0)+' primaries', fontsize=Fontsize) plot.texax(ax1) for i in range(len(ct['rpct']['data'])): x,y,fo=ct['rpct']['x'],ct['rpct']['data'][i],ct['rpct']['falloff'][i] ax1.step(x, y, label=ct['name']+'ct', color='indianred', lw=1, where='mid',clip_on=False, alpha=0.5) ax1.axvline(fo, color='indianred', ls='-',lw=1, alpha=0.5) if str(ct['nprim'])[1] == '0': ax1.set_title('PG detection for '+plot.sn_mag(ct['nprim'])+' primaries', fontsize=Fontsize) else: ax1.set_title('PG detection for '+plot.sn(ct['nprim'])+' primaries', fontsize=Fontsize) ax1.set_ylim(bottom=0) ct_labelextra = '' rpct_labelextra = '' if True: ct_labelextra += 'CT DE: '+plot.sn(ct['ct']['detyieldmu']) #yield per prot rpct_labelextra += 'RPCT DE: '+plot.sn(ct['rpct']['detyieldmu']) ax1.text(0.05, 0.95, ct_labelextra , ha='left', va='center', fontsize=Fontsize, transform=ax1.transAxes) ax1.text(0.05, 0.8, rpct_labelextra , ha='left', va='center', fontsize=Fontsize, transform=ax1.transAxes) plot.texax(ax1)
def plotrange(ax1,ct): x = ct['ct']['x'] y = ct['ct']['av'] um = ct['ct']['uncm'] up = ct['ct']['uncp'] ymax = max(y) if len(um)>0: ymax = max(ymax,max(up)) plot.fill_between_steps(ax1, x, um, up, alpha=0.2, color='steelblue', lw=0.5,clip_on=False) #doesnt support where=mid else: ax1.step(x, y, label=ct['name']+'ct', color='steelblue', lw=1, where='mid',clip_on=False) #ax1.step(x, y, label=ct['name']+'ct', color='steelblue', lw=1, where='mid') x = ct['rpct']['x'] y = ct['rpct']['av'] um = ct['rpct']['uncm'] up = ct['rpct']['uncp'] ymax = max(ymax,max(y)) if len(um)>0: ymax = max(ymax,max(up)) plot.fill_between_steps(ax1, x, um, up, alpha=0.2, color='indianred', lw=0.5,clip_on=False) else: ax1.step(x, y, label=ct['name']+'rpct', color='indianred', lw=1, where='mid',clip_on=False) #ax1.step(x, y, label=ct['name']+'rpct', color='indianred', lw=1, where='mid') ax1.set_xlabel('Depth [mm]', fontsize=FONTSIZE) ax1.set_ylabel('PG detected [counts]', fontsize=FONTSIZE) ax1.set_ylim(bottom=0,top=ymax) #ax1.set_title('PG detection for '+plot.sn_mag(ct['nprim'])+'primaries', fontsize=FONTSIZE) plot.texax(ax1)
def get_effhist(ax1,image,name=None): colors = plot.colors get_effhist.color_index+=1 data = image.imdata[~np.isnan(image.imdata)].flatten() if np.nanmin(data) == 0: binn = np.logspace(1,np.log10(np.nanmax(data))) label = plot.sn_mag(image.nprim)+" primaries\nMin: "+str(0)+"\nMax: "+plot.sn(np.nanmax(data)) else: binn = np.logspace(np.log10(np.nanmin(data)),np.log10(np.nanmax(data))) label = plot.sn_mag(image.nprim)+" primaries\nMin: "+plot.sn(np.nanmin(data))+"\nMax: "+plot.sn(np.nanmax(data)) hist,bins = np.histogram(data, bins=binn) center = (bins[:-1] + bins[1:]) / 2 bins=center # hist[0] = 0 # hist[-1] = 0 if name is None: ax1.plot(bins,hist/float(hist.max()),label=label,color=colors[get_effhist.color_index],drawstyle='steps') else: ax1.plot(bins,hist/float(hist.max()),label=name+'\nMedian gain: '+plot.sn(np.median(data)),color=colors[get_effhist.color_index],drawstyle='steps') ax1.semilogx() plot.texax(ax1) # print 'Median of efficiency:',np.median(data) # print 'Mean of efficiency:',np.mean(data) return [np.nanmin(data),np.median(data),np.nanmax(data),np.mean(data)]
def get_yield(ax1,dataset,refdata,ax,typ='parodi'): colors = plot.colors color_index=0 #asume voxels are 2mm if 'Z' in ax and 'parodi' in typ: x_axis = np.linspace(0,222,111) if 'Y' in ax and 'head' in typ: x_axis = np.linspace(0,170,85) if 'E' in ax: x_axis = np.linspace(0,10,250) for key, valuee in iter(sorted(dataset.iteritems())): # if TLE value = valuee[ax] # print ax, len(value['yield']) ax1.step(x_axis,value['yield'], label=plot.sn_mag(key)+' primaries', color=colors[color_index], lw=0.5) plot.fill_between_steps(ax1, x_axis, value['yield-unc'], value['yield+unc'], alpha=0.5, color=colors[color_index], lw=0.5) color_index+=1 #analog reference refdata = refdata[ax] ax1.step(x_axis,refdata['yield'], label='Reference', color='k', lw=0.5) plot.fill_between_steps(ax1, x_axis, refdata['yield-unc'], refdata['yield+unc'], alpha=0.5, color='k', lw=0.5) ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) ax1.autoscale(axis='x',tight=True) # #PG falloff line parodi spectcutoff = [1,8] if ax == 'E': ax1.set_xlim(spectcutoff) plot.texax(ax1)
def get_yield(ax1, dataset, refdata, ax, typ='parodi'): colors = plot.colors color_index = 0 #asume voxels are 2mm if 'Z' in ax and 'parodi' in typ: x_axis = np.linspace(0, 222, 111) if 'Y' in ax and 'head' in typ: x_axis = np.linspace(0, 170, 85) if 'E' in ax: x_axis = np.linspace(0, 10, 250) for key, valuee in iter(sorted(dataset.iteritems())): # if TLE value = valuee[ax] # print ax, len(value['yield']) ax1.step(x_axis, value['yield'], label=plot.sn_mag(key) + ' primaries', color=colors[color_index], lw=0.5) plot.fill_between_steps(ax1, x_axis, value['yield-unc'], value['yield+unc'], alpha=0.5, color=colors[color_index], lw=0.5) color_index += 1 #analog reference refdata = refdata[ax] ax1.step(x_axis, refdata['yield'], label='Reference', color='k', lw=0.5) plot.fill_between_steps(ax1, x_axis, refdata['yield-unc'], refdata['yield+unc'], alpha=0.5, color='k', lw=0.5) ax1.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax1.autoscale(axis='x', tight=True) # #PG falloff line parodi spectcutoff = [1, 8] if ax == 'E': ax1.set_xlim(spectcutoff) plot.texax(ax1)
def get_relunc(ax1, dataset, refdata, ax, typ='parodi'): colors = plot.colors color_index = 0 #asume voxels are 2mm if 'Z' in ax and 'parodi' in typ: x_axis = np.linspace(0, 222, 111) if 'Y' in ax and 'head' in typ: x_axis = np.linspace(0, 170, 85) if 'E' in ax: x_axis = np.linspace(0, 10, 250) for key, valuee in iter(sorted(dataset.iteritems())): value = valuee[ax] try: ax1.step(x_axis, [x * 100. for x in value['relunc']], label=plot.sn_mag(key) + ' primaries', color=colors[color_index]) except TypeError: ax1.step(x_axis, [x * 100. for x in value['relunc']], label=key, color=colors[color_index]) color_index += 1 if refdata is not None: refdata = refdata[ax] ax1.step(x_axis, [x * 100. for x in refdata['relunc']], label='Reference', color='k') ax1.semilogy() ax1.autoscale(axis='x', tight=True) #ax1.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.0f%%')) #PG falloff line spectcutoff = [1, 8] if ax == 'E': ax1.set_xlim(spectcutoff) # if ax == 'E': # ax1.axvline(spectcutoff[0], color='#999999', ls='--') # ax1.axvline(spectcutoff[1], color='#999999', ls='--') plot.texax(ax1)
def get_reldiff(ax1, dataset, ax, typ='parodi'): colors = plot.colors color_index = 0 #asume voxels are 2mm if 'Z' in ax and 'parodi' in typ: x_axis = np.linspace(0, 222, 111) if 'Y' in ax and 'head' in typ: x_axis = np.linspace(0, 170, 85) if 'E' in ax: x_axis = np.linspace(0, 10, 250) for key, valuee in iter(sorted(dataset.iteritems())): value = valuee[ax] ax1.step(x_axis, [x * 100. for x in value['reldiff']], label=plot.sn_mag(key) + ' primaries', color=colors[color_index], lw=0.5) print key, __withinsigma(value) plot.fill_between_steps(ax1, x_axis, [x * 100. for x in value['reldiff-2sigma']], [x * 100. for x in value['reldiff+2sigma']], alpha=0.25, color=colors[color_index], lw=0.01) color_index += 1 ax1.autoscale(axis='x', tight=True) #ax1.set_ylim([-4,4]) # #PG falloff line parodi spectcutoff = [1, 8] if ax == 'E': ax1.set_xlim(spectcutoff) # if ax == 'E': # ax1.axvline(spectcutoff[0], color='#999999', ls='--') # ax1.axvline(spectcutoff[1], color='#999999', ls='--') plot.texax(ax1)
def get_reluncconv(ax1, xlist, ylist, func=None): colors = 'rk' labels = ['vpgTLE', 'Analog'] get_reluncconv.color_index += 1 #set default fit 1/sqrt(x) if func is None: def func(x, b): #var, params return b / np.sqrt(x) # return a+b/np.sqrt(x) parameter, covariance_matrix = curve_fit(func, xlist, ylist) threshold = fsolve(lambda x: func(x, *parameter) - .02, 1e1) #initial guess at 1e3 x = np.linspace(min(xlist), max([threshold, max(xlist)]), 1e5) y = func(x, *parameter) #'Fit: '+plot.sn(parameter[0])+'+\n'+plot.sn(parameter[1])+'/$\sqrt{runtime}$' fitlabel = labels[ get_reluncconv. color_index] + ', Fit:\n' + r'$\frac{%s}{\sqrt{t}}$' % plot.snS( parameter[0]) ax1.scatter(xlist, [100 * i for i in ylist], marker='x', s=100, color=colors[get_reluncconv.color_index]) ax1.plot(x, 100 * y, 'b-', label=fitlabel, color=colors[get_reluncconv.color_index]) ax1.autoscale(axis='x', tight=True) ax1.autoscale(axis='y', tight=True) ax1.axhline(100 * 0.02, color='#666666', ls='--') ax1.axvline(threshold, color='#999999', ls='--') plot.texax(ax1) print "Crossing 2pc threshold at %.2e" % threshold return threshold
def plot1d(ax1,dataset): colors = plot.colors color_index=0 #asume voxels are 2mm x_axis = np.linspace(0,10,250) key = 1e4 ax1.step(x_axis,[x*100. for x in dataset], label=plot.sn_mag(key)+' primaries', color=colors[color_index]) color_index+=1 ax1.semilogy() ax1.autoscale(axis='x',tight=True) #ax1.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.0f%%')) #PG falloff line spectcutoff = [1,8] ax1.set_xlim(spectcutoff) plot.texax(ax1)
def plot_single_range(ax1,ct): for i in range(len(ct['ct']['data'])): x,y,fo=ct['ct']['x'],ct['ct']['data'][i],ct['ct']['falloff'][i] ax1.step(x, y, label=ct['name']+'ct', color='steelblue', lw=1, where='mid',clip_on=False, alpha=0.5) ax1.axvline(fo, color='steelblue', ls='-',lw=1, alpha=0.5) break ax1.set_xlabel('Depth [mm]', fontsize=FONTSIZE) ax1.set_ylabel('PG detected [counts]', fontsize=FONTSIZE) ax1.set_title(plot.sn(ct['nprim'],0)+' primaries', fontsize=FONTSIZE) plot.texax(ax1) for i in range(len(ct['rpct']['data'])): x,y,fo=ct['rpct']['x'],ct['rpct']['data'][i],ct['rpct']['falloff'][i] ax1.step(x, y, label=ct['name']+'ct', color='indianred', lw=1, where='mid',clip_on=False, alpha=0.5) ax1.axvline(fo, color='indianred', ls='-',lw=1, alpha=0.5) break ax1.set_title('PG detection for '+plot.sn_mag(ct['nprim'])+'primaries', fontsize=FONTSIZE) ax1.set_ylim(bottom=0) plot.texax(ax1)
def get_reldiff(ax1,dataset,ax,typ='parodi'): colors = plot.colors color_index=0 #asume voxels are 2mm if 'Z' in ax and 'parodi' in typ: x_axis = np.linspace(0,222,111) if 'Y' in ax and 'head' in typ: x_axis = np.linspace(0,170,85) if 'E' in ax: x_axis = np.linspace(0,10,250) for key, valuee in iter(sorted(dataset.iteritems())): value = valuee[ax] ax1.step(x_axis, [x*100. for x in value['reldiff']], label=plot.sn_mag(key) +' primaries', color=colors[color_index], lw=0.5) print key, __withinsigma(value) plot.fill_between_steps(ax1, x_axis, [x*100. for x in value['reldiff-2sigma']], [x*100. for x in value['reldiff+2sigma']], alpha=0.25, color=colors[color_index], lw=0.01) color_index+=1 ax1.autoscale(axis='x',tight=True) #ax1.set_ylim([-4,4]) # #PG falloff line parodi spectcutoff = [1,8] if ax == 'E': ax1.set_xlim(spectcutoff) # if ax == 'E': # ax1.axvline(spectcutoff[0], color='#999999', ls='--') # ax1.axvline(spectcutoff[1], color='#999999', ls='--') plot.texax(ax1)
def get_effhist(ax1, image, name=None): colors = plot.colors get_effhist.color_index += 1 data = image.imdata[~np.isnan(image.imdata)].flatten() if np.nanmin(data) == 0: binn = np.logspace(1, np.log10(np.nanmax(data))) label = plot.sn_mag( image.nprim) + " primaries\nMin: " + str(0) + "\nMax: " + plot.sn( np.nanmax(data)) else: binn = np.logspace(np.log10(np.nanmin(data)), np.log10(np.nanmax(data))) label = plot.sn_mag(image.nprim) + " primaries\nMin: " + plot.sn( np.nanmin(data)) + "\nMax: " + plot.sn(np.nanmax(data)) hist, bins = np.histogram(data, bins=binn) center = (bins[:-1] + bins[1:]) / 2 bins = center # hist[0] = 0 # hist[-1] = 0 if name is None: ax1.plot(bins, hist / float(hist.max()), label=label, color=colors[get_effhist.color_index], drawstyle='steps') else: ax1.plot(bins, hist / float(hist.max()), label=name + '\nMedian gain: ' + plot.sn(np.median(data)), color=colors[get_effhist.color_index], drawstyle='steps') ax1.semilogx() plot.texax(ax1) # print 'Median of efficiency:',np.median(data) # print 'Mean of efficiency:',np.mean(data) return [np.nanmin(data), np.median(data), np.nanmax(data), np.mean(data)]
def plot_all_ranges_2(ax1,ct,firstcolor='steelblue',secondcolor='indianred'): yield_ct=0 for i in range(len(ct['ct']['data'])): yield_ct+=sum(ct['ct']['data'][i]) x,y,fo=ct['ct']['x'],ct['ct']['data'][i],ct['ct']['falloff'][i] ax1.step(x, y, label=ct['name']+'ct', color=firstcolor, lw=1, where='mid',clip_on=True, alpha=0.5) ax1.axvline(fo, color=firstcolor, ls='-',lw=1, alpha=0.5) yield_ct = yield_ct/len(ct['ct']['data']) #per realisatie if secondcolor is not None: yield_rpct=0 for i in range(len(ct['rpct']['data'])): yield_rpct+=sum(ct['rpct']['data'][i]) x,y,fo=ct['rpct']['x'],ct['rpct']['data'][i],ct['rpct']['falloff'][i] ax1.step(x, y, label=ct['name']+'ct', color=secondcolor, lw=1, where='mid',alpha=0.5, clip_on=True) ax1.axvline(fo, color=secondcolor, ls='-',lw=1, alpha=0.5) yield_rpct = yield_rpct/len(ct['rpct']['data']) #per realisatie plot.texax(ax1) return (yield_ct+yield_rpct)/(2.*ct['nprim']) return yield_ct/ct['nprim']
def plot1d(ax1, dataset): colors = plot.colors color_index = 0 #asume voxels are 2mm x_axis = np.linspace(0, 10, 250) key = 1e4 ax1.step(x_axis, [x * 100. for x in dataset], label=plot.sn_mag(key) + ' primaries', color=colors[color_index]) color_index += 1 ax1.semilogy() ax1.autoscale(axis='x', tight=True) #ax1.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.0f%%')) #PG falloff line spectcutoff = [1, 8] ax1.set_xlim(spectcutoff) plot.texax(ax1)
def get_effhist_oud(ax1, image, name=None): colors = plot.colors get_effhist.color_index += 1 data = image.imdata[~np.isnan(image.imdata)].flatten() # data=data/np.nanmax(data) # with np.errstate(divide='ignore', invalid='ignore'): # data = np.true_divide(data,np.nanmax(data)) #data = np.nonzero(data)] #print image.nprim,np.nanmin(data),np.nanmax(data) if np.nanmin(data) == 0: label = plot.sn_mag( image.nprim) + " primaries\nMin: " + str(0) + "\nMax: " + plot.sn( np.nanmax(data)) y, x, _ = ax1.hist(data, bins=np.logspace(1, np.log10(np.nanmax(data))), label=label, color=colors[get_effhist.color_index], histtype='step', lw=1) else: label = plot.sn_mag(image.nprim) + " primaries\nMin: " + plot.sn( np.nanmin(data)) + "\nMax: " + plot.sn(np.nanmax(data)) y, x, _ = ax1.hist(data, bins=np.logspace(np.log10(np.nanmin(data)), np.log10(np.nanmax(data))), label=label, color=colors[get_effhist.color_index], histtype='step', lw=1) print y.max() # label=str(image.nprim)+" primaries\nMin: "+str(np.nanmin(data))+"\nMax: "+str(np.nanmax(data)) # ax1.hist(data, bins = np.linspace(np.nanmin(data),np.nanmax(data)) ,label=label,color=colors[get_effhist.color_index],histtype='step', lw=1) ax1.semilogx() plot.texax(ax1) # print 'Median of efficiency:',np.median(data) # print 'Mean of efficiency:',np.mean(data) return [np.nanmin(data), np.median(data), np.nanmax(data), np.mean(data)]
def get_effhist_oud(ax1,image,name=None): colors = plot.colors get_effhist.color_index+=1 data = image.imdata[~np.isnan(image.imdata)].flatten() # data=data/np.nanmax(data) # with np.errstate(divide='ignore', invalid='ignore'): # data = np.true_divide(data,np.nanmax(data)) #data = np.nonzero(data)] #print image.nprim,np.nanmin(data),np.nanmax(data) if np.nanmin(data) == 0: label=plot.sn_mag(image.nprim)+" primaries\nMin: "+str(0)+"\nMax: "+plot.sn(np.nanmax(data)) y, x, _=ax1.hist(data, bins = np.logspace(1,np.log10(np.nanmax(data))) ,label=label,color=colors[get_effhist.color_index],histtype='step', lw=1) else: label=plot.sn_mag(image.nprim)+" primaries\nMin: "+plot.sn(np.nanmin(data))+"\nMax: "+plot.sn(np.nanmax(data)) y, x, _=ax1.hist(data, bins = np.logspace(np.log10(np.nanmin(data)),np.log10(np.nanmax(data))) ,label=label,color=colors[get_effhist.color_index],histtype='step', lw=1) print y.max() # label=str(image.nprim)+" primaries\nMin: "+str(np.nanmin(data))+"\nMax: "+str(np.nanmax(data)) # ax1.hist(data, bins = np.linspace(np.nanmin(data),np.nanmax(data)) ,label=label,color=colors[get_effhist.color_index],histtype='step', lw=1) ax1.semilogx() plot.texax(ax1) # print 'Median of efficiency:',np.median(data) # print 'Mean of efficiency:',np.mean(data) return [np.nanmin(data),np.median(data),np.nanmax(data),np.mean(data)]
#a = ax.pcolormesh(xbins, ybins, counts.T,cmap='Greys',norm=matplotlib.colors.LogNorm(), vmin=0.7) ax.set_xlim(min(xbins),max(xbins)) ax.set_ylim(min(spot[1]),max(spot[1])*1.05) ax.semilogy() except Exception as e: print str(e) pass if first: ax.set_ylabel('Spots\nNr. protons') first=False #ax.set_xlabel('$E$ [MeV]') plot.texax(ax) ax.set_title('Field '+str(fieldnr+1)+"\n"+str(len(spot[0]))+" spots\n"+str(len(set(spot[0])))+" layers") first = True for layer,ax in zip(layloop,layaxes): #1 is tweede rij try: xbins = plot.bincenters_to_binedges(sorted(layer[0])) ax.hist(layer[0],bins=xbins,weights=layer[1],bottom=min(layer[1])/100.,histtype='bar',color='grey',linewidth=0.2) new_layer_min_y = min(layer[1])/1.5 new_layer_max_y = max(layer[1])*1.5 if new_layer_min_y < layer_min_y: layer_min_y=new_layer_min_y ax.set_ylim(ymin=layer_min_y) if new_layer_max_y > layer_max_y: layer_max_y=new_layer_max_y
#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]') plot.texax(ax3) ax4.set_title('Dose Diff (E)') ax4.set_xlabel('Energy [MeV]') ax4.set_ylabel('Dose Diff [RMSE]') plot.texax(ax4)
def get_fop_fow_contrast(x,y,**kwargs): plotten = False plottenname = '' label='' threshold = 0.5 ax1 = '' smooth=2 fitlines=False globmax=False filename = '' if 'filename' in kwargs: filename = kwargs['filename'] if 'plot' in kwargs: plotten = True fitlines = True plottenname = str(kwargs['plot']) import plot if 'threshold' in kwargs: threshold = float(kwargs['threshold']) if 'globmax' in kwargs: globmax = float(kwargs['globmax']) if 'width' in kwargs: FOW = True if 'ax' in kwargs: if plotten == True: ax1 = kwargs['ax'] else: return if 'ax2' in kwargs: if plotten == True: ax2 = kwargs['ax2'] else: return if 'ax3' in kwargs: if plotten == True: ax3 = kwargs['ax3'] else: return if 'smooth' in kwargs: smooth = kwargs['smooth'] if 'label' in kwargs: label = kwargs['label'] if 'fitlines' in kwargs: fitlines = kwargs['fitlines'] if 'nprim' in kwargs: nprim = kwargs['nprim'] if 'contrast_divisor' in kwargs: contrast_divisor = kwargs['contrast_divisor'] y=np.array(y) # if plotten: import plot # if plotten: f, ax1 = plot.subplots(nrows=1, ncols=1, sharex=False, sharey=False) if plotten: ax1.scatter( x,y, color='black',marker="x",clip_on=False) #bindata #smooth that shit out. #https://en.wikipedia.org/wiki/Smoothing_spline y2 = scipy.signal.cspline1d(y,lamb=smooth) y_intpol_f = scipy.interpolate.interp1d(x,y2,kind='cubic') #interpolate function x_intpol = np.linspace(x[0],x[-1],2048,endpoint=False) y_intpol = y_intpol_f(x_intpol) #interpolate for x_intpol y_intpol = y_intpol.clip(min=0) #set any possible negatives to zero ####################################################################### CURVE IS COMPLETE, NOW ANALYSIS #if plotten: ax1.step(x,y2,color='steelblue', where='mid') if plotten: ax1.plot(x_intpol,y_intpol,color='indianred') #get 25 percentile, and take mean as baseline. baseline = y_intpol[y_intpol < np.percentile(y_intpol, 25)].mean() maxind=0 if globmax: maxind = np.where(y_intpol == y_intpol.max())[0][-1] #so that we find the LAST index where argmax(y) else: #global max globmaxind = np.where(y_intpol == y_intpol.max())[0][-1] globfalloff = y_intpol[globmaxind]-baseline #find distal local max within 30% of FO maxind = np.sort( scipy.signal.argrelextrema(y_intpol, np.greater)[0] )[::-1] for locmac in maxind[::-1]: #search from back if y_intpol[locmac] > (baseline+globfalloff*0.3): maxind = locmac #if fitlines: ax1.axhline(baseline+globfalloff*0.3,color='green') falloff = y_intpol[maxind]-baseline falloff_index=len(x_intpol)-1 print falloff try: while y_intpol[falloff_index] < threshold*falloff+baseline: #default threshold is 0.5 falloff_index-=1 except ValueError: print y_intpol[falloff_index] < threshold*falloff+baseline print y_intpol[falloff_index] print threshold print falloff print baseline #contrast = (y_intpol[maxind]-baseline)/(y_intpol[maxind]+baseline) contrast = y_intpol[maxind]-baseline/contrast_divisor falloff_pos=x_intpol[falloff_index] if fitlines: ax1.axvline(falloff_pos,color='green') if fitlines: ax1.axhline(baseline,color='green') if fitlines: ax1.axhline(y_intpol[maxind],color='green') if fitlines: ax1.axvline(x_intpol[maxind],color='green') if plotten: plot.texax(ax1) if plotten: ax1.set_xlabel('Position [mm]', fontsize=8) if plotten: ax1.set_ylabel('PG yield [counts]', fontsize=8) if plotten: from matplotlib.ticker import MaxNLocator if plotten: ax1.yaxis.set_major_locator(MaxNLocator(integer=True)) # if plotten: ax1.set_ylim(bottom=0) if plotten: ax1.annotate('FOP: '+str(falloff_pos)[:4],xy=(falloff_pos,falloff/2.+baseline)) if plotten: ax1.annotate('Contrast: '+str(contrast)[:4],xy=(x_intpol[maxind],y_intpol[maxind])) if plotten: print 'FOP is',falloff_pos if plotten: print 'Contrast is',contrast ################################################# FOW # first diff: y_intpol_diff = np.diff(y_intpol) # second diff: y_intpol_diff2 = np.diff(y_intpol_diff) # find inflex in second diff and plot # print "len y_intpol_diff2:", len(y_intpol_diff2) if plotten: ax3.plot(x_intpol[:-2],y_intpol_diff2,color='darkseagreen') diff2_zero_index = falloff_index while y_intpol_diff2[diff2_zero_index]*y_intpol_diff2[diff2_zero_index-1] >=0 or y_intpol_diff2[diff2_zero_index] > y_intpol_diff2[diff2_zero_index-1]: #zolang product positief, dan geen kruising van x as #zolang positieve kruising van xas ga dan verder diff2_zero_index+=1 if fitlines: ax3.axvline(x_intpol[diff2_zero_index],color='green') if fitlines: ax3.annotate('Inflex: '+str(x_intpol[diff2_zero_index])[:4],xy=(x_intpol[diff2_zero_index],0 ) ) # use inflex to set interval for gauss fit in first diff if plotten: ax2.plot(x_intpol[:-1],y_intpol_diff,color='steelblue') # fit_interval = x_intpol[maxind : falloff_index+(falloff_index-maxind)] fit_interval = x_intpol[maxind : diff2_zero_index] fit_points = y_intpol_diff[maxind : diff2_zero_index] #offset = y_intpol_diff[diff2_zero_index] offset = 0 #actually, lets remove this param if plotten: ax2.plot(fit_interval,fit_points,color='steelblue') try: popt,y_fitted = fitgauss_tuned(fit_interval,fit_points,falloff_pos,offset) except RuntimeError as e: raise RuntimeError("in scipy.optimize.curve_fit for filename: "+filename+'. '+e) #except ValueError as e: #raise ValueError("in scipy.optimize.curve_fit for filename: "+filename+'.') def guassianfunc(xVar, a, b, c): return a * np.exp(-(xVar - b) ** 2 / (2 * c ** 2)) + offset if plotten: ax2.plot(x_intpol[:-1], guassianfunc(x_intpol[:-1], *popt) ,color='grey',linestyle='--') #full function over full window if plotten: ax2.plot(fit_interval,y_fitted,color='black') g_fwhm = abs(popt[2]*2.35482) #can be neg? g_center = popt[1]#np.argmin(y_fitted) # print 'FWHM = ',g_fwhm # stride = np.diff(fit_interval)[0] # fwhm_ind_l = fit_interval[ g_center - int( (g_fwhm*0.5)/stride) ] # fwhm_ind_r = fit_interval[ g_center + int( (g_fwhm*0.5)/stride) ] fwhm_ind_l = g_center - (g_fwhm*0.5) fwhm_ind_r = g_center + (g_fwhm*0.5) # print g_center,g_fwhm,fwhm_ind_l, fwhm_ind_r if fitlines: ax2.axvline(fwhm_ind_l,color='green') if fitlines: ax2.axvline(fwhm_ind_r,color='green') if fitlines: ax2.annotate('FOW: '+str(g_fwhm)[:4],xy=(fwhm_ind_r,min(y_fitted)/2.) )#,xycoords='axes points') if plotten: print 'FOW is',g_fwhm return falloff_pos,g_fwhm,contrast
def get_fop(x,y,**kwargs): plotten = False plottenname = '' label='' threshold = 0.5 ax1 = '' smooth=True fitlines=False globmax=False if 'plot' in kwargs: plotten = True fitlines = True plottenname = str(kwargs['plot']) import plot if 'threshold' in kwargs: threshold = float(kwargs['threshold']) if 'globmax' in kwargs: globmax = float(kwargs['globmax']) if 'ax' in kwargs: if plotten == True: ax1 = kwargs['ax'] else: return if 'smooth' in kwargs: smooth = kwargs['smooth'] if 'label' in kwargs: label = kwargs['label'] if 'fitlines' in kwargs: fitlines = kwargs['fitlines'] y=np.array(y) #if plotten: import plot #if plotten: f, ax1 = plot.subplots(nrows=1, ncols=1, sharex=False, sharey=False) if plotten: ax1.scatter( x,y, color='black',marker="x",clip_on=False) #bindata #smooth that shit out. #https://en.wikipedia.org/wiki/Smoothing_spline y2 = scipy.signal.cspline1d(y,lamb=2) y_intpol_f = scipy.interpolate.interp1d(x,y2,kind='cubic') #interpolate function x_intpol = np.linspace(x[0],x[-1],2048,endpoint=False) y_intpol = y_intpol_f(x_intpol) #interpolate for x_intpol y_intpol = y_intpol.clip(min=0) #set any possible negatives to zero #if plotten: ax1.step(x,y2,color='steelblue', where='mid') if plotten: ax1.plot(x_intpol,y_intpol,color='indianred') #get 25 percentile, and take mean as baseline. baseline = y_intpol[y_intpol < np.percentile(y_intpol, 25)].mean() maxind=0 if globmax: maxind = np.where(y_intpol == y_intpol.max())[0][-1] #so that we find the LAST index where argmax(y) else: #global max globmaxind = np.where(y_intpol == y_intpol.max())[0][-1] globfalloff = y_intpol[globmaxind]-baseline #find distal local max within 30% of FO maxind = np.sort( scipy.signal.argrelextrema(y_intpol, np.greater)[0] )[::-1] for locmac in maxind[::-1]: #search from back if y_intpol[locmac] > (baseline+globfalloff*0.3): maxind = locmac #if fitlines: ax1.axhline(baseline+globfalloff*0.3,color='green') falloff = y_intpol[maxind]-baseline falloff_index=len(x_intpol)-1 #print falloff try: while y_intpol[falloff_index] < threshold*falloff+baseline: #default threshold is 0.5 falloff_index-=1 except ValueError: print y_intpol[falloff_index] < threshold*falloff+baseline print y_intpol[falloff_index] print threshold print falloff print baseline falloff_pos=x_intpol[falloff_index] if fitlines: ax1.axvline(falloff_pos,color='green') if fitlines: ax1.axhline(baseline,color='green') if fitlines: ax1.axhline(y_intpol[maxind],color='green') if fitlines: ax1.axvline(x_intpol[maxind],color='green') if plotten: plot.texax(ax1) if plotten: ax1.set_xlabel('Position [mm]', fontsize=8) if plotten: ax1.set_ylabel('PG yield [counts]', fontsize=8) if plotten: from matplotlib.ticker import MaxNLocator if plotten: ax1.yaxis.set_major_locator(MaxNLocator(integer=True)) if plotten: ax1.set_ylim(bottom=0) #if plotten: ax1.set_title('FOP = '+str(falloff_pos), fontsize=8) #if plotten: f.savefig(plottenname, bbox_inches='tight') #if plotten: print 'Plotted PG profile to',plottenname #if plotten: plot.close('all') if plotten: print 'FOP is',falloff_pos #if plotten: quit() return falloff_pos
rects1 = barax1.bar(ind, full[:3] + [0], width, color='red') rects2 = barax1.bar(ind + width, [0] + full[3:], width, color='blue') rects3 = barax2.bar(ind, layer[:3] + [0], width, color='red') rects4 = barax2.bar(ind + width, [0] + layer[3:], width, color='blue') rects5 = barax3.bar(ind, spot[:3] + [0], width, color='red') rects6 = barax3.bar(ind + width, [0] + spot[3:], width, color='blue') # axes and labels barax1.set_xlim(-width, len(ind) + width) barax1.set_ylabel('Shift [mm]') barax1.set_title('Full field') xTickMarks = labelbar barax1.set_xticks(ind + width) xtickNames = barax1.set_xticklabels(xTickMarks) plt.setp(xtickNames, rotation=45, fontsize=10) plot.texax(barax1) # axes and labels2 barax2.set_xlim(-width, len(ind) + width) barax2.set_ylabel('Shift [mm]') barax2.set_title('Layer') xTickMarks = labelbar barax2.set_xticks(ind + width) xtickNames = barax2.set_xticklabels(xTickMarks) plt.setp(xtickNames, rotation=45, fontsize=10) plot.texax(barax2) barax3.set_xlim(-width, len(ind) + width) barax3.set_ylabel('Shift [mm]') barax3.set_title('Spot') xTickMarks = labelbar
y, color='indianred', lw=1., label='Spot count', where='mid') dose, = ax1.step(ct_x, ct1d / ct1d.max() * float(y.max()), color='steelblue', lw=1., label='Integral dose (scaled)', where='mid') ax1.set_xlabel('Position [mm]') ax1.set_ylabel('Number of spots') ax1.set_xlim(-60, 16) ax1.set_ylim(0, 110) plot.texax(ax1) ax2 = ax1.twinx() ax2.semilogy() geo_prot, = ax2.step(geo_x, y_msw, color='forestgreen', lw=1., label='Protons', where='mid') ax2.set_xlim(-58, 18) ax2.set_ylim(5e7, 5e9) ax2.set_ylabel('Number of Protons') plot.texax(ax2, 'twinx') #ax1.axvline(falloffs[61],color='green') #plot FOP of spot 61
im = image.image(doseimage) ct = im.imdata.reshape(im.imdata.shape[::-1]).squeeze() ct1d=np.add.reduce(ct) ct_xhist = np.linspace(-150,150,301) #2mm voxels, endpoints ct_x = np.linspace(-149.5,149.5,300) #bincenters f, ax1 = plot.subplots(nrows=1, ncols=1, sharex=False, sharey=False) geo_spot, = ax1.step(geo_x,y, color='indianred',lw=1., label='Spot count', where='mid') dose, = ax1.step(ct_x,ct1d/ct1d.max()*float(y.max()), color='steelblue',lw=1., label='Integral dose (scaled)', where='mid') ax1.set_xlabel('Position [mm]') ax1.set_ylabel('Number of spots') ax1.set_xlim(-60,16) ax1.set_ylim(0,110) plot.texax(ax1) ax2=ax1.twinx() ax2.semilogy() geo_prot, = ax2.step(geo_x,y_msw, color='forestgreen',lw=1., label='Protons', where='mid') ax2.set_xlim(-58,18) ax2.set_ylim(5e7,5e9) ax2.set_ylabel('Number of Protons') plot.texax(ax2,'twinx') #ax1.axvline(falloffs[61],color='green') #plot FOP of spot 61 f.legend([geo_spot,dose,geo_prot],['Spot count','Dose (scaled)','Proton count'],frameon = False)#,fancybox = True,ncol = 1,fontsize = 'x-small',loc = 'upper right') f.savefig('rtplan.geolayers.pdf', bbox_inches='tight') plot.close('all')
def get_fop_fow_contrast(x,y,**kwargs): plotten = False plottenname = '' label='' threshold = 0.5 ax1 = '' smooth=2 fitlines=False globmax=False filename = '' nokillax3=True killfirst=False if 'killfirst' in kwargs: killfirst=True if 'filename' in kwargs: filename = kwargs['filename'] if 'plot' in kwargs: plotten = True fitlines = True plottenname = str(kwargs['plot']) import plot if 'threshold' in kwargs: threshold = float(kwargs['threshold']) if 'globmax' in kwargs: globmax = float(kwargs['globmax']) if 'width' in kwargs: FOW = True if 'ax' in kwargs: if plotten == True: ax1 = kwargs['ax'] else: return if 'ax2' in kwargs: if plotten == True: ax2 = kwargs['ax2'] else: return if 'ax3' in kwargs: if plotten == True: ax3 = kwargs['ax3'] else: nokillax3 = False else: nokillax3 = False if 'smooth' in kwargs: smooth = kwargs['smooth'] if 'label' in kwargs: label = kwargs['label'] if 'fitlines' in kwargs: fitlines = kwargs['fitlines'] if 'nprim' in kwargs: nprim = kwargs['nprim'] if 'contrast_divisor' in kwargs: contrast_divisor = kwargs['contrast_divisor'] y=np.array(y) # if plotten: import plot # if plotten: f, ax1 = plot.subplots(nrows=1, ncols=1, sharex=False, sharey=False) if plotten: if killfirst: ax1.scatter( x[1:],y[1:], color='black',marker="x",clip_on=False) #bindata else: ax1.scatter( x,y, color='black',marker="x",clip_on=False) #bindata #smooth that shit out. #https://en.wikipedia.org/wiki/Smoothing_spline y2 = scipy.signal.cspline1d(y,lamb=smooth) y_intpol_f = scipy.interpolate.interp1d(x,y2,kind='cubic') #interpolate function x_intpol = np.linspace(x[0],x[-1],2048,endpoint=False) y_intpol = y_intpol_f(x_intpol) #interpolate for x_intpol y_intpol = y_intpol.clip(min=0) #set any possible negatives to zero ####################################################################### CURVE IS COMPLETE, NOW ANALYSIS #if plotten: ax1.step(x,y2,color='steelblue', where='mid') if plotten: ax1.plot(x_intpol,y_intpol,color='indianred') #get 25 percentile, and take mean as baseline. baseline = y_intpol[y_intpol < np.percentile(y_intpol, 25)].mean() maxind=0 if globmax: maxind = np.where(y_intpol == y_intpol.max())[0][-1] #so that we find the LAST index where argmax(y) else: #global max globmaxind = np.where(y_intpol == y_intpol.max())[0][-1] globfalloff = y_intpol[globmaxind]-baseline #find distal local max within 30% of FO maxind = np.sort( scipy.signal.argrelextrema(y_intpol, np.greater)[0] )[::-1] for locmac in maxind[::-1]: #search from back if y_intpol[locmac] > (baseline+globfalloff*0.3): maxind = locmac #if fitlines: ax1.axhline(baseline+globfalloff*0.3,color='green') falloff = y_intpol[maxind]-baseline falloff_index=len(x_intpol)-1 print falloff try: while y_intpol[falloff_index] < threshold*falloff+baseline: #default threshold is 0.5 falloff_index-=1 except ValueError: print y_intpol[falloff_index] < threshold*falloff+baseline print y_intpol[falloff_index] print threshold print falloff print baseline #contrast = (y_intpol[maxind]-baseline)/(y_intpol[maxind]+baseline) contrast = (y_intpol[maxind]-baseline)/contrast_divisor falloff_pos=x_intpol[falloff_index] if fitlines: ax1.axvline(falloff_pos,color='green') if fitlines: ax1.axhline(baseline,color='green') if fitlines: ax1.axhline(y_intpol[maxind],color='green') if fitlines: ax1.axvline(x_intpol[maxind],color='green') if plotten: plot.texax(ax1) if plotten: ax1.set_ylim(bottom=0) if plotten: ax1.set_xlabel('Position [mm]', fontsize=8) if plotten: ax1.set_ylabel('PG yield [counts]', fontsize=8) if plotten: from matplotlib.ticker import MaxNLocator if plotten: ax1.yaxis.set_major_locator(MaxNLocator(integer=True)) # if plotten: ax1.set_ylim(bottom=0) if fitlines: ax1.annotate('FOP: '+str(falloff_pos)[:4],xy=(falloff_pos,falloff/2.+baseline)) if fitlines: ax1.annotate('Contrast: '+str(contrast)[:4],xy=(x_intpol[maxind],y_intpol[maxind])) if plotten: print 'FOP is',falloff_pos if plotten: print 'Contrast is',contrast ################################################# FOW # first diff: y_intpol_diff = np.diff(y_intpol) # second diff: y_intpol_diff2 = np.diff(y_intpol_diff) # find inflex in second diff and plot # print "len y_intpol_diff2:", len(y_intpol_diff2) if nokillax3: ax3.plot(x_intpol[:-2],y_intpol_diff2,color='darkseagreen') diff2_zero_index = falloff_index try: while y_intpol_diff2[diff2_zero_index]*y_intpol_diff2[diff2_zero_index-1] >=0 or y_intpol_diff2[diff2_zero_index] > y_intpol_diff2[diff2_zero_index-1]: #zolang product positief, dan geen kruising van x as #zolang positieve kruising van xas ga dan verder diff2_zero_index+=1 except IndexError: diff2_zero_index-=1 #reached end if nokillax3: ax3.axvline(x_intpol[diff2_zero_index],color='green') if nokillax3: ax3.annotate('Inflex: '+str(x_intpol[diff2_zero_index])[:4],xy=(x_intpol[diff2_zero_index],0 ) ) # use inflex to set interval for gauss fit in first diff if plotten: ax2.plot(x_intpol[:-1],y_intpol_diff,color='steelblue') # fit_interval = x_intpol[maxind : falloff_index+(falloff_index-maxind)] fit_interval = x_intpol[maxind : diff2_zero_index] fit_points = y_intpol_diff[maxind : diff2_zero_index] #offset = y_intpol_diff[diff2_zero_index] offset = 0 #actually, lets remove this param if plotten: ax2.plot(fit_interval,fit_points,color='steelblue') try: popt,y_fitted = fitgauss_tuned(fit_interval,fit_points,falloff_pos,offset) except RuntimeError as e: print(kleur.fail("[auger/__init__.py]")+" RuntimeError in scipy.optimize.curve_fit for filename: "+filename+'. '+str(e)) raise e except ValueError as e: print(kleur.fail("[auger/__init__.py]")+" ValueError in scipy.optimize.curve_fit for filename: "+filename+'. '+str(e)) raise e def guassianfunc(xVar, a, b, c): return a * np.exp(-(xVar - b) ** 2 / (2 * c ** 2)) + offset if plotten: ax2.plot(x_intpol[:-1], guassianfunc(x_intpol[:-1], *popt) ,color='grey',linestyle='--') #full function over full window if plotten: ax2.plot(fit_interval,y_fitted,color='black') if plotten: ax2.set_xlabel('Position [mm]', fontsize=8) if not nokillax3: ax2.set_ylabel('First Derivative', fontsize=8) g_fwhm = abs(popt[2]*2.35482) #can be neg? g_center = popt[1]#np.argmin(y_fitted) # print 'FWHM = ',g_fwhm # stride = np.diff(fit_interval)[0] # fwhm_ind_l = fit_interval[ g_center - int( (g_fwhm*0.5)/stride) ] # fwhm_ind_r = fit_interval[ g_center + int( (g_fwhm*0.5)/stride) ] fwhm_ind_l = g_center - (g_fwhm*0.5) fwhm_ind_r = g_center + (g_fwhm*0.5) # print g_center,g_fwhm,fwhm_ind_l, fwhm_ind_r if fitlines: ax2.axvline(fwhm_ind_l,color='green') if fitlines: ax2.axvline(fwhm_ind_r,color='green') if fitlines: ax2.annotate('FOW: '+str(g_fwhm)[:4],xy=(fwhm_ind_r,min(y_fitted)/2.) )#,xycoords='axes points') if plotten: print 'FOW is',g_fwhm return falloff_pos,g_fwhm,contrast
dosebar.append(dose_shift) ipnlbar.append(ipnl_shift) ibabar.append(iba_shift) dosebar2.append(dose_corr_af)#-dose_corr_bef) ipnlbar2.append(ipnl_corr_af)#-ipnl_corr_bef) ibabar2.append(iba_corr_af)#-iba_corr_bef) labelbar.append(key+", CMU:"+value['CMU']) plotter(pl,value['orig'],'dose','orig') plotter(pl,value['replan'],'dose',formatlabel(dose_shift,dose_corr_bef,dose_corr_af)) plotter(pm,value['orig'],'ipnl','orig') plotter(pm,value['replan'],'ipnl',formatlabel(ipnl_shift,ipnl_corr_bef,ipnl_corr_af)) plotter(pr,value['orig'],'iba','orig') plotter(pr,value['replan'],'iba',formatlabel(iba_shift,iba_corr_bef,iba_corr_af)) plot.texax(pl) plot.texax(pm) plot.texax(pr) pl.set_title("Dose") pm.set_title("PG IPNL") pr.set_title("PG IBA") # plo.set_ylim([1e-1,1.1e2]) pl.set_ylabel('Dose [gy], PG Yield [counts]') pl.set_xlabel('Depth [mm]') #plo.xaxis.set_label_coords(1.1,-0.1) lgd = pl.legend(loc='upper right', bbox_to_anchor=(1.4, 1.),frameon=False) [label.set_linewidth(1) for label in lgd.get_lines()] lgd = pm.legend(loc='upper right', bbox_to_anchor=(1.4, 1.),frameon=False) [label.set_linewidth(1) for label in lgd.get_lines()]
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) ax2.set_ylim(0,0.003) ax2.set_xlabel('Position [mm]') ax2.xaxis.set_label_coords(-0.1, -0.1) plot.texax(ax2) ######## TopRow #ax4.step(x,dose[29]/dose[29].max(), color='steelblue',lw=1., alpha=1, label='CT', where='mid') #ax4.step(x,rpdose[29]/rpdose[29].max(), color='indianred',lw=1., alpha=1, label='RPCT', where='mid')
f, (tl,tr) = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True) # tleeff[1e6]['var'].saveas('speedup.mhd') tl.imshow(speedim,interpolation='nearest',origin='lower',norm = mpl.colors.LogNorm(),cmap="hot",clim=[1e2,1e4]) pica=tr.imshow(speedim,interpolation='nearest',origin='lower',norm = mpl.colors.LogNorm(),cmap="hot",clim=[1e2,1e4]) tr.imshow(ctim,interpolation='nearest', origin='lower',cmap="gray",alpha=0.5) tl.set_ylim([5,75]) tr.set_ylim([5,75]) tl.set_xlim([5,30]) tr.set_xlim([5,30]) tr.yaxis.set_visible(False) tl.set_ylabel('Depth [mm]') tl.set_xlabel('Width [mm]') tr.set_xlabel('Width [mm]') tl.set_title(r'Gain vpgTLE $10^6$'+'\n w.r.t. Reference') tr.set_title('CT Image') plot.texax(tl) plot.texax(tr) f.colorbar(pica)#, ticks=[1e2, 1e3, 1e4]) # f.colorbar(tl,shrink=.92) f.savefig('slice1.pdf', bbox_inches='tight') f.savefig('slice1.png', bbox_inches='tight',dpi=300) plt.close('all') ### Speedup slice + material slice speedim = tleeff[1e6]['var'].getslice('x',14) ctim = patient.getslice('x',14) #ctim[ctim == 0] = np.nan f, (tl,tr) = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True)
#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]') plot.texax(ax3) ax4.set_title('Dose Diff (E)') ax4.set_xlabel('Energy [MeV]') ax4.set_ylabel('Dose Diff [RMSE]') plot.texax(ax4)
def get_fop(x,y,**kwargs): plotten = False plottenname = '' label='' threshold = 0.5 ax1 = '' smooth=True fitlines=False globmax=False if 'plot' in kwargs: plotten = True fitlines = True plottenname = str(kwargs['plot']) import plot if 'threshold' in kwargs: threshold = float(kwargs['threshold']) if 'globmax' in kwargs: globmax = float(kwargs['globmax']) if 'ax' in kwargs: if plotten == True: ax1 = kwargs['ax'] else: return if 'smooth' in kwargs: smooth = kwargs['smooth'] if 'label' in kwargs: label = kwargs['label'] if 'fitlines' in kwargs: fitlines = kwargs['fitlines'] y=np.array(y) #if plotten: import plot #if plotten: f, ax1 = plot.subplots(nrows=1, ncols=1, sharex=False, sharey=False) if plotten: ax1.scatter( x,y, color='black',marker="x",clip_on=False) #bindata #smooth that shit out. #https://en.wikipedia.org/wiki/Smoothing_spline y2 = scipy.signal.cspline1d(y,lamb=2) y_intpol_f = scipy.interpolate.interp1d(x,y2,kind='cubic') #interpolate function x_intpol = np.linspace(x[0],x[-1],2048,endpoint=False) y_intpol = y_intpol_f(x_intpol) #interpolate for x_intpol y_intpol = y_intpol.clip(min=0) #set any possible negatives to zero #if plotten: ax1.step(x,y2,color='steelblue', where='mid') if plotten: ax1.plot(x_intpol,y_intpol,color='indianred') #get 25 percentile, and take mean as baseline. baseline = y_intpol[y_intpol < np.percentile(y_intpol, 25)].mean() maxind=0 if globmax: maxind = np.where(y_intpol == y_intpol.max())[0][-1] #so that we find the LAST index where argmax(y) else: #global max globmaxind = np.where(y_intpol == y_intpol.max())[0][-1] globfalloff = y_intpol[globmaxind]-baseline #find distal local max within 30% of FO maxind = np.sort( scipy.signal.argrelextrema(y_intpol, np.greater)[0] )[::-1] for locmac in maxind[::-1]: #search from back if y_intpol[locmac] > (baseline+globfalloff*0.3): maxind = locmac #if fitlines: ax1.axhline(baseline+globfalloff*0.3,color='green') falloff = y_intpol[maxind]-baseline falloff_index=len(x_intpol)-1 print falloff try: while y_intpol[falloff_index] < threshold*falloff+baseline: #default threshold is 0.5 falloff_index-=1 except ValueError: print y_intpol[falloff_index] < threshold*falloff+baseline print y_intpol[falloff_index] print threshold print falloff print baseline falloff_pos=x_intpol[falloff_index] if fitlines: ax1.axvline(falloff_pos,color='green') if fitlines: ax1.axhline(baseline,color='green') if fitlines: ax1.axhline(y_intpol[maxind],color='green') if fitlines: ax1.axvline(x_intpol[maxind],color='green') if plotten: plot.texax(ax1) if plotten: ax1.set_xlabel('Position [mm]', fontsize=8) if plotten: ax1.set_ylabel('PG yield [counts]', fontsize=8) if plotten: from matplotlib.ticker import MaxNLocator if plotten: ax1.yaxis.set_major_locator(MaxNLocator(integer=True)) if plotten: ax1.set_ylim(bottom=0) #if plotten: ax1.set_title('FOP = '+str(falloff_pos), fontsize=8) #if plotten: f.savefig(plottenname, bbox_inches='tight') #if plotten: print 'Plotted PG profile to',plottenname #if plotten: plot.close('all') if plotten: print 'FOP is',falloff_pos #if plotten: quit() return falloff_pos