def build(self): edges = self.cfg.edges emin, emax = self.cfg.normalize try: (imin, imax), = N.where(((edges - emin) * (edges - emax)).round(6) == 0.0) except: raise Exception( 'Was able to determine normalization region for Fast Neutrons (%f, %f)' % (emin, emax)) data = N.zeros(edges.size - 1) data[imin:imax] = 1.0 data /= data.sum() label = self.cfg.get('label', 'hist {autoindex}') for it in self.nidx.iterate(): hist = C.Histogram(edges, data, labels=it.current_format(label)) self.set_output(self.cfg.name, it, hist.single()) # """Provide the outputs and objects""" self.context.objects[('hist', ) + it.current_values()] = hist
def test_histogram_v01_TH1D(tmp_path): rhist = R.TH1D('testhist', 'testhist', 20, -5, 5) rhist.FillRandom('gaus', 10000) hist = C.Histogram(rhist) buf = rhist.get_buffer() res = hist.hist.hist() # Plot fig = plt.figure() ax = plt.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('X label') ax.set_ylabel('entries') ax.set_title('Histogram') rhist.plot(alpha=0.5, linestyle='dashed', label='ROOT histogram') hist.hist.hist.plot_hist(alpha=0.5, linestyle='dashdot', label='GNA histogram') ax.legend() suffix = 'histogram1d' path = os.path.join(str(tmp_path), suffix + '.png') savefig(path, dpi=300) allure_attach_file(path) plt.close() path = os.path.join(str(tmp_path), suffix + '_graph.png') savegraph(hist.hist, path) allure_attach_file(path) plt.close() # Test consistency assert np.all(buf == res)
def test_typeclass_ndim_v01(): objects = [C.Histogram(np.arange(6), np.arange(5)), C.Points(np.arange(5))] outputs = [p.single() for p in objects] obj = C.DummyType() list(map(obj.add_input, outputs)) dt = R.TypeClasses.CheckNdimT(context.current_precision())(1) R.SetOwnership(dt, False) dt.dump() print() obj.add_typeclass(dt) res = obj.process_types() assert res dt1 = R.TypeClasses.CheckNdimT(context.current_precision())(2) R.SetOwnership(dt1, False) dt1.dump() print() obj.add_typeclass(dt1) print('Exception expected: ', end='') res = obj.process_types() assert not res
def _handler_root(self, source): import mpl_tools.root2numpy as r2n r2n.bind() def _apply_filters(names): if not self.opts.take: yield names for filt in self.opts.take: yield fn.filter(names, filt) roo_file = ROOT.TFile(source) items_in_file = [_.GetName() for _ in iter(roo_file.GetListOfKeys())] filtered = list(chain(*_apply_filters(items_in_file))) # register observables for name in filtered: hist = roo_file.Get(name) data, edges = hist.get_buffer(), hist.get_edges() obs = C.Histogram(edges, data) self.data.append(obs) self.namespace.addobservable(name, obs.hist) roo_file.Close()
def test_typeclass_passeach(): """Last input has another edges""" objects = [ C.Histogram2d(np.arange(4), np.arange(5)), C.Histogram(np.arange(4)), C.Points(np.arange(20).reshape(4,5)) ] outputs = [p.single() for p in objects] obj = C.DummyType() j = list(map(obj.add_input, outputs)) for i in range(5): obj.add_output() dt1 = R.TypeClasses.PassTypeT(context.current_precision())((2,), (0,1)) dt2 = R.TypeClasses.PassEachTypeT(context.current_precision())((0,-1), (2,-1)) R.SetOwnership(dt1, False) R.SetOwnership(dt2, False) dt1.dump(); print() dt2.dump(); print() obj.add_typeclass(dt1) obj.add_typeclass(dt2) res = obj.process_types(); assert res obj.print() dta = outputs[0].datatype() dtb = outputs[1].datatype() dtc = outputs[2].datatype() doutputs = obj.transformations.back().outputs assert doutputs[0].datatype()==dtc assert doutputs[1].datatype()==dtc assert doutputs[2].datatype()==dta assert doutputs[3].datatype()==dtb assert doutputs[4].datatype()==dtc
def test_histedges_v01(edges): centers = 0.5*(edges[1:]+edges[:-1]) widths = edges[1:]-edges[:-1] data = N.arange(edges.size-1) hist = C.Histogram(edges, data) h2e = R.HistEdges() h2e.histedges.hist(hist.hist.hist) out_edges = h2e.histedges.edges.data() out_centers = h2e.histedges.centers.data() out_widths = h2e.histedges.widths.data() print( 'Input:' ) print( edges ) print( 'Output:' ) print( 'Edges', out_edges ) print( 'Centers', out_centers ) print( 'Widths', out_widths ) assert (edges==out_edges).all() assert (centers==out_centers).all() assert (widths==out_widths).all()
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", (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='Pessimistic'), ) 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, 15.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'] # # Python energy model interpolation function # from scipy.interpolate import interp1d lsnl_x = quench.histoffset.histedges.points_truncated.data() lsnl_y = quench.positron_model_relative.single().data() lsnl_fcn = interp1d(lsnl_x, lsnl_y, kind='quadratic') # # Energy resolution # def eres_sigma_rel(edep): return 0.03 / edep**0.5 def eres_sigma_abs(edep): return 0.03 * edep**0.5 # # Energy offset # from physlib import pc edep_offset = pc.DeltaNP - pc.ElectronMass # # Oscprob # baselinename = 'L' ns = env.ns("oscprob") import gna.parameters.oscillation gna.parameters.oscillation.reqparameters(ns) ns.defparameter(baselinename, central=52.0, fixed=True, label='Baseline, km') # # Define energy range # enu_input = N.arange(1.8, 15.0, 0.001) edep_input = enu_input - edep_offset edep_lsnl = edep_input * lsnl_fcn(edep_input) # Initialize oscillation variables enu = C.Points(enu_input, labels='Neutrino energy, MeV') component_names = C.stdvector(['comp0', 'comp12', 'comp13', 'comp23']) with ns: R.OscProbPMNSExpressions(R.Neutrino.ae(), R.Neutrino.ae(), component_names, ns=ns) labels = [ 'Oscillation probability|%s' % s for s in ('component 12', 'component 13', 'component 23', 'full', 'probsum') ] oscprob = R.OscProbPMNS(R.Neutrino.ae(), R.Neutrino.ae(), baselinename, labels=labels) enu >> oscprob.full_osc_prob.Enu enu >> (oscprob.comp12.Enu, oscprob.comp13.Enu, oscprob.comp23.Enu) unity = C.FillLike(1, labels='Unity') enu >> unity.fill.inputs[0] with ns: op_sum = C.WeightedSum(component_names, [ unity.fill.outputs[0], oscprob.comp12.comp12, oscprob.comp13.comp13, oscprob.comp23.comp23 ], labels='Oscillation probability sum') psur = op_sum.single().data() from scipy.signal import argrelmin, argrelmax psur_minima, = argrelmin(psur) psur_maxima, = argrelmax(psur) def build_extrema(x): data_min_x = (x[psur_minima][:-1] + x[psur_minima][1:]) * 0.5 data_min_y = (x[psur_minima][1:] - x[psur_minima][:-1]) data_max_x = (x[psur_maxima][:-1] + x[psur_maxima][1:]) * 0.5 data_max_y = (x[psur_maxima][1:] - x[psur_maxima][:-1]) data_ext_x = N.vstack([data_max_x, data_min_x]).T.ravel() data_ext_y = N.vstack([data_max_y, data_min_y]).T.ravel() return data_ext_x, data_ext_y psur_ext_x_enu, psur_ext_y_enu = build_extrema(enu_input) psur_ext_x_edep, psur_ext_y_edep = build_extrema(edep_input) psur_ext_x_edep_lsnl, psur_ext_y_edep_lsnl = build_extrema(edep_lsnl) # # 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 = '' pdfpages = None 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.8, 1.05) savefig(opts.output, suffix='_total_relative') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Edep, MeV') ax.set_ylabel(r'$\sigma/E$') ax.set_title('Energy resolution') ax.plot(edep_input, eres_sigma_rel(edep_input), '-') savefig(opts.output, suffix='_eres_rel') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Edep, MeV') ax.set_ylabel(r'$\sigma$') ax.set_title('Energy resolution') ax.plot(edep_input, eres_sigma_abs(edep_input), '-') savefig(opts.output, suffix='_eres_abs') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Enu, MeV') ax.set_ylabel('Psur') ax.set_title('Survival probability') op_sum.single().plot_vs(enu.single(), label='full') ax.plot(enu_input[psur_minima], psur[psur_minima], 'o', markerfacecolor='none', label='minima') ax.plot(enu_input[psur_maxima], psur[psur_maxima], 'o', markerfacecolor='none', label='maxima') savefig(opts.output, suffix='_psur_enu') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Edep, MeV') ax.set_ylabel('Psur') ax.set_title('Survival probability') op_sum.single().plot_vs(edep_input, label='true') op_sum.single().plot_vs(edep_lsnl, label='with LSNL') ax.legend() savefig(opts.output, suffix='_psur_edep') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Enu, MeV') ax.set_ylabel('Dist, MeV') ax.set_title('Nearest peaks distance') ax.plot(psur_ext_x_enu, psur_ext_y_enu, 'o-', markerfacecolor='none') savefig(opts.output, suffix='_dist_enu') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Edep, MeV') ax.set_ylabel('Dist, MeV') ax.set_title('Nearest peaks distance') ax.plot(psur_ext_x_edep, psur_ext_y_edep, '-', markerfacecolor='none', label='true') ax.plot(psur_ext_x_edep_lsnl, psur_ext_y_edep_lsnl, '-', markerfacecolor='none', label='with LSNL') ax.plot(edep_input, eres_sigma_abs(edep_input), '-', markerfacecolor='none', label=r'$\sigma$') ax.legend(loc='upper left') savefig(opts.output, suffix='_dist') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Edep, MeV') ax.set_ylabel(r'Dist/$\sigma$') ax.set_title('Resolution ability') x1, y1 = psur_ext_x_edep, psur_ext_y_edep / eres_sigma_abs(psur_ext_x_edep) x2, y2 = psur_ext_x_edep_lsnl, psur_ext_y_edep_lsnl / eres_sigma_abs( psur_ext_x_edep_lsnl) ax.plot(x1, y1, '-', markerfacecolor='none', label='true') ax.plot(x2, y2, '-', markerfacecolor='none', label='with LSNL') ax.legend(loc='upper left') savefig(opts.output, suffix='_ability') ax.set_xlim(3, 4) ax.set_ylim(5, 8) savefig(opts.output, suffix='_ability_zoom') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('Edep, MeV') ax.set_ylabel(r'Dist/$\sigma$') ax.set_title('Resolution ability difference (quenching-true)') y2fcn = interp1d(x2, y2) y2_on_x1 = y2fcn(x1) diff = y2_on_x1 - y1 from scipy.signal import savgol_filter diff = savgol_filter(diff, 21, 3) ax.plot(x1, diff) savefig(opts.output, suffix='_ability_diff') 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()
xyg.SetParameter(1, -1 / 8.) R.gDirectory.Add(xyg) roothist2d.FillRandom('xyg', 10000) # Fill TMatrixD with for i, (i1, i2) in enumerate( I.product(range(rootmatrix.GetNrows()), range(rootmatrix.GetNcols()))): rootmatrix[i1, i2] = i # Create Points p1 = C.Points(roothist1d) p2 = C.Points(roothist2d) p3 = C.Points(rootmatrix) # Create Histograms h1d = C.Histogram(roothist1d) h2d = C.Histogram2d(roothist2d) # Check p1 print('Points from TH1D (underflow/overflow are ignored)') roothist1d.Print('all') print(p1.points.points()) fig = plt.figure() ax = plt.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('X axis') ax.set_ylabel('Entries') ax.set_title('Points and TH1 comparison')
# Define namespaces # namespaces = cfg.detector.detectors # # Bin edges, required by energy nonlinearity # Data input # nbins = 240 edges = N.linspace(0.0, 12.0, nbins+1, dtype='d') points = C.Points(edges) hists_list = () for eset in ( (1.025, 6.025), (2.025, 7.025), (3.025, 8.025) ): heights = unit_bins_at( eset, edges ) hist = C.Histogram( edges, heights ) hists_list += hist, # # Define the chain # shared = NestedDict( edges=points.single() ) b, = execute_bundles(cfg=cfg.detector, namespaces=namespaces, shared=shared) print('Parameters:') env.globalns.printparameters(labels=True) # # Connect inputs # for inp, hist in zip(b.inputs.values(), hists_list):
centers_m = conversion_fcn_direct(centers) edges_m = conversion_fcn_direct(edges) edges_back = conversion_fcn_inverse(edges) print('Edges before:', edges) print('Edges after:', edges_m) print('Edges back:', edges_back) matp_a = rescale_to_matrix_a( edges, edges_m, roundto=3 ) matp_b = rescale_to_matrix_b( edges, centers_m, roundto=3 ) matp_c = rescale_to_matrix_c( edges, edges_m, centers_m, roundto=3 ) pedges_m = C.Points(edges_m) pcenters = C.Points(centers) ntrue = C.Histogram(edges, np.ones(edges.size-1)) nlA = C.HistNonlinearity(True) nlA.set(ntrue.hist, pedges_m) nlA.add_input() # nlB = C.HistNonlinearityB(True) # nlB.set(ntrue.hist, pcenters) # nlB.add_input() mat_a = nlA.matrix.FakeMatrix.data() # mat_b = nlB.matrix.FakeMatrix.data() print( 'Mat A and its sum' ) print( mat_a ) print( mat_a.sum( axis=0 ) )
data1 = np.zeros(nbins, dtype='d') data1[20] = 1.0 # 1 MeV data1[120] = 1.0 # 6 MeV data1[200] = 1.0 # 10 MeV data2 = np.zeros(nbins, dtype='d') data2[40] = 1.0 # 2 MeV data2[140] = 1.0 # 7 MeV data2[220] = 1.0 # 11 MeV data3 = np.zeros(nbins, dtype='d') data3[60] = 1.0 # 3 MeV data3[160] = 1.0 # 8 MeV data3[239] = 1.0 # 12 MeV hist1 = C.Histogram(edges, data1) hist1.hist.setLabel('Input histogram 1') hist2 = C.Histogram(edges, data2) hist2.hist.setLabel('Input histogram 2') hist3 = C.Histogram(edges, data3) hist3.hist.setLabel('Input histogram 3') # # Bind outputs # suffix = '' if cfg.split_transformations else 'merged_' savegraph(b.context.outputs.smearing_matrix.values(), tutorial_image_name('png', suffix=suffix + 'graph0'), rankdir='TB')
def build(self): snf_ratio = C.Histogram(self.cfg.edges, self.ratio_spectrum ) self.objects['snf_spectra'] = snf_ratio self.set_output(snf_ratio.single(), "snf_ratio")
def test_rebinner(tmp_path): 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) ntrue >> rebin.rebin.histin 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 # print(((prj == 1.0) + (prj == 0.0)).all() and '\033[32mOK!' or '\033[31mFAIL!', '\033[0m') fig = plt.figure() ax = plt.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') path = os.path.join(str(tmp_path), 'rebinner_hist.png') savefig(path, dpi=300) allure_attach_file(path) plt.close() # # Plot matrix # fig = plt.figure() ax = plt.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 ) path = os.path.join(str(tmp_path), 'rebinner_matrix.png') savefig(path, dpi=300) allure_attach_file(path) plt.close()
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()
env.defparameter('Eres_c', central=0.0, fixed=True) print_parameters(env.globalns) # # Define bin edges # nbins = 40 edges = N.linspace(0.0, 2.0, nbins + 1) binwidth = edges[1] - edges[0] centers = (edges[1:] + edges[:-1]) * 0.5 efine = N.arange(edges[0], edges[-1] + 1.e-5, 0.005) ax = axes('Energy resolution impact') phist = N.ones(edges.size - 1) 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() eres.smear.plot_hist(label='default') arrays = N.eye(20, edges.size - 1, dtype='d') objects = [C.Histogram(edges, a) for a in arrays] outputs = [o.single() for o in objects] for i, out in enumerate(outputs): out = eres.add_input(out)
import gna.constructors as C import numpy as np from gna.bindings import common from matplotlib import pyplot as plt # Create numpy array for data points nbins = 40 # Create numpy array for bin edges edges = np.linspace(1.0, 10.0, nbins + 1) narray1 = np.exp(edges[:-1]) narray2 = np.flip(narray1) narray3 = narray1[-1] * np.exp(-0.5 * (5.0 - edges[:-1])**2 / 1.0) / (2 * np.pi)**0.5 # Create a histogram instance with data, stored in `narray` # and edges, stored in `edges` hist1 = C.Histogram(edges, narray1) hist2 = C.Histogram(edges, narray2) hist3 = C.Histogram(edges, narray3) fig = plt.figure() ax = plt.subplot(111) ax.set_title('Plot title (left)') ax.minorticks_on() ax.grid() ax.set_xlabel('x label') ax.set_ylabel('y label') plt.ticklabel_format(style='sci', axis='y', scilimits=(-2, 2), useMathText=True)
def main(opts): global savefig 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): close = kwargs.pop('close', False) if opts.individual and args and args[0]: savefig_old(*args, **kwargs) pdf.savefig() if close: P.close() else: pdf = None pdfpagesfilename = '' pdfpages = None cfg = NestedDict( bundle = dict( name='energy_nonlinearity_birks_cherenkov', version='v01', nidx=[ ('r', 'reference', ['R1', 'R2']) ], major=[], ), stopping_power='data/data_juno/energy_model/2019_birks_cherenkov_v01/stoppingpower.txt', annihilation_electrons=dict( file='data/data_juno/energy_model/2019_birks_cherenkov_v01/hgamma2e.root', histogram='hgamma2e_1KeV', scale=1.0/50000 # events 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", (11.9999999, '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 = 'Pessimistic' ), ) ns = env.globalns('energy') quench = execute_bundle(cfg, namespace=ns) print() normE = ns['normalizationEnergy'].value() # # Input bins # evis_edges_full_input = N.arange(0.0, 15.0+1.e-6, 0.001) 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'] # # Python energy model interpolation function # lsnl_x = quench.histoffset.histedges.points_truncated.data() lsnl_y = quench.positron_model_relative.single().data() lsnl_fcn = interp1d(lsnl_x, lsnl_y, kind='quadratic', bounds_error=False, fill_value='extrapolate') # # Energy resolution # def eres_sigma_rel(edep): return 0.03/edep**0.5 def eres_sigma_abs(edep): return 0.03*edep**0.5 # # Oscprob # baselinename='L' ns = env.ns("oscprob") import gna.parameters.oscillation gna.parameters.oscillation.reqparameters(ns) ns.defparameter(baselinename, central=52.0, fixed=True, label='Baseline, km') # # Define energy range # data = Data(N.arange(1.8, 15.0, 0.001), lsnl_fcn=lsnl_fcn, eres_fcn=eres_sigma_abs) # Initialize oscillation variables enu = C.Points(data.enu, labels='Neutrino energy, MeV') component_names = C.stdvector(['comp0', 'comp12', 'comp13', 'comp23']) with ns: R.OscProbPMNSExpressions(R.Neutrino.ae(), R.Neutrino.ae(), component_names, ns=ns) labels=['Oscillation probability|%s'%s for s in ('component 12', 'component 13', 'component 23', 'full', 'probsum')] oscprob = R.OscProbPMNS(R.Neutrino.ae(), R.Neutrino.ae(), baselinename, labels=labels) enu >> oscprob.full_osc_prob.Enu enu >> (oscprob.comp12.Enu, oscprob.comp13.Enu, oscprob.comp23.Enu) unity = C.FillLike(1, labels='Unity') enu >> unity.fill.inputs[0] with ns: op_sum = C.WeightedSum(component_names, [unity.fill.outputs[0], oscprob.comp12.comp12, oscprob.comp13.comp13, oscprob.comp23.comp23], labels='Oscillation probability sum') oscprob.printtransformations() env.globalns.printparameters(labels=True) ns = env.globalns('oscprob') data.set_dm_par(ns['DeltaMSqEE']) data.set_nmo_par(ns['Alpha']) data.set_psur_fcn(op_sum.single().data) data.build() # # Plotting # xmax = 12.0 # # Positron non-linearity # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='Evis/Edep', title='Positron energy nonlineairty') ax.minorticks_on(); ax.grid() 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.8, 1.05) ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_total_relative', close=not opts.show_all) # # Positron non-linearity derivative # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='dEvis/dEdep', title='Positron energy nonlineairty derivative') ax.minorticks_on(); ax.grid() e = quench.histoffset.histedges.points_truncated.single().data() f = quench.positron_model_relative.single().data()*e ec = (e[1:] + e[:-1])*0.5 df = (f[1:] - f[:-1]) dedf = (e[1:] - e[:-1])/df ax.plot(ec, dedf) ax.legend(loc='lower right') ax.set_ylim(0.975, 1.01) ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_total_derivative', close=not opts.show_all) # # Positron non-linearity effect # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='Evis/Edep', title='Positron energy nonlineairty') ax.minorticks_on(); ax.grid() es = N.arange(1.0, 3.1, 0.5) esmod = es*lsnl_fcn(es) esmod_shifted = esmod*(es[-1]/esmod[-1]) ax.vlines(es, 0.0, 1.0, linestyle='--', linewidth=2, alpha=0.5, color='green', label='Edep') ax.vlines(esmod, 0.0, 1.0, linestyle='-', color='red', label='Edep quenched') ax.legend() savefig(opts.output, suffix='_quenching_effect_0') ax.vlines(esmod_shifted, 0.0, 1.0, linestyle=':', color='blue', label='Edep quenched, scaled') ax.legend() savefig(opts.output, suffix='_quenching_effect_1', close=not opts.show_all) # # Energy resolution # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel=r'$\sigma/E$', title='Energy resolution') ax.minorticks_on(); ax.grid() ax.plot(data.edep, eres_sigma_rel(data.edep), '-') ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_eres_rel', close=not opts.show_all) # # Energy resolution # fig = P.figure() ax = P.subplot(111, xlabel= 'Edep, MeV', ylabel= r'$\sigma$', title='Energy resolution') ax.minorticks_on(); ax.grid() ax.plot(data.edep, eres_sigma_abs(data.edep), '-') ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_eres_abs', close=not opts.show_all) # # Survival probability vs Enu # fig = P.figure() ax = P.subplot(111, xlabel='Enu, MeV', ylabel='Psur', title='Survival probability') ax.minorticks_on(); ax.grid() ax.plot(data.enu, data.data_no.psur[data.dmmid_idx], label=r'full NO') ax.plot(data.enu, data.data_io.psur[data.dmmid_idx], label=r'full IO') ax.plot(data.data_no.data_enu.psur_e[data.dmmid_idx], data.data_no.data_enu.psur[data.dmmid_idx], '^', markerfacecolor='none') ax.legend() ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_psur_enu') ax.set_xlim(2.0, 4.5) savefig(opts.output, suffix='_psur_enu_zoom', close=not opts.show_all) # # Survival probability vs Edep # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='Psur', title='Survival probability') ax.minorticks_on(); ax.grid() ax.plot(data.edep, data.data_no.psur[data.dmmid_idx], label=r'full NO') ax.plot(data.edep, data.data_io.psur[data.dmmid_idx], label=r'full IO') ax.plot(data.data_no.data_edep.psur_e[data.dmmid_idx], data.data_no.data_edep.psur[data.dmmid_idx], '^', markerfacecolor='none') ax.legend() ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_psur_edep') ax.set_xlim(1.2, 3.7) savefig(opts.output, suffix='_psur_edep_zoom', close=not opts.show_all) # # Survival probability vs Edep_lsnl # fig = P.figure() ax = P.subplot(111, xlabel='Edep quenched, MeV', ylabel='Psur', title='Survival probability') ax.minorticks_on(); ax.grid() ax.plot(data.edep_lsnl, data.data_no.psur[data.dmmid_idx], label=r'full NO') ax.plot(data.edep_lsnl, data.data_io.psur[data.dmmid_idx], label=r'full IO') ax.plot(data.data_no.data_edep_lsnl.psur_e[data.dmmid_idx], data.data_no.data_edep_lsnl.psur[data.dmmid_idx], '^', markerfacecolor='none') ax.legend() ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_psur_edep_lsnl') ax.set_xlim(1.2, 3.7) savefig(opts.output, suffix='_psur_edep_lsnl_zoom', close=not opts.show_all) # # Distance between nearest peaks vs Enu, single # fig = P.figure() ax = P.subplot(111, xlabel='Enu, MeV', ylabel='Dist, MeV', title='Nearest peaks distance') ax.minorticks_on(); ax.grid() ax.plot(data.data_no.data_enu.diff_x[data.dmmid_idx], data.data_no.data_enu.diff[data.dmmid_idx], label=r'NO') ax.plot(data.data_io.data_enu.diff_x[data.dmmid_idx], data.data_io.data_enu.diff[data.dmmid_idx], label=r'IO') ax.legend() ax.set_xlim(0.0, xmax) ax.set_ylim(bottom=0.0) savefig(opts.output, suffix='_dist_enu') ax.set_xlim(2.0, 5.0) ax.set_ylim(top=0.5) savefig(opts.output, suffix='_dist_enu_zoom', close=not opts.show_all) # # Distance between nearest peaks vs Edep, single # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='Dist, MeV', title='Nearest peaks distance') ax.minorticks_on(); ax.grid() ax.plot(data.data_no.data_edep.diff_x[data.dmmid_idx], data.data_no.data_edep.diff[data.dmmid_idx], label=r'NO') ax.plot(data.data_io.data_edep.diff_x[data.dmmid_idx], data.data_io.data_edep.diff[data.dmmid_idx], label=r'IO') ax.legend() ax.set_xlim(0.0, xmax) ax.set_ylim(bottom=0.0) savefig(opts.output, suffix='_dist_edep') ax.set_xlim(1.2, 4.2) ax.set_ylim(top=0.5) savefig(opts.output, suffix='_dist_edep_zoom', close=not opts.show_all) # # Distance between nearest peaks vs Edep, single # fig = P.figure() ax = P.subplot(111, xlabel='Edep quenched, MeV', ylabel='Dist, MeV', title='Nearest peaks distance') ax.minorticks_on(); ax.grid() ax.plot(data.data_no.data_edep_lsnl.diff_x[data.dmmid_idx], data.data_no.data_edep_lsnl.diff[data.dmmid_idx], label=r'NO') ax.plot(data.data_io.data_edep_lsnl.diff_x[data.dmmid_idx], data.data_io.data_edep_lsnl.diff[data.dmmid_idx], label=r'IO') ax.legend() ax.set_xlim(0.0, xmax) ax.set_ylim(bottom=0.0) savefig(opts.output, suffix='_dist_edep_lsnl') ax.set_xlim(1.2, 4.2) ax.set_ylim(top=0.5) savefig(opts.output, suffix='_dist_edep_lsnl_zoom') poly = N.polynomial.polynomial.Polynomial([0, 1, 0]) x = data.data_no.data_edep_lsnl.diff_x[data.dmmid_idx] pf = poly.fit(x, data.data_no.data_edep_lsnl.diff[data.dmmid_idx], 2) print(pf) ax.plot(x, pf(x), label=r'NO fit') ax.legend() savefig(opts.output, suffix='_dist_edep_lsnl_fit', close=not opts.show_all) # # Distance between nearest peaks vs Edep, multiple # fig = P.figure() ax = P.subplot(111, xlabel='Edep quenched, MeV', ylabel='Dist, MeV', title='Nearest peaks distance') ax.minorticks_on(); ax.grid() ax.plot(data.data_no.data_edep_lsnl.diff_x[data.dmmid_idx], data.data_no.data_edep_lsnl.diff[data.dmmid_idx], label=r'NO') ax.plot(data.data_io.data_edep_lsnl.diff_x[data.dmmid_idx], data.data_io.data_edep_lsnl.diff[data.dmmid_idx], '--', label=r'IO') for idx in (0, 5, 15, 20): ax.plot(data.data_io.data_edep_lsnl.diff_x[idx], data.data_io.data_edep_lsnl.diff[idx], '--') ax.legend() ax.set_xlim(0.0, xmax) savefig(opts.output, suffix='_dist_edep_lsnl_multi', close=not opts.show_all) # # Distance between nearest peaks difference # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='Dist(IO) - Dist(NO), MeV', title='Nearest peaks distance diff: IO-NO') ax.minorticks_on(); ax.grid() ax.plot(data.e, data.diffs.edep[data.dmmid_idx], '-', markerfacecolor='none', label='Edep') ax.plot(data.e, data.diffs.edep_lsnl[data.dmmid_idx], '-', markerfacecolor='none', label='Edep quenched') ax.plot(data.e, data.diffs.enu[data.dmmid_idx], '-', markerfacecolor='none', label='Enu') ax.legend() savefig(opts.output, suffix='_dist_diff') ax.plot(data.e, data.eres, '-', markerfacecolor='none', label='Resolution $\\sigma$') ax.legend() savefig(opts.output, suffix='_dist_diff_1') # # Distance between nearest peaks difference relative to sigma # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='(Dist(IO) - Dist(NO))/$\\sigma$', title='Nearest peaks distance diff: IO-NO') ax.minorticks_on(); ax.grid() ax.plot(data.e, data.diffs_rel.edep[data.dmmid_idx], '-', markerfacecolor='none', label='Edep') ax.plot(data.e, data.diffs_rel.edep_lsnl[data.dmmid_idx], '-', markerfacecolor='none', label='Edep quenched') i_edep=N.argmax(data.diffs_rel.edep[data.dmmid_idx]) i_edep_lsnl=N.argmax(data.diffs_rel.edep_lsnl[data.dmmid_idx]) ediff = data.e[i_edep] - data.e[i_edep_lsnl] ax.axvline(data.e[i_edep], linestyle='dashed', label='Max location: %.3f MeV'%(data.e[i_edep])) ax.axvline(data.e[i_edep_lsnl], linestyle='dashed', label='Max location: %.3f MeV'%(data.e[i_edep_lsnl])) ax.axvspan(data.e[i_edep], data.e[i_edep_lsnl], alpha=0.2, label='Max location diff: %.3f MeV'%(ediff)) ax.legend() savefig(opts.output, suffix='_dist_diff_rel') # # Distance between nearest peaks difference relative to sigma # fig = P.figure() ax = P.subplot(111, xlabel='Edep, MeV', ylabel='(Dist(IO) - Dist(NO))/$\\sigma$', title='Nearest peaks distance diff: IO-NO') ax.minorticks_on(); ax.grid() ledep = ax.plot(data.e, data.diffs_rel.edep[data.dmmid_idx], '--', markerfacecolor='none', label='Edep')[0] lquench = ax.plot(data.e, data.diffs_rel.edep_lsnl[data.dmmid_idx], '-', color=ledep.get_color(), markerfacecolor='none', label='Edep quenched')[0] kwargs=dict(alpha=0.8, linewidth=1.5, markerfacecolor='none') for idx in (0, 5, 15, 20): l = ax.plot(data.e, data.diffs_rel.edep[idx], '--', **kwargs)[0] ax.plot(data.e, data.diffs_rel.edep_lsnl[idx], '-', color=l.get_color(), **kwargs) ax.legend() savefig(opts.output, suffix='_dist_diff_rel_multi', close=not opts.show_all) # # Distance between nearest peaks difference relative to sigma # fig = P.figure() ax = P.subplot(111, ylabel=r'$\Delta m^2_\mathrm{ee}$', xlabel='Edep quenched, MeV', title='Nearest peaks distance diff: IO-NO/$\\sigma$') ax.minorticks_on(); ax.grid() formatter = ax.yaxis.get_major_formatter() formatter.set_useOffset(False) formatter.set_powerlimits((-2,2)) formatter.useMathText=True c = ax.pcolormesh(data.mesh_e.T, data.mesh_dm.T, data.diffs_rel.edep_lsnl.T) from mpl_tools.helpers import add_colorbar add_colorbar(c, rasterized=True) c.set_rasterized(True) savefig(opts.output, suffix='_dist_diff_rel_heatmap') 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 or opts.show_all: P.show()
def test_histedges_offset_02(): size = 13 for edges_offset in (0, 1.5): edges = N.arange(size, dtype='d') + edges_offset hist_in = C.Histogram(edges) arr = N.zeros(edges.size - 1, dtype=context.current_precision_short()) for offset in range(size - 1): threshold = edges[offset] + 0.6 print('Offset', offset) print('Threshold', threshold) view = C.HistEdgesOffset(hist_in, threshold) edges_truncated = edges[offset:] edges_threshold = edges_truncated.copy() edges_threshold[0] = threshold edges_offset = edges_threshold.copy() edges_offset -= threshold trans = view.histedges points = trans.points.data() points_truncated = trans.points_truncated.data() points_threshold = trans.points_threshold.data() points_offset = trans.points_offset.data() hist_truncated_d = trans.hist_truncated.data() hist_truncated = N.array(trans.hist_truncated.datatype().edges) hist_threshold_d = trans.hist_threshold.data() hist_threshold = N.array(trans.hist_threshold.datatype().edges) hist_offset_d = trans.hist_offset.data() hist_offset = N.array(trans.hist_offset.datatype().edges) print(' Edges (expected)', edges) print(' Edges truncated (expected)', edges_truncated) print(' Edges threshold (expected)', edges_threshold) print(' Edges offset (expected)', edges_offset) print(' Points', points) print(' Points truncated', points_truncated) print(' Points threshold', points_threshold) print(' Points offset', points_offset) print(' Hist truncated', hist_truncated) print(' Hist truncated data', hist_truncated_d) print(' Hist threshold', hist_threshold) print(' Hist threshold data', hist_threshold_d) print(' Hist offset', hist_offset) print(' Hist offset data', hist_offset_d) assert (edges == points).all() assert (edges_truncated == points_truncated).all() assert (edges_threshold == points_threshold).all() assert (edges_offset == points_offset).all() assert (edges_truncated == hist_truncated).all() assert (0.0 == hist_truncated_d).all() assert (edges_threshold == hist_threshold).all() assert (0.0 == hist_threshold_d).all() assert (edges_offset == hist_offset).all() assert (0.0 == hist_offset_d).all()
p2b = ns.defparameter('fcn2.b', central=0.1, free=True, label='weight 2') p2k = ns.defparameter('fcn2.k', central=16.0, free=True, label='argument scale') # Print the list of parameters ns.printparameters(labels=True) print() # Define binning and integration orders nbins = 20 x_edges = np.linspace(-np.pi, np.pi, nbins+1, dtype='d') x_widths = x_edges[1:]-x_edges[:-1] x_width_ratio = x_widths/x_widths.min() orders = 4 # Initialize histogram hist = C.Histogram(x_edges) # Initialize integrator integrator = R.IntegratorGL(nbins, orders) integrator.points.edges(hist.hist.hist) int_points = integrator.points.x # Initialize sine and two cosines sin_t = R.Sin(int_points) cos1_arg = C.WeightedSum( ['fcn1.k'], [int_points] ) cos2_arg = C.WeightedSum( ['fcn2.k'], [int_points] ) cos1_t = R.Cos(cos1_arg.sum.sum) cos2_t = R.Cos(cos2_arg.sum.sum) # Initalizes both weighted sums
# Prepare inputs # emin, emax = 0.0, 12.0 nbins = 240 edges = np.linspace(emin, emax, nbins + 1, dtype='d') peaks = 20, 120, 200 hists = () for i in range(3): data = np.zeros(nbins, dtype='d') for peak in peaks: pos = np.min((peak + 20 * i, nbins - 1)) data[pos] = 1.0 hist = C.Histogram(edges, data) hist.hist.setLabel('Input histogram %i' % i) hists += hist, cfg = NestedDict( bundle=dict( name='expression', version='v01', nidx=[('d', 'detector', ['D1', 'D2', 'D3']), ('z', 'zone', ['z1', 'z2'])], ), verbose=2, # Expression expr=[ 'smearing_matrix[z]| hist0()',
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()
# # Make input histogram # def singularities(values, edges): indices = N.digitize(values, edges) - 1 phist = N.zeros(edges.size - 1) phist[indices] = 1.0 return phist nbins = 240 edges = N.linspace(0.0, 12.0, nbins + 1, dtype='d') points = C.Points(edges, labels='Bin edges') phist = singularities([1.225, 2.225, 4.025, 7.025, 9.025], edges) hist = C.Histogram(edges, phist, labels='Input hist') # # Initialize expression # indices = [('l', 'lsnl_component', ['nominal', 'pull0', 'pull1', 'pull2', 'pull3'])] lib = dict() formulas = [ 'evis_edges()', 'lsnl_coarse = sum[l]| lsnl_weight[l] * lsnl_component_y[l]()', 'lsnl_interpolator| lsnl_x(), lsnl_coarse, evis_edges() ', 'lsnl_edges| hist()', 'lsnl| hist()',
#!/usr/bin/env python from tutorial import tutorial_image_name import gna.constructors as C import numpy as np from gna.bindings import common from matplotlib import pyplot as plt # Create numpy array for data points nbins = 100 narray = np.arange(nbins)**2 * np.arange(nbins)[::-1]**2 # Create numpy array for bin edges edges = np.linspace(1.0, 40.0, nbins+1) # Create a histogram instance with data, stored in `narray` # and edges, stored in `edges` hist = C.Histogram(edges, narray) fig = plt.figure(figsize=(12, 5)) ax = plt.subplot( 121 ) ax.set_title( 'Plot title (left)' ) ax.minorticks_on() ax.grid() ax.set_xlabel( 'x label' ) ax.set_ylabel( 'y label' ) plt.ticklabel_format(style='sci', axis='y', scilimits=(-2,2), useMathText=True) hist.hist.hist.plot_hist(label='histogram 1') ax.legend() ax = plt.subplot( 122 )
orig = np.array( [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] ) orig_proj = fcn_direct(orig) mod_proj = fcn_inverse(orig) xfine = np.linspace(orig[0], orig[-1], 1000) yfine = np.linspace(orig_proj[0], orig_proj[-1], 1000) print('Edges original:', orig) print('Edges original projected:', orig_proj) print('Edges modified projected back:', mod_proj) Orig = C.Points(orig) Orig_proj = C.Points(orig_proj) Mod_proj = C.Points(mod_proj) ntrue = C.Histogram(orig, np.ones(orig.size-1)) nlB = C.HistNonlinearityB(True) nlB.set(ntrue.hist, Orig_proj, Mod_proj) nlB.add_input() print('Get data') mat_b = nlB.matrix.FakeMatrix.data() print( 'Mat B and its sum' ) print( mat_b ) matbsum = mat_b.sum( axis=0 ) print( matbsum ) assert np.allclose(matbsum[1:-1], 1, rtol=0, atol=1.e-16) ntrue.hist.hist.data()
# # Test bundle # def singularities(values, edges): indices = N.digitize(values, edges) - 1 phist = N.zeros(edges.size - 1) phist[indices] = 1.0 return phist binwidth = 0.05 edges = N.arange(0.0, 12.0001, binwidth) phist = singularities([1.225, 4.025, 7.025], edges) hist = C.Histogram(edges, phist) smear1.inputs.Ntrue(hist.hist) smear2.inputs.Ntrue(hist.hist) smear3.inputs.Ntrue(hist.hist) # # Plot # fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('') ax.set_ylabel('') ax.set_title('IAV effect')
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()