def test_rebinner(): edges = N.array([0.0, 0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.0], dtype='d') edges_m = N.array([0.1, 1.2, 3.4, 4.5, 7.8], dtype='d') ntrue = C.Histogram(edges, N.ones(edges.size - 1)) rebin = R.Rebin(edges_m.size, edges_m, 3) rebin.rebin.histin(ntrue) olddata = ntrue.data() newdata = rebin.rebin.histout.data() mat = convert(rebin.getDenseMatrix(), 'matrix') if "pytest" not in sys.modules: print(mat) prj = mat.sum(axis=0) assert ((prj == 1.0) + (prj == 0.0)).all(), "Not matching results after rebin" # # Plot spectra # if "pytest" not in sys.modules: print(((prj == 1.0) + (prj == 0.0)).all() and '\033[32mOK!' or '\033[31mFAIL!', '\033[0m') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() # ax.grid() ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_title('Rebinner') ax.vlines(edges, 0.0, 4.0, linestyle='--', linewidth=0.5) plot_hist(edges, olddata, label='before') plot_hist(edges_m, newdata, label='after') ax.legend(loc='upper left') # # Plot matrix # fig = P.figure() ax = P.subplot(111) ax.minorticks_on() # ax.grid() ax.set_xlabel('Source bins') ax.set_ylabel('Target bins') ax.set_title('Rebinning matrix') c = ax.matshow(N.ma.array(mat, mask=mat == 0.0), extent=[edges[0], edges[-1], edges_m[-1], edges_m[0]]) # add_colorbar( c ) P.show()
def plot_ratio(gna, dyboscar, **kwargs): title = kwargs.pop('title', '') dyb_data, dyb_bins = dyboscar.numpy() fig, (axis_spectra, axis_ratio) = plt.subplots(ncols=1, nrows=2, sharex=True, gridspec_kw={'hspace': 0.}, squeeze=True) fig.subplots_adjust(hspace=0.05) fig.set_tight_layout(True) gna.plot_hist(axis=axis_spectra, label='GNA') plot_hist(dyb_bins, dyb_data, label='dybOscar', axis=axis_spectra) axis_spectra.legend() axis_spectra.set_title("{}".format(title), fontsize=16) axis_spectra.minorticks_on() axis_spectra.grid('both', alpha=0.5) axis_spectra.set_ylabel(r"Entries", fontsize=14) axis_spectra.set_ylim(bottom=0.) ratio = gna.data() / dyb_data - 1 try: scale = int(kwargs['yscale']) ratio *= 10**(scale) ylabel = ''.join(("Ratio$-1$, $10^{-", str(scale), "}$")) axis_ratio.set_ylabel(r'{}'.format(ylabel), fontsize=14) except (KeyError, TypeError): axis_ratio.set_ylabel(r"Ratio$-1$", fontsize=14) plot_hist(dyb_bins, ratio, axis=axis_ratio, label='GNA/dybOscar') ylims = kwargs.pop('ylims') if ylims is not None: axis_ratio.set_ylim(ylims[0], ylims[1]) xlims = kwargs.pop('xlims') axis_ratio.axhline(y=0.0, linestyle='--', color='grey', alpha=0.5) axis_ratio.legend() axis_ratio.minorticks_on() axis_ratio.grid(alpha=0.5) axis_ratio.grid('minor', alpha=0.5) axis_ratio.set_xlabel(r"$E_{\mathrm{vis}}$, MeV", fontsize=14) plt.setp(axis_ratio.get_yticklabels()[-1], visible=False) axis_ratio.get_yaxis().get_major_formatter().set_useOffset(True) if xlims is not None: axis_spectra.set_xlim(xlims[0], xlims[1]) axis_ratio.set_xlim(xlims[0], xlims[1]) printer_to_file = kwargs.get('pp', None) if printer_to_file: printer_to_file.savefig(fig) plt.close('all')
def plot_hist1(h, *args, **kwargs): """Plot 1-dimensinal histogram using pyplot.plot executes pyplot.plot(x, y, *args, **kwargs) with first two arguments overridden all other arguments passes as is. Options: autolabel=True guesses plot label with histogram's title returns pyplot.plot() result """ if kwargs.pop('autolabel', None): kwargs['label'] = h.GetTitle() lims = R2N.get_bin_edges_axis(h.GetXaxis()) height = R2N.get_buffer_hist1(h).copy() return helpers.plot_hist(lims, height, *args, **kwargs)
def plot_hist(output, *args, **kwargs): """Plot 1-dimensinal output using pyplot.plot executes pyplot.plot(x, y, *args, **kwargs) with first two arguments overridden all other arguments are passed as is. Options: scale=float or 'width' - multiply bin by a scale or divide by bin width returns pyplot.plot() result """ scale = kwargs.pop('scale', None) height, lims, _ = get_1d_data(output, scale=scale) diff = kwargs.pop('diff', None) if diff is not None: ifSameType(output, diff) height1, lims1, _ = get_1d_data(diff, scale) height -= height1 ratio = kwargs.pop('ratio', None) if ratio is not None: ifSameType(output, ratio) height1, lims1, _ = get_1d_data(ratio, scale) height /= height1 height[N.isnan(height)] = 1.0 offset_ratio = kwargs.pop('offset_ratio', None) if offset_ratio is not None: ifSameType(output, offset_ratio) height1, lims1, _ = get_1d_data(offset_ratio, scale) height /= height1 height -= 1.0 height[N.isnan(height)] = 0.0 return helpers.plot_hist(lims, height, *args, **kwargs)
from mpl_tools.helpers import plot_hist from gna.labelfmt import formatter as L axes=() for i, hist in enumerate(hists_list): P.figure(), ax = P.subplot( 111 ) axes+=ax, ax.minorticks_on() ax.grid() ax.set_xlabel( L.u('evis') ) ax.set_ylabel( 'Entries' ) ax.set_title( cfg.detector.detectors[i] ) data = hist.hist.hist.data() print( 'Sum data %i=%i'%( i, data.sum() ) ) plot_hist(edges, data, label='original') for bundle in b.bundles.values(): for i, (oname, out) in enumerate( bundle.outputs.items() ): P.sca(axes[i]) data = out.data() print( 'Sum data %s (%s) %i=%f'%( type(bundle).__name__, oname, i, data.sum() ) ) plot_hist(out.datatype().edges, data, label=type(bundle).__name__) for i, hist in enumerate(hists_list): ax=axes[i] P.sca(ax) ax.legend( loc='upper right' )
def test_energyresolution_v01(tmp_path): def axes( title, ylabel='' ): fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( L.u('evis') ) ax.set_ylabel( ylabel ) ax.set_title( title ) return ax def singularities( values, edges ): indices = np.digitize( values, edges )-1 phist = np.zeros( edges.size-1 ) phist[indices] = 1.0 return phist # # Define the parameters in the current namespace # ns = env.globalns('test_energyresolution_v01') weights = [ 'Eres_'+s for s in 'abc' ] wvals = [0.016, 0.081, 0.026] percent = 0.01 ns.defparameter(weights[0], central=wvals[0], relsigma=30*percent ) par = ns.defparameter(weights[1], central=wvals[1], relsigma=30*percent ) ns.defparameter(weights[2], central=wvals[2], relsigma=30*percent ) ns.printparameters() values = [] def pop_value(): values, par par.set(values.pop()) def push_value(v): values, par values.append(par.value()) par.set(v) # # Define bin edges # binwidth=0.05 edges = np.arange( 0.0, 12.0001, binwidth ) efine = np.arange( edges[0], edges[-1]+1.e-5, 0.005 ) for eset in [ [ [1.025], [3.025], [6.025], [9.025] ], [ [ 1.025, 5.025, 9.025 ] ], [ [ 6.025, 7.025, 8.025, 8.825 ] ], ]: for i, e in enumerate(eset): ax = axes( 'Energy resolution impact' ) phist = singularities( e, edges ) hist = C.Histogram( edges, phist ) edges_o = R.HistEdges(hist) with ns: eres = C.EnergyResolution(weights, True) eres.matrix.Edges( hist ) eres.smear.Ntrue( hist ) path = os.path.join(str(tmp_path), 'eres_graph_%i.png'%i) savegraph(hist, path) allure_attach_file(path) smeared = eres.smear.Nrec.data() diff = phist.sum()-smeared.sum() print( 'Sum check for {} (diff): {}'.format( e, diff ) ) assert diff<1.e-9 lines = plot_hist( edges, smeared, label='default' ) color = lines[0].get_color() ax.vlines( e, 0.0, smeared.max(), linestyle='--', color=color ) if len(e)>1: color='green' for e in e: ax.plot( efine, binwidth*norm.pdf( efine, loc=e, scale=eres.relativeSigma(e)*e ), linestyle='--', color='green' ) sprev = smeared.copy() push_value(0.162) assert eres.smear.tainted() smeared = eres.smear.Nrec.data() assert not np.all(smeared==sprev) plot_hist( edges, smeared, label='modified', color='red', alpha=0.5) pop_value() ax.legend() path = os.path.join(str(tmp_path), 'eres_test_{:02d}.png'.format(i)) savefig(path, density=300) allure_attach_file(path) plt.close() smeared = eres.smear.Nrec.data() ax = axes( 'Relative energy uncertainty', ylabel=L.u('eres_sigma_rel') ) ax.set_ylim(0, 13.0) ax.set_xlim(0.5, 12.0) x = np.arange( 0.5, 12.0, 0.01 ) fcn = np.frompyfunc( eres.relativeSigma, 1, 1 ) y = fcn( x ) ax.plot( x, y*100. ) path = os.path.join(str(tmp_path), 'eres_sigma.png') savefig(path, density=300) allure_attach_file(path) plt.close() fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( '' ) ax.set_ylabel( '' ) ax.set_title( 'Energy resolution convertsion matrix (class)' ) mat = convert(eres.getDenseMatrix(), 'matrix') mat = np.ma.array( mat, mask= mat==0.0 ) c = ax.matshow( mat, extent=[ edges[0], edges[-1], edges[-1], edges[0] ] ) add_colorbar( c ) path = os.path.join(str(tmp_path), 'eres_matc.png') savefig(path, density=300) allure_attach_file(path) plt.close() fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( '' ) ax.set_ylabel( '' ) ax.set_title( 'Energy resolution convertsion matrix (trans)' ) eres.matrix.FakeMatrix.plot_matshow(colorbar=True, mask=0.0, extent=[edges[0], edges[-1], edges[-1], edges[0]]) path = os.path.join(str(tmp_path), 'eres_mat.png') savefig(path, density=300) allure_attach_file(path) plt.close()
# # Plot hists # fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('') ax.set_ylabel('') ax.set_title('Non-linearity effect') smeared = smear.Nrec.data().copy() print('Sum check for {} (diff): {}'.format(1.0, phist.sum() - smeared.sum())) plot_hist(edges, phist, label='original') lines = plot_hist(edges, smeared, label='smeared: nominal') ax.legend(loc='upper right') savefig(args.output) # # Plot matrix # fig = P.figure() ax1 = P.subplot(111) ax1.minorticks_on() ax1.grid() ax1.set_xlabel('Source bins') ax1.set_ylabel('Target bins') ax1.set_title('Daya Bay LSNL matrix')
print(a.expressions_raw) print(a.expressions) a.parse() a.guessname(lib, save=True) a.tree.dump(True) edges = np.linspace(0., 12, 240 + 1) print() cfg = NestedDict(snf=NestedDict( bundle="reactor_snf_spectra_v02", data_path= "data/reactor_anu_spectra/SNF/kopeikin_0412.044_spent_fuel_spectrum_smooth.dat", edges=edges)) context = ExpressionContext(cfg, ns=env.globalns) a.build(context) from gna.bindings import OutputDescriptor env.globalns.printparameters(labels=True) print('outputs:') print(context.outputs) if args.show: import matplotlib.pyplot as plt import mpl_tools.helpers as mplh snf = context.outputs['snf_ratio'] bin_centers = (edges[1:] + edges[:-1]) / 2 mplh.plot_hist(edges, snf.data()) plt.show()
rd = R.RenormalizeDiag(ndiag, int(opts.offdiag), int(opts.upper)) rd.renorm.inmat(pmat.points) esmear = R.HistSmear(opts.upper) esmear.smear.inputs.SmearMatrix(rd.renorm) esmear.smear.inputs.Ntrue(hist.hist) for i, value in enumerate([1.0, 0.5, 2.0]): par.set(value) smeared = esmear.smear.Nrec.data() print('Sum check for {} (diff): {}'.format(value, phist.sum() - smeared.sum())) # bars = P.bar( edges[:-1], phist, binwidth, align='edge' ) P.sca(ax) lines = plot_hist(edges, smeared, label='%.2f' % value) color = lines[0].get_color() fig = P.figure() ax1 = P.subplot(111) ax1.minorticks_on() ax1.grid() ax1.set_xlabel('') ax1.set_ylabel('') ax1.set_title('Synthetic energy leak matrix (diag scale=%.2f, ndiag=%i)' % (value, ndiag)) mat = rd.renorm.outmat.data() mat = N.ma.array(mat, mask=mat == 0.0) c = ax1.matshow(mat, extent=[edges[0], edges[-1], edges[-1], edges[0]]) add_colorbar(c)
# fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( r'$E_\nu$, MeV' ) ax.set_ylabel( 'entries' ) ax.set_title( 'IAV effect' ) smeared = smear.data().copy() par.set( 2.0 ) smeared2 = smear.data().copy() print( 'Sum check for {} (diff): {}'.format( 1.0, phist.sum()-smeared.sum() ) ) print( 'Sum check for {} (diff): {}'.format( 2.0, phist.sum()-smeared2.sum() ) ) lines = plot_hist( edges, smeared, label='nominal' ) lines = plot_hist( edges, smeared2, linewidth=1.0, label='diag scale $s=2$' ) ax.legend( loc='upper right' ) if args.xlim: ax.set_xlim( *args.xlim ) savefig( args.output ) fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( '' ) ax.set_ylabel( '' )
def test_energyresolutioninput_v01(tmp_path): def axes( title, ylabel='' ): fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( L.u('evis') ) ax.set_ylabel( ylabel ) ax.set_title( title ) return ax def singularities( values, edges ): indices = np.digitize( values, edges )-1 phist = np.zeros( edges.size-1 ) phist[indices] = 1.0 return phist # # Define the parameters in the current namespace # wvals = [0.016, 0.081, 0.026] # # Define bin edges # binwidth=0.05 edges = np.arange( 0.0, 12.0001, binwidth ) efine = np.arange( edges[0], edges[-1]+1.e-5, 0.005 ) centers = 0.5*(edges[1:]+edges[:-1]) def RelSigma(e): a, b, c = wvals return (a**2+ (b**2)/e + (c/e)**2)**0.5 relsigma = RelSigma(centers) for eset in [ [ [1.025], [3.025], [6.025], [9.025] ], [ [ 1.025, 5.025, 9.025 ] ], [ [ 6.025, 7.025, 8.025, 8.825 ] ], ]: for i, e in enumerate(eset): ax = axes( 'Energy resolution (input) impact' ) phist = singularities( e, edges ) relsigma_i = relsigma.copy() relsigma_p = C.Points(relsigma_i) hist = C.Histogram( edges, phist ) edges_o = R.HistEdges(hist) eres = C.EnergyResolutionInput(True) hist >> eres.matrix.Edges relsigma_p >> eres.matrix.RelSigma hist >> eres.smear.Ntrue path = os.path.join(str(tmp_path), 'eres_graph_%i.png'%i) savegraph(hist, path) allure_attach_file(path) smeared = eres.smear.Nrec.data() diff = phist.sum()-smeared.sum() print( 'Sum check for {} (diff): {}'.format( e, diff ) ) assert diff<1.e-9 lines = plot_hist( edges, smeared, label='default' ) color = lines[0].get_color() ax.vlines( e, 0.0, smeared.max(), linestyle='--', color=color ) if len(e)>1: color='green' for e in e: ax.plot( efine, binwidth*norm.pdf( efine, loc=e, scale=RelSigma(e)*e ), linestyle='--', color='green' ) sprev = smeared.copy() icut = relsigma_i.size//2 relsigma_i[icut:]*=2 relsigma_p.set(relsigma_i, relsigma_i.size) smeared = eres.smear.Nrec.data() shouldchange = phist[icut:].any() assert not np.all(smeared==sprev)==shouldchange plot_hist( edges, smeared, label='modified', color='red', alpha=0.5) ax.legend() path = os.path.join(str(tmp_path), 'eres_test_{:02d}.png'.format(i)) savefig(path, density=300) allure_attach_file(path) plt.close() relsigma_p.set(relsigma, relsigma.size) smeared = eres.smear.Nrec.data() ax = axes( 'Relative energy uncertainty', ylabel=L.u('eres_sigma_rel') ) ax.set_xlim(0.5, 12.0) ax.set_ylim(0, 13.0) ax.plot( centers, relsigma*100. ) path = os.path.join(str(tmp_path), 'eres_sigma.png') savefig(path, density=300) allure_attach_file(path) plt.close() fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( '' ) ax.set_ylabel( '' ) ax.set_title( 'Energy resolution convertsion matrix (class)' ) mat = convert(eres.getDenseMatrix(), 'matrix') mat = np.ma.array( mat, mask= mat==0.0 ) c = ax.matshow( mat, extent=[ edges[0], edges[-1], edges[-1], edges[0] ] ) add_colorbar( c ) path = os.path.join(str(tmp_path), 'eres_matc.png') savefig(path, density=300) allure_attach_file(path) plt.close() fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( '' ) ax.set_ylabel( '' ) ax.set_title( 'Energy resolution convertsion matrix (trans)' ) eres.matrix.FakeMatrix.plot_matshow(colorbar=True, mask=0.0, extent=[edges[0], edges[-1], edges[-1], edges[0]]) path = os.path.join(str(tmp_path), 'eres_mat.png') savefig(path, density=300) allure_attach_file(path) plt.close()
# # Test bundle # nonlin1.smear.Ntrue(hist.hist) nonlin2.smear.Ntrue(hist.hist) # # Plot hists # fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('') ax.set_ylabel('') ax.set_title('Non-linearity effect') smeared1 = nonlin1.smear.Nrec.data().copy() smeared2 = nonlin2.smear.Nrec.data().copy() print('Sum check for {} (diff): {}'.format(1.0, phist.sum() - smeared1.sum())) print('Sum check for {} (diff): {}'.format(1.0, phist.sum() - smeared2.sum())) lines = plot_hist(edges, smeared1, label='Smeared 1') lines = plot_hist(edges, smeared2, label='Smeared 2') plot_hist(edges, phist, label='original') ax.legend(loc='upper right') P.show()
ax = axes('Energy resolution impact') for i, e in enumerate(eset): phist = singularities(e, edges) hist = C.Histogram(edges, phist) edges_o = R.HistEdges(hist) eres = R.EnergyResolution(True) eres.matrix.Edges(hist) eres.smear.Ntrue(hist) smeared = eres.smear.Nrec.data() print('Sum check for {} (diff): {}'.format(e, phist.sum() - smeared.sum())) lines = plot_hist(edges, smeared, label='default') color = lines[0].get_color() ax.vlines(e, 0.0, smeared.max(), linestyle='--', color=color) if len(e) > 1: color = 'green' for e in e: ax.plot(efine, binwidth * norm.pdf(efine, loc=e, scale=eres.relativeSigma(e) * e), linestyle='--', color=color) push_value(0.162) smeared = eres.smear.Nrec.data()
nl.set(hist.hist, pedges_m.points) nl.add_input(hist) smeared = nl.smear.Nrec.data() print('Sum check (diff): {}'.format(phist.sum() - smeared.sum())) fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel(L.u('evis')) ax.set_ylabel('Entries') ax.set_title('Non-linearity correction') lines = plot_hist(edges, smeared) color = lines[0].get_color() _, ev_m = nlfcn(ev) heights = smeared[smeared > 0.45] ax.vlines(ev, 0.0, heights, alpha=0.7, color='red', linestyle='--') ax.vlines(ev_m, 0.0, heights, alpha=0.7, color='green', linestyle='--') savefig(opts.output, suffix='_evis') fig = P.figure() ax1 = P.subplot(111) ax1.minorticks_on() ax1.grid() ax1.set_xlabel('Source bins') ax1.set_ylabel('Target bins') ax1.set_title('Energy non-linearity matrix')
for bundle in b.bundles.values()+[b, bfn]: bkgname=bundle.cfg.get('name', 'total') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'x axis' ) ax.set_ylabel( 'entries' ) ax.set_title(bkgname) for i, (name, output) in enumerate(bundle.outputs.items()): pack=None if opts.pack: if bkgname=='bkg2': group = bundle.groups.get_group(name, 'site') pack = (group.index(name), len(group)) elif bkgname=='bkgw': pack = (i, len(bundle.outputs)) if bkgname=='bkg_fn': plot_hist( output.datatype().edges, output.data(), label=name ) else: plot_bar( output.datatype().edges, output.data(), label=name, pack=pack, alpha=0.8 ) ax.legend( loc='upper right' ) P.show()
fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('') ax.set_ylabel('') ax.set_title('IAV effect') smeared1 = smear1.Nrec.data() smeared2 = smear2.Nrec.data() smeared3 = smear3.Nrec.data() print('Sum check for {} (diff): {}'.format(1.0, phist.sum() - smeared1.sum())) print('Sum check for {} (diff): {}'.format(2.0, phist.sum() - smeared2.sum())) print('Sum check for {} (diff): {}'.format(2.0, phist.sum() - smeared3.sum())) lines = plot_hist(edges, smeared1, linewidth=1.0, label='IAV 1') lines = plot_hist(edges, smeared2, linewidth=1.0, label='IAV 2') lines = plot_hist(edges, smeared3, linewidth=1.0, label='IAV 3') ax.legend(loc='upper right') # # Dump graph # if args.dot: try: from gna.graphviz import GNADot graph = GNADot(b.transformations_out.values()[0]) graph.write(args.dot) print('Write output to:', args.dot)
def main(opts): global savefig cfg = NestedDict( bundle = dict( name='energy_nonlinearity_birks_cherenkov', version='v01', nidx=[ ('r', 'reference', ['R1', 'R2']) ], major=[], ), stopping_power='stoppingpower.txt', annihilation_electrons=dict( file='input/hgamma2e.root', histogram='hgamma2e_1KeV', scale=1.0/50000 # event simulated ), pars = uncertaindict( [ ('birks.Kb0', (1.0, 'fixed')), ('birks.Kb1', (15.2e-3, 0.1776)), # ('birks.Kb2', (0.0, 'fixed')), ("cherenkov.E_0", (0.165, 'fixed')), ("cherenkov.p0", ( -7.26624e+00, 'fixed')), ("cherenkov.p1", ( 1.72463e+01, 'fixed')), ("cherenkov.p2", ( -2.18044e+01, 'fixed')), ("cherenkov.p3", ( 1.44731e+01, 'fixed')), ("cherenkov.p4", ( 3.22121e-02, 'fixed')), ("Npescint", (1341.38, 0.0059)), ("kC", (0.5, 0.4737)), ("normalizationEnergy", (2.505, 'fixed')) # ("normalizationEnergy", (12.0, 'fixed')) ], mode='relative' ), integration_order = 2, correlations_pars = [ 'birks.Kb1', 'Npescint', 'kC' ], correlations = [ 1.0, 0.94, -0.97, 0.94, 1.0, -0.985, -0.97, -0.985, 1.0 ], fill_matrix=True, labels = dict( normalizationEnergy = '60Co total gamma energy, MeV' # normalizationEnergy = 'Pessimistic norm point' ), ) ns = env.globalns('energy') quench = execute_bundle(cfg, namespace=ns) ns.printparameters(labels=True) print() normE = ns['normalizationEnergy'].value() # # Input bins # evis_edges_full_input = N.arange(0.0, 12.0+1.e-6, 0.025) evis_edges_full_hist = C.Histogram(evis_edges_full_input, labels='Evis bin edges') evis_edges_full_hist >> quench.context.inputs.evis_edges_hist['00'] # # HistNonLinearity transformation # reference_histogram1_input = N.zeros(evis_edges_full_input.size-1) reference_histogram2_input = reference_histogram1_input.copy() reference_histogram1_input+=1.0 # reference_histogram2_input[[10, 20, 50, 100, 200, 300, 400]]=1.0 reference_histogram2_input[[10, 20]]=1.0 reference_histogram1 = C.Histogram(evis_edges_full_input, reference_histogram1_input, labels='Reference hist 1') reference_histogram2 = C.Histogram(evis_edges_full_input, reference_histogram2_input, labels='Reference hist 2') reference_histogram1 >> quench.context.inputs.lsnl.R1.values() reference_histogram2 >> quench.context.inputs.lsnl.R2.values() reference_smeared1 = quench.context.outputs.lsnl.R1 reference_smeared2 = quench.context.outputs.lsnl.R2 # # Plots and tests # if opts.output and opts.output.endswith('.pdf'): pdfpages = PdfPages(opts.output) pdfpagesfilename=opts.output savefig_old=savefig pdf=pdfpages.__enter__() def savefig(*args, **kwargs): if opts.individual and args and args[0]: savefig_old(*args, **kwargs) pdf.savefig() else: pdf = None pdfpagesfilename = '' # # Plots and tests # fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'Edep, MeV' ) ax.set_ylabel( 'dE/dx' ) ax.set_title( 'Stopping power' ) quench.birks_quenching_p.points.points.plot_vs(quench.birks_e_p.points.points, '-', markerfacecolor='none', markersize=2.0, label='input') ax.legend(loc='upper right') savefig(opts.output, suffix='_spower') ax.set_xlim(left=0.001) ax.set_xscale('log') savefig(opts.output, suffix='_spower_log') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'Edep, MeV' ) ax.set_ylabel( '' ) ax.set_title( "Birk's integrand" ) quench.birks_integrand_raw.polyratio.ratio.plot_vs(quench.birks_e_p.points.points, '-o', alpha=0.5, markerfacecolor='none', markersize=2.0, label='raw') # birks_integrand_interpolated.plot_vs(integrator_ekin.points.x, '-', alpha=0.5, markerfacecolor='none', markersize=2.0, label='interpolated') lines=quench.birks_integrand_interpolated.plot_vs(quench.integrator_ekin.points.x, '-', alpha=0.5, markerfacecolor='none', markersize=2.0, label='interpolated') quench.birks_integrand_interpolated.plot_vs(quench.integrator_ekin.points.x, 'o', alpha=0.5, color='black', markersize=0.6) ax.legend(loc='lower right') savefig() ax.set_xlim(left=0.0001) ax.set_ylim(bottom=0.3) # ax.set_yscale('log') ax.set_xscale('log') savefig(opts.output, suffix='_spower_int') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'Edep, MeV' ) ax.set_ylabel( '' ) ax.set_title( "Birk's integral (bin by bin)" ) quench.birks_integral.plot_hist() savefig() ax.set_xlim(left=0.0001) ax.set_ylim(bottom=0.0) # ax.set_yscale('log') ax.set_xscale('log') ax.set_ylim(auto=True) savefig(opts.output, suffix='_spower_intc') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'Edep, MeV' ) ax.set_ylabel( 'Evis, MeV' ) ax.set_title( 'Electron energy (Birks)' ) # birks_accumulator.reduction.out.plot_vs(integrator_evis.transformations.hist, '-', markerfacecolor='none', markersize=2.0, label='partial sum') quench.birks_accumulator.reduction.plot_vs(quench.histoffset.histedges.points_offset) ax.plot([0.0, 12.0], [0.0, 12.0], '--', alpha=0.5) savefig(opts.output, suffix='_birks_evis') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'Edep, MeV' ) ax.set_ylabel( 'Evis/Edep' ) ax.set_title( 'Electron energy (Birks)' ) # birks_accumulator.reduction.out.plot_vs(integrator_evis.transformations.hist, '-', markerfacecolor='none', markersize=2.0, label='partial sum') quench.histoffset.histedges.points_offset.vs_plot(quench.birks_accumulator.reduction.data()/quench.histoffset.histedges.points_offset.data()) ax.set_ylim(0.40, 1.0) savefig(opts.output, suffix='_birks_evis_rel') ax.set_xlim(1.e-3, 2.0) ax.set_xscale('log') savefig() fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( 'Npe' ) ax.set_title( 'Cherenkov photons' ) quench.cherenkov.cherenkov.ch_npe.plot_vs(quench.histoffset.histedges.points_offset) savefig(opts.output, suffix='_cherenkov_npe') ax.set_ylim(bottom=0.1) ax.set_yscale('log') savefig() ax.set_xlim(0.0, 2.0) # ax.set_ylim(0.0, 200.0) savefig() fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( 'Npe' ) ax.set_title( 'Electron model' ) quench.electron_model.single().plot_vs(quench.histoffset.histedges.points_offset) savefig(opts.output, suffix='_electron') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( 'Npe' ) ax.set_title( 'Electron model (low energy view)' ) annihilation_gamma_evis = quench.npe_positron_offset.normconvolution.result.data()[0] label = 'Annihilation contribution=%.2f Npe'%annihilation_gamma_evis quench.electron_model_lowe.plot_vs(quench.ekin_edges_lowe, 'o', markerfacecolor='none', label='data') quench.electron_model_lowe_interpolated.single().plot_vs(quench.annihilation_electrons_centers.single(), '-', label='interpolation\n%s'%label) ax.legend(loc='upper left') savefig(opts.output, suffix='_electron_lowe') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( 'Npe' ) ax.set_title( 'Total Npe' ) quench.positron_model.sum.outputs[0].plot_vs(quench.histoffset.histedges.points_truncated) savefig(opts.output, suffix='_total_npe') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'Edep, MeV' ) ax.set_ylabel( 'Evis, MeV' ) ax.set_title( 'Positron energy model' ) quench.positron_model_scaled.plot_vs(quench.histoffset.histedges.points_truncated, label='definition range') quench.positron_model_scaled_full.plot_vs(quench.histoffset.histedges.points, '--', linewidth=1., label='full range', zorder=0.5) ax.vlines(normE, 0.0, normE, linestyle=':') ax.hlines(normE, 0.0, normE, linestyle=':') ax.legend(loc='upper left') savefig(opts.output, suffix='_total') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'Edep, MeV' ) ax.set_ylabel( 'Evis/Edep' ) ax.set_title( 'Positron energy nonlineairty' ) quench.positron_model_relative.single().plot_vs(quench.histoffset.histedges.points_truncated, label='definition range') quench.positron_model_relative_full.plot_vs(quench.histoffset.histedges.points, '--', linewidth=1., label='full range', zorder=0.5) ax.vlines(normE, 0.0, 1.0, linestyle=':') ax.legend(loc='lower right') ax.set_ylim(0.85, 1.1) savefig(opts.output, suffix='_total_relative') ax.set_xlim(0.75, 3) savefig(opts.output, suffix='_total_relative1') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel('Etrue, MeV') ax.set_ylabel('Edep, MeV') ax.set_title( 'Smearing matrix' ) quench.pm_histsmear.matrix.FakeMatrix.plot_matshow(mask=0.0, extent=[evis_edges_full_input.min(), evis_edges_full_input.max(), evis_edges_full_input.max(), evis_edges_full_input.min()], colorbar=True) ax.plot([0.0, 12.0], [0.0, 12.0], '--', alpha=0.5, linewidth=1.0, color='magenta') ax.vlines(normE, 0.0, normE, linestyle=':') ax.hlines(normE, 0.0, normE, linestyle=':') savefig(opts.output, suffix='_matrix') ax.set_xlim(0.8, 3.0) ax.set_ylim(3.0, 0.8) savefig(opts.output, suffix='_matrix_zoom') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( '' ) ax.set_title( 'Reference histogram 1' ) reference_histogram1.single().plot_hist(linewidth=0.5, alpha=1.0, label='original') reference_smeared1.single().plot_hist( linewidth=0.5, alpha=1.0, label='smeared') ax.legend(loc='upper right') savefig(opts.output, suffix='_refsmear1') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( '' ) ax.set_title( 'Matrix projections' ) mat = quench.pm_histsmear.matrix.FakeMatrix.data() proj0 = mat.sum(axis=0) proj1 = mat.sum(axis=1) plot_hist(evis_edges_full_input, proj0, alpha=0.7, linewidth=1.0, label='Projection 0: Edep view') plot_hist(evis_edges_full_input, proj1, alpha=0.7, linewidth=1.0, label='Projection 1: Evis') ax.legend(loc='upper right') savefig(opts.output, suffix='_matrix_projections') if opts.mapping: fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( '' ) ax.set_title( 'Mapping' ) positron_model_scaled_data = quench.positron_model_scaled.single().data() for e1, e2 in zip(quench.histoffset.histedges.points_truncated.data(), positron_model_scaled_data): if e2>12.0 or e2<1.022: alpha = 0.05 else: alpha = 0.7 ax.plot( [e1, e2], [1.0, 0.0], '-', linewidth=2.0, alpha=alpha ) ax.axvline(1.022, linestyle='--', linewidth=1.0) ax.axvline(12.0, linestyle='--', linewidth=1.0) fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() # ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( '' ) ax.set_title( 'Mapping' ) positron_model_scaled_data = quench.positron_model_scaled.single().data() for e1, e2 in zip(quench.histoffset.histedges.points_truncated.data(), positron_model_scaled_data): if e2>12.0 or e2<1.022: alpha = 0.05 else: alpha = 0.7 ax.plot( [e1, e2], [1.1, 0.9], '-', linewidth=2.0, alpha=alpha ) for e1 in quench.histoffset.histedges.points.data(): ax.axvline(e1, linestyle=':', linewidth=1.0, color='black') ax.axvline(1.022, linestyle='--', linewidth=1.0) ax.axvline(12.0, linestyle='--', linewidth=1.0) # ax.legend(loc='upper right') savefig(opts.output, suffix='_mapping_bins') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( '' ) ax.set_title( 'Reference histogram 2' ) reference_histogram2.single().plot_hist(linewidth=0.5, alpha=1.0, label='original') reference_smeared2.single().plot_hist( linewidth=0.5, alpha=1.0, label='smeared') ax.vlines(normE, 0.0, 1.0, linestyle=':') ax.legend(loc='upper right') savefig(opts.output, suffix='_refsmear2') fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'E, MeV' ) ax.set_ylabel( 'Entries' ) ax.set_title( 'Annihilation gamma electrons' ) plot_hist(quench.annihilation_electrons_edges_input, quench.annihilation_electrons_p_input) ax.set_yscale('log') savefig(opts.output, suffix='_annihilation_electrons') ax.set_yscale('linear') ax.set_xlim(0.0, 0.1) savefig(opts.output, suffix='_annihilation_electrons_lin') if pdfpages: pdfpages.__exit__(None,None,None) print('Write output figure to', pdfpagesfilename) savegraph(quench.histoffset.histedges.points_truncated, opts.graph, namespace=ns) if opts.show: P.show()