def test_histogram_v01_1d(tmp_path): edges = np.logspace(-3, 3, 40) data = np.arange(1.0, edges.size, dtype='d') hist = C.Histogram(edges, data) res = hist.hist.hist() edges_dt = np.array(hist.hist.hist.datatype().edges) # Plot fig = plt.figure() ax = plt.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('X label, log scale') ax.set_ylabel('entries') ax.set_title('Example histogram') ax.set_xscale('log') hist.hist.hist.plot_hist(label='label') 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(res == data) assert np.all(edges == edges_dt)
def main(opts): data = dict() for datum in opts.files: source = datum['info']['source'] step = datum['info']['step'] fun = datum['fun'] data.setdefault(source, []).append( (step, fun) ) fig = plt.figure() ax = plt.subplot(111, xlabel='Internal bin width, keV', ylabel=r'$\Delta \chi^2$', title='Fit stability') ax.minorticks_on() ax.grid() ax.set_xlim(0.0, 21.0) markers = { 'nolsnl': 'x', 'subst': '+', 'proper': 'o', 'dumb': 'o', } offset = min(y for (x,y) in data['subst']) for source, xy in data.items(): x, y = np.array(xy).T idx = np.argsort(x) x, y = x[idx], y[idx] x*=1000.0 # y-=offset ax.plot(x, y, markers.get(source, '*'), label=source, markerfacecolor='none') ax.legend(title='Mode:') savefig(opts.output, suffix='_'+source) plt.show()
def test_anue_free_spectra(tmp_path): """ Test implementation of a model of antineutrino spectra with free parameters in exponential parametrization. """ _enu = np.linspace(1.8, 8.0, 500, dtype='d') Enu = C.Points(_enu, labels='anue energy') indices = [ ('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']) ] expr = ['anuspec[i,r](enu())'] a = Expression_v01(expr, indices = NIndex.fromlist(indices)) a.parse() lib = dict() a.guessname(lib, save=True) ns_anuexpr = env.globalns('anue_expr') cfg = NestedDict( anuspec = NestedDict( bundle = dict(name='reactor_anu_spectra', version='v04'), name = 'anuspec', filename = ['data/reactor_anu_spectra/Huber/Huber_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat', 'data/reactor_anu_spectra/Mueller/Mueller_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat'], # strategy = dict( underflow='constant', overflow='extrapolate' ), varmode='log', varname='anu_weight_{index}', free_params=True, ns_name='spectral_weights', edges = np.concatenate( ( np.arange( 1.8, 8.7, 0.5 ), [ 12.3 ] ) ), ), enu = NestedDict( bundle = NestedDict(name='predefined', version='v01', major=''), name = 'enu', inputs = None, outputs = Enu.single(), ), ) context = ExpressionContext_v01(cfg, ns=ns_anuexpr) a.build(context) ns_anuexpr.printparameters(labels=True) u235_spec = context.outputs.anuspec.U235 u235_spec.plot_vs(Enu.single(), label='default pars') ns_anuexpr['spectral_weights.anu_weight_5'].set(0.3) ns_anuexpr['spectral_weights.anu_weight_7'].set(-0.3) plt.rcParams.update({'font.size': 14}) plt.rcParams.update({'text.usetex': True}) u235_spec.plot_vs(Enu.single(), label='update pars') plt.yscale('log') plt.xlabel(r'$E_{\nu}$, MeV') plt.ylabel('Anue per MeV') plt.legend() plt.title('Antineutrino spectrum') path = os.path.join(str(tmp_path), 'anuspec.png') savefig(path, dpi=300) allure_attach_file(path)
def run(opts): for label, distr in zip( labels, distrs ): data = N.zeros( shape=opts.n, dtype=[ ('x', 'd'), ('y', 'd'), ('z', 'd') ] ) for i in xrange( opts.n ): data[i] = tuple(distr.toymc.data()) distr.nextSample() plot( label, data, opts ) fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.set_xlabel( 'x, y, z' ) ax.set_ylabel( 'x, y, z' ) ax.set_title( 'Covmat' ) c=ax.matshow( cov ) add_colorbar( c ) savefig( opts.output, suffix='_cov' ) P.close() fig = P.figure() ax = P.subplot( 111 ) ax.minorticks_on() ax.set_xlabel( 'x, y, z' ) ax.set_ylabel( 'x, y, z' ) ax.set_title( 'Cormat' ) c = ax.matshow( cor ) add_colorbar( c ) savefig( opts.output, suffix='_cor' ) P.close()
def plot_edges_b(edges, centers, edges_m, centers_m): fig = plt.figure() ax = plt.subplot(111, xlabel='', ylabel='', title='Edges B') ax.set_xlim(left=-2.0, right=10.0) ax.set_ylim(0.0, 3.0) ax.vlines(edges, 0.0, 5.0, linestyle='solid', color='black', alpha=0.4, linewidth=0.2) ax.vlines(edges, 0.0, 1.0, linestyle='solid', color='blue', label='Original') ax.vlines(centers, 0.0, 1.0, linestyle='dashed', color='blue') hwidths = 0.5*(edges[1:]-edges[:-1]) edges_m1 = centers_m-hwidths edges_m2 = centers_m+hwidths ax.vlines(edges_m1, 2.0, 2.5, linestyle='solid', color='red', label='Left') ax.vlines(edges_m2, 2.5, 3.0, linestyle='solid', color='magenta', label='Right') ax.vlines(centers_m, 2.0, 3.0, linestyle='dashed', color='red') for a, b in zip(edges, edges_m): ax.plot( (a, b), (1.0, 2.0), color='gray' ) for i, c in enumerate(centers): ax.text(c, 1.33, str(i), va='center', ha='center') for i, c in enumerate(centers_m): ax.text(c, 1.66, str(i), va='center', ha='center') ax.legend(loc='upper left') savefig(opts.output, suffix='edges_b')
def configure_figure1(self): from matplotlib import pyplot as plt if self.opts.output: from mpl_tools.helpers import savefig savefig(self.opts.output) if self.opts.show: plt.show()
def test_histogram_v02_2d(tmp_path): edgesx = np.logspace(0, 3, 6, base=2) edgesy = np.linspace(0, 10, 20) data = np.arange(1.0, (edgesx.size - 1) * (edgesy.size - 1) + 1, dtype='d').reshape(edgesx.size - 1, edgesy.size - 1) hist = C.Histogram2d(edgesx, edgesy, data) res = hist.hist.hist() edgesx_dt = np.array(hist.hist.hist.datatype().edgesNd[0]) edgesy_dt = np.array(hist.hist.hist.datatype().edgesNd[1]) # Plot fig = plt.figure() ax = plt.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('X (column), log scale') ax.set_ylabel('Y row') ax.set_title('2d histogram example') ax.set_xscale('log') hist.hist.hist.plot_pcolor(colorbar=True) suffix = 'histogram2d' path = os.path.join(str(tmp_path), suffix + '.png') savefig(path, dpi=300) allure_attach_file(path) plt.close() fig = plt.figure() ax = plt.subplot(111, projection='3d') ax.minorticks_on() ax.grid() ax.set_xlabel('X (column)') ax.set_ylabel('Y (row)') ax.set_title('2d histogram example (3d)') ax.azim -= 70 hist.hist.hist.plot_bar3d(cmap=True, colorbar=True) suffix = 'histogram2d_3d' 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(res == data) assert np.all(edgesx == edgesx_dt) assert np.all(edgesy == edgesy_dt)
def test_histogram_v02_TH2D(tmp_path): rhist = R.TH2D('testhist', 'testhist', 20, 0, 10, 24, 0, 12) xyg = R.TF2("xyg", "exp([0]*x)*exp([1]*y)", 0, 10, 0, 12) xyg.SetParameter(0, -1 / 2.) xyg.SetParameter(1, -1 / 8.) R.gDirectory.Add(xyg) rhist.FillRandom('xyg', 10000) hist = C.Histogram2d(rhist) buf = rhist.get_buffer().T 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('Y label') ax.set_title('ROOT histogram') rhist.pcolorfast(colorbar=True) suffix = 'histogram2d' path = os.path.join(str(tmp_path), suffix + '.png') savefig(path, dpi=300) allure_attach_file(path) plt.close() fig = plt.figure() ax = plt.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('X label') ax.set_ylabel('Y label') ax.set_title('GNA histogram') hist.hist.hist.plot_pcolorfast(colorbar=True) suffix = 'histogram2d' 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_offeq_correction_expression(tmp_path): """Same test but build bundle with expressions""" _enu = np.linspace(1., 8.0, 500, dtype='d') Enu = C.Points(_enu, labels='anue energy') indices = [('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']), ('r', 'reactor', ['DB1', 'DB2', 'LA1', 'LA2', 'LA3', 'LA4'])] expr = ['offeq_correction[i,r](enu())'] a = Expression_v01(expr, indices=NIndex.fromlist(indices)) a.parse() lib = dict() a.guessname(lib, save=True) ns_offeq = env.globalns('offeq_expr') cfg = NestedDict( offeq_correction=NestedDict( bundle=dict(name='reactor_offeq_spectra', version='v03', major='ir'), offeq_data= './data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat', ), enu=NestedDict( bundle=NestedDict(name='predefined', version='v01', major=''), name='enu', inputs=None, outputs=Enu.single(), ), ) context = ExpressionContext_v01(cfg, ns=ns_offeq) a.build(context) ns_offeq.printparameters(labels=True) fig, ax = plt.subplots() for iso in indices[0][2]: corrected_spectra = context.outputs.offeq_correction[iso]['DB1'].data() ax.plot(Enu.single().data(), corrected_spectra - 1., label=iso) ax.set_title("Offequilibrium correction") ax.legend(loc='best') ax.grid() ax.set_xlabel("Antineutrino energy, MeV") ax.set_ylabel("(Corrected - nominal) / nominal") suffix = 'correction' path = os.path.join(str(tmp_path), suffix + '.png') savefig(path, dpi=300) savefig(path.replace('.png', '.pdf'), dpi=300) allure_attach_file(path) path = os.path.join(str(tmp_path), suffix + '_graph.png') savegraph(context.outputs.offeq_correction['U235']['DB1'], path) allure_attach_file(path)
def test_offeq_correction(tmp_path): """ Test implementation of off-equilibrium contribution to antineutrino spectra from nuclear fission in commercial reactors. The reason that contribution appears is the fact the electron conversion spectra measured at ILL doesn't take into account long-lived isotopes. That correction is required for precision measurement of oscillation parameters and is uncorrelated between reactors. It comes in a form of ratio of true spectra to nominal Huber-Mueller. """ _enu = np.linspace(1., 8.0, 500, dtype='d') Enu = C.Points(_enu, labels='anue energy') indices = [('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']), ('r', 'reactor', ['DB1', 'DB2', 'LA1', 'LA2', 'LA3', 'LA4'])] cfg = NestedDict( bundle=dict(name='reactor_offeq_spectra', version='v03', nidx=indices), offeq_data= './data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat', ) ns = env.globalns('offeq') offeq, = execute_bundles(cfg, namespace=ns) ns.printparameters(labels=True) for iso in offeq.context.inputs.offeq_correction.values(): try: for _input in iso.values(): Enu >> _input.values() except AttributeError: Enu >> iso fig, ax = plt.subplots() for iso in indices[0][2]: corrected_spectra = offeq.context.outputs.offeq_correction[iso][ 'DB1'].data() ax.plot(Enu.single().data(), corrected_spectra - 1., label=iso) ax.set_title("Offequilibrium correction") ax.grid() ax.legend(loc='best') ax.set_xlabel("Antineutrino energy, MeV") ax.set_ylabel("(Corrected - nominal) / nominal") suffix = 'correction' path = os.path.join(str(tmp_path), suffix + '.png') savefig(path, dpi=300) savefig(path.replace('.png', '.pdf'), dpi=300) allure_attach_file(path) path = os.path.join(str(tmp_path), suffix + '_graph.png') savegraph(offeq.context.outputs.offeq_correction['U235']['DB1'], path) allure_attach_file(path)
def plot_matrix(mat): fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.set_xlabel( 'Source bins' ) ax.set_ylabel( 'Target bins' ) ax.set_title( 'Bin edges conversion matrix' ) ax.set_aspect('equal') ax.set_xlim(orig[0], orig[-1]) ax.set_ylim(orig[-1], orig[0]) mmat = np.ma.array(mat, mask=mat==0.0) c = ax.matshow(mmat, extent=[orig[0], orig[-1], orig[-1], orig[0]]) add_colorbar(c) savefig(opts.output, suffix='matrix_0') ax.plot(xfine, fcn_direct(xfine), '--', color='white') savefig(opts.output, suffix='matrix_1')
def main(args): if args.plot_map: low = np.concatenate(([0.7], np.arange(1.0, 8.0, 0.5))) high = np.concatenate((np.arange(1.5, 6.0, 0.5), [9.0, 12.0])) plot_boxes(low=low, high=high) savefig(args.output, suffix='_map') plt.close() plot_boxes(low=low, high=high, scale=True) savefig(args.output, suffix='_map_scaled') plt.close() data = load_data(args) for i, (idata, title) in enumerate(it.zip_longest(data.values(), args.title)): plot_boxes(idata, title=title, scale=True, output=args.output, suffix=('_{}_scaled'.format(i), )) plt.show()
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 plot_matrix(mat, title, suffix): fig = plt.figure() ax = plt.subplot( 111 ) ax.minorticks_on() ax.set_xlabel( 'Source bins' ) ax.set_ylabel( 'Target bins' ) ax.set_title( 'Bin edges conversion matrix: {}'.format(title) ) mmat = np.ma.array(mat, mask=mat==0.0) c = ax.matshow(mmat, extent=[edges[0], edges[-1], edges[-1], edges[0]]) add_colorbar(c) savefig(opts.output, suffix='matrix_'+suffix) fig = plt.figure() ax = plt.subplot(111, xlabel='Edges', ylabel='', title='Check sum: {}'.format(title)) ax.minorticks_on() rsum = mat.sum(axis=0) ax.plot(centers, rsum, 'o') ax.axhline(1.0) savefig(opts.output, suffix='norm_'+suffix)
def plot(self): fig = plt.figure() ax = plt.subplot(111, xlabel=r'$\Delta m^2_\mathrm{ee}$', ylabel=r'$\Delta \chi^2$', title='Sensivitivy versus mass splitting') ax.minorticks_on() ax.grid() ax.plot(self.dm, self.chi2, '-', markerfacecolor='none') ax.axvline(2.43e-3, label='YB', linestyle='--', color='red') ax.axvline(2.5e-3, label='Current', linestyle='--', color='green') ax.legend() f = ax.xaxis.get_major_formatter() f.set_powerlimits((-2, 2)) f.useMathText = True savefig(self.opts.output) plt.show()
def test_geoneutrino_spectrum_v01(tmp_path): _enu = np.arange(1., 8.0+1.e-6, 0.01, dtype='d') Enu = C.Points(_enu, labels='anue energy') cfg = NestedDict( bundle = dict(name='geoneutrino_spectrum', version='v01'), data = 'data/data-common/geo-neutrino/2006-sanshiro/geoneutrino-luminosity_{isotope}_truncated.knt' ) ns = env.globalns('geonu') geonu, = execute_bundles(cfg, namespace=ns) ns.printparameters(labels=True) Enu >> geonu.context.inputs.values(nested=True) # Dump some info print(geonu.context.inputs) print(geonu.context.outputs) geonu.interp.values()[0].printtransformations() geonu.interp.values()[1].printtransformations() # Plot figures and graphs fig = plt.figure() ax = plt.subplot(111, xlabel=r'$E_{\nu}$, MeV', ylabel='N/MeV/s', title='Geo-neutrino luminosity (truncated at 1.7 MeV)') ax.minorticks_on() ax.grid() for k, v in geonu.context.outputs.items(): ax.plot(_enu, v.data(), label=k) ax.legend() plt.show() savefig(os.path.join(str(tmp_path), '_spectra.png')) savegraph(Enu, os.path.join(str(tmp_path), '_graph.png')) ns.printparameters(labels=True)
def plot_matrix(mat, curve_x=None, curve_y=None, reshapen=None): nbins = mat.shape[0] title = 'Bin edges conversion matrix {}x{}'.format(nbins, nbins) suffix = 'matrix_{}'.format(nbins) if reshapen: nbins_orig, nbins = nbins, nbins // reshapen title = 'Bin edges conversion matrix {}x{} from {}x{}'.format( nbins, nbins, nbins_orig, nbins_orig) suffix = 'matrix_{}_{}'.format(nbins, nbins_orig) mat = reduce_matrix(mat, reshapen) fig = plt.figure() ax = plt.subplot(111) ax.minorticks_on() ax.set_xlabel('Source bins') ax.set_ylabel('Target bins') ax.set_title(title) ax.set_aspect('equal') ax.set_xlim(orig[0], orig[-1]) ax.set_ylim(orig[-1], orig[0]) mmat = np.ma.array(mat, mask=mat == 0.0) c = ax.matshow(mmat, extent=[orig[0], orig[-1], orig[-1], orig[0]]) add_colorbar(c) savefig(opts.output, suffix=suffix) if curve_x is None or curve_y is None: return ax.plot(curve_x, curve_y, '--', color='white') savefig(opts.output, suffix='{}_c'.format(suffix)) return mat
def plot_matrices(self): if self.opts.cmap: plt.set_cmap(self.opts.cmap) fig, ax = plt.subplots() im = ax.matshow(self.covmat) ax.minorticks_on() cbar = fig.colorbar(im) plt.title("Covariance matrix") savefig(self.opts.savefig, suffix='_cov') fig, ax = plt.subplots() im = ax.matshow(self.cormat) ax.minorticks_on() cbar = fig.colorbar(im) plt.title("Correlation matrix") savefig(self.opts.savefig, suffix='_cor') if self.opts.dump: np.savez(self.opts.dump, self.covmat) if self.opts.show: plt.show()
binwidth = 0.05 edges = N.arange(0.0, 12.0001, binwidth) corr, edges_m = nlfcn(edges) edges_m_plot = N.ma.array(edges_m, mask=edges_m <= -1.e100) fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel(L.u('edep')) ax.set_ylabel('Correction') ax.set_title('Non-linearity correction') ax.plot(edges, corr) savefig(opts.output, suffix='_corr') fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel(L.u('edep')) ax.set_ylabel(L.u('evis')) ax.set_title('Non-linearity correction') ax.plot(edges, edges_m_plot) ax.plot([edges[0], edges[-1]], [edges[0], edges[-1]], '--') savefig(opts.output, suffix='_energy') pedges_m = C.Points(edges_m)
def savefig(self, *args): path = '_'.join((self.tmp_path,)+tuple(args))+'.png' savefig(path, dpi=300) allure_attach_file(path)
def run(self): self.params = None self.statistics = {} self.statpoints = {} self.ndim = None self.labels = None if self.opts.labels: self.labels = iter(self.opts.labels) minorLocatorx = AutoMinorLocator() minorLocatory = AutoMinorLocator() if self.opts.figure: plt.figure() ax = plt.subplot( 111 ) else: ax = plt.gca() levels = set() colors = iter('bgrcmyk') for plotdesc in self.opts.plots: plottype, rest = plotdesc[0], plotdesc[1:] pvmap = pvmaptypes[plottype](self) color = self.plotmap(ax, pvmap) if color is None: color = next(colors) for pvspec in rest: pvlevel = self.parselevel(pvspec) # print 'pvmap', pvmap.data # print 'pvlevel', pvlevel self.plotlevel(ax, pvmap, pvlevel, color=color, pvspec=pvspec) levels.add(pvlevel) pointsfile = None if self.opts.savepoints: pointsfile = PointTree(self.env, self.opts.savepoints, "w") pointsfile.params = self.params for plotdesc in self.opts.points: plottype, pvspec, rest = plotdesc[0], plotdesc[1], plotdesc[2:] pvmap = pvmaptypes[plottype](self) if len(rest) > 1: width = (float(rest[0]), float(rest[1])) else: width = (0.05, 0.05) pvlevel = self.parselevel(pvspec) points = self.filterpoints(pvmap, pvlevel, width)[0] if pointsfile: for path in points[0]: pointsfile.touch(path) self.plotpoints(ax, points[0]) if self.ndim == 1: # plt.yticks(list(plt.yticks()[0]) + list(levels)) # labels = ['%g' % loc for loc in plt.yticks()[0]] # ticks, labels = plt.yticks(plt.yticks()[0], labels) #plt.yticks(np.arange(self.opts.ylim[0], self.opts.ylim[1], (self.opts.ylim[1]-self.opts.ylim[0])/10.0)) for level in levels: plt.axhline(level, linestyle='-.') xlabel = r'{}'.format(self.opts.xlabel) ylabel = r'{}'.format(self.opts.ylabel) ax.set_xlabel(xlabel, fontsize='xx-large') ax.set_ylabel(ylabel, fontsize='xx-large') if self.opts.xlog: ax.semilogx() ax.grid(False) elif self.ndim == 2 and self.opts.no_bestfit: if self.statpoints.get('chi2min'): xy = [self.statpoints['chi2min'][par] for par in reversed(self.opts.minimizer.pars)] # self.fixaxes(xy) print('bestfit', xy[0], xy[1]) ax.plot(xy[0], xy[1], 'o', label='Best fit') # ax.set_xlabel(r'$\sigma_{rel}$', fontsize='xx-large') if 'dm31' in self.params: if self.opts.dm32: ax.set_ylabel(r'$\Delta m^2_{23}$', fontsize='xx-large') else: ax.set_ylabel(r'$\Delta m^2_{13}$', fontsize='xx-large') elif 'theta13' in self.params: ax.set_ylabel(r'$\sin^2 2\theta_{13}$', fontsize='xx-large') ax.grid(True) if self.opts.ylim is not None: ax.set_ylim(self.opts.ylim) if self.opts.xlim is not None: ax.set_xlim(self.opts.xlim) if self.opts.drawgrid: ax.xaxis.set_minor_locator(minorLocatorx) ax.yaxis.set_minor_locator(minorLocatory) plt.tick_params(which='both', width=1) plt.tick_params(which='major', length=7) plt.tick_params(which='minor', length=4, color='k') ax.grid(which = 'minor', alpha = 0.3) ax.grid(which = 'major', alpha = 0.7) if self.opts.legend: plt.legend(loc=' '.join(self.opts.legend)) if self.opts.title: plt.title(r'{0}'.format(self.opts.title)) if self.opts.output: savefig(self.opts.output) if self.opts.show: plt.show() return True
def savefig(self, suffix): savefig(self.opts.output, dpi=300, suffix=suffix)
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()
def main(args): low = np.concatenate(([0.7], np.arange(1.0, 8.0, 0.5))) high = np.concatenate((np.arange(1.5, 6.0, 0.5), [9.0, 12.0])) plot_boxes(low, high) savefig(args.output, suffix='_map') hasmap = True plot_boxes(low, high, scale=True) savefig(args.output, suffix='_map_scaled') datasets = load_data(args) for i, ((low, high, data), title) in enumerate(it.zip_longest(datasets, args.title)): plot_boxes(low, high, data, title=title) savefig(args.output, suffix='_{}_full'.format(i)) ax = plt.gca() ax.set_xlim(right=4.0) savefig(args.output, suffix='_{}_zoom'.format(i)) plot_boxes(low, high, data, title=title, scale=True) savefig(args.output, suffix='_{}_scaled_full'.format(i)) ax = plt.gca() ax.set_xlim(right=4.0) savefig(args.output, suffix='_{}_scaled_zoom'.format(i)) plt.show()
ax.plot(b.storage.edges[::stride], b.storage[name][::stride], 'o', markerfacecolor='none', color=lines[0].get_color()) for par in pars[1:]: par.set(0.0) escale.set(1.1) ax.plot(edges, corr.sum.sum.data(), '--', label='escale=1.1') escale.set(1.0) ax.legend(loc='lower right') savefig(opts.output, suffix='_escale') # # Test bundle # smear.Ntrue(hist.hist) # # Plot hists # fig = P.figure() ax = P.subplot(111) ax.minorticks_on() ax.grid() ax.set_xlabel('') ax.set_ylabel('')
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 ) ax.set_title( 'Plot title (right)' ) 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_bar(label='histogram 1 (bar)', alpha=0.6) ax.legend() from mpl_tools.helpers import savefig savefig(tutorial_image_name('png')) plt.show()
print('Parameters after modification') env.globalns.printparameters() for name, output in b.outputs.items(): data=output.data().copy() ax.plot( points, N.ma.array(data, mask=data==0.0), '--', label=L.s(name) ) if opts.log: ax.set_yscale('log') ax.legend( loc='upper right' ) if opts.dot: try: from gna.graphviz import GNADot kwargs=dict( # splines='ortho' joints=False, ) graph = GNADot( b.transformations_out.values()[0], **kwargs ) graph.write(opts.dot) print( 'Write output to:', opts.dot ) except Exception as e: print( '\033[31mFailed to plot dot\033[0m' ) savefig(opts.output) if opts.show: P.show()
def test_offeq_correction_expression(tmp_path): """Tests for new version of offequilibrium correction with snapshoting initial spectrum""" _enu = np.linspace(1., 8.0, 500, dtype='d') Enu = C.Points(_enu, labels='anue energy') indices = [('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']), ('r', 'reactor', ['DB1', 'DB2', 'LA1', 'LA2', 'LA3', 'LA4'])] expr = [ 'enu()', 'anuspec[i](enu())', 'offeq_correction[i,r]| enu(), anuspec[i]()' ] a = Expression_v01(expr, indices=NIndex.fromlist(indices)) a.parse() lib = dict() a.guessname(lib, save=True) ns_offeq = env.globalns('offeq_expr_v04') cfg = NestedDict( offeq_correction=NestedDict( bundle=dict(name='reactor_offeq_spectra', version='v04', major='ir'), offeq_data= './data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat', ), enu=NestedDict( bundle=NestedDict(name='predefined', version='v01', major=''), name='enu', inputs=None, outputs=Enu.single(), ), anuspec=NestedDict( bundle=dict(name='reactor_anu_spectra', version='v04'), name='anuspec', filename=[ 'data/reactor_anu_spectra/Huber/Huber_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat', 'data/reactor_anu_spectra/Mueller/Mueller_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat' ], varmode='log', varname='anu_weight_{index}', free_params=True, ns_name='spectral_weights', edges=np.concatenate((np.arange(1.8, 8.7, 0.5), [12.3])), ), ) context = ExpressionContext_v01(cfg, ns=ns_offeq) a.build(context) ns_offeq.printparameters(labels=True) fig, ax = plt.subplots() for iso in indices[0][2]: corrected_spectra = context.outputs.offeq_correction[iso]['DB1'].data() initial_spectra = context.outputs.anuspec[iso].data() ax.plot(Enu.single().data(), (corrected_spectra - initial_spectra) / initial_spectra, label=iso) ax.set_title("Offequilibrium corrected spectra") ax.legend(loc='best') ax.grid() ax.set_xlabel("Antineutrino energy, MeV") ax.set_ylabel("(Corrected - nominal) / nominal") suffix = 'offeq' path = os.path.join(str(tmp_path), suffix + '.png') savefig(path.replace('.png', '.pdf'), dpi=300) allure_attach_file(path) path = os.path.join(str(tmp_path), suffix + '_graph.png') savegraph(context.outputs.offeq_correction['U235']['DB1'], path) allure_attach_file(path)
def plot_boxes(dataall=None, title=None, scale=False, low=None, high=None, output=None, suffix=()): if dataall is None: assert low is not None assert high is not None data = None else: low, high, data = dataall['scan'] split = dataall['split'] xlabel = 'E low' ylabel = 'E high' eminimal = low[0] emaximal = high[-1] if scale: fwd_x, inv_x = MakeEqualScale(low) fwd_y, inv_y = MakeEqualScale(high) # Prepare data L, H = np.meshgrid(low, high, indexing='ij') W = np.around(H[1:, 1:] - L[:-1, :-1], 6) Center = np.around(H[1:, 1:] + L[:-1, :-1], 6) * 0.5 emin, emax, ew = 1.5, 4.0, 0.5 gridopts = dict(color='red', alpha=0.4, linestyle='dashed') # # Make figure # fig = plt.figure(figsize=(8, 6)) ax = plt.subplot(111, xlabel=xlabel, ylabel=ylabel, title='Energy limits map: ' + title) if scale: ax.set_xscale('function', functions=(fwd_x, inv_x)) ax.set_yscale('function', functions=(fwd_y, inv_y)) ax.xaxis.set_tick_params(top=True, labeltop=True, which='both') ax.set_xticks(low) ax.set_yticks(high) # # Plot stuff # zorder = 10 if data is None: # Helper rectangle rpos = (0.60, 0.05) rwidth, rheight = 0.1, 0.1 hlen = rwidth * 0.1 hwidth = hlen rcenter_x = rpos[0] + rwidth * 0.5 rcenter_y = rpos[1] + rheight * 0.5 rect_example = Rectangle(rpos, rwidth, rheight, color='white', zorder=zorder, transform=ax.transAxes) ax.add_artist(rect_example) # Arrows opts = dict(zorder=zorder + 2, head_width=hwidth, head_length=hlen, ec='black', fc='black', transform=ax.transAxes) ax.arrow(rpos[0], rcenter_y, rwidth * 0.4 - hlen, 0.0, **opts) ax.arrow(rcenter_x, rcenter_y + rheight * 0.1, 0.0, rheight * 0.4 - hlen, **opts) # # # Highlight sides opts = dict(linewidth=2.5, color='black', zorder=zorder + 1, transform=ax.transAxes, head_width=0.0, head_length=0.0) ax.arrow(rpos[0], rpos[1], 0.0, rheight, **opts) ax.arrow(rpos[0], rpos[1] + rheight, rwidth, 0.0, **opts) if data is None: # Total rect_total = Rectangle((eminimal, 10.0), 0.3, 2.0, color='magenta', zorder=zorder) ax.add_artist(rect_total) # Minimal if data is None: rect_min = Rectangle((emin, emax - ew), ew, ew, color='green', zorder=zorder) ax.add_artist(rect_min) goodlineopts = dict(zorder=zorder + 1, linestyle='--', color='yellow', alpha=0.5) goodline = ax.vlines(emin, emax, emaximal, **goodlineopts) ax.hlines(emax, eminimal, emin, **goodlineopts) else: # rect_min = Rectangle((emin, emax-ew), ew, ew, fc='none', ec='yellow', linestyle='dashed', zorder=zorder) pass if data is None: # # Legend # rect_forbidden = Rectangle((emin, emax - ew), ew, ew, color=cm(0)) rect_bad = Rectangle((emin, emax - ew), ew, ew, color=cm(1)) rect_acceptable = Rectangle((emin, emax - ew), ew, ew, color=cm(2)) handles = [ rect_example, rect_total, rect_min, rect_acceptable, rect_forbidden, rect_bad ] labels = [ 'Example', 'Total: {:.1f}$-${:.0f}'.format(eminimal, 12.0), 'Minimal: {:.1f}$-${:.0f}'.format(emin, emax), 'Acceptable', 'Acceptable', 'Forbidden', 'Bad' ] ax.legend(handles, labels, loc='lower right') # # Example plot # data = np.ones_like(L, dtype='i') * 2.0 data[L > emin] = 1 data[H < emax - ew] = 1 data[L > H] = 0 data = data[:-1, :-1] ax.pcolormesh(L, H, data, vmin=0.1, cmap=cm) ax.grid(**gridopts) return # # Data # Data = np.ma.array(np.zeros_like(L, dtype='d'), mask=np.zeros_like(L, dtype='i'))[:-1, :-1] for emin, emax, fun, success in data: imin = np.searchsorted(low, emin) imax = np.searchsorted(high, emax) - 1 Data[imin, imax] = fun Data.mask[imin, imax] = not success if fun > 12.5: # Data[imin, imax] = -1 print('Strange value below:') print('{index1:02d} {emin} in ({emin1}, {emin2})' '\t' '{index2:02d} {emax} in ({emax1}, {emax2})' '\t' '{fun}'.format( index1=imin, emin=emin, emin1=low[imin] if len(low) > imin else -1, emin2=low[imin + 1] if len(low) - 1 > imin else -1, index2=imax, emax=emax, emax1=high[imax] if len(high) > imax else -1, emax2=high[imax + 1] if len(high) - 1 > imax else -1, fun=fun)) c = ax.pcolormesh(L, H, Data, vmin=0.1) add_colorbar(c, label=dchi2) if scale: show_values(c, fontsize='x-small') ax.grid(**gridopts) lines2opts = dict(color='red', linewidth=1, linestyle='-') ax.axvline(low[1], **lines2opts) ax.axhline(high[-2], **lines2opts) axd = ax ax.set_xlim(right=3.4) savefig(output, suffix=suffix + ('zoom', )) if not scale: return axd, None, None # # Test data # # fig = plt.figure() # ax = plt.subplot(111, xlabel=xlabel, ylabel=ylabel, title='Range, MeV') # ax.minorticks_on() # ax.grid() # ax.set_xscale('function', functions=(fwd_x, inv_x)) # ax.set_yscale('function', functions=(fwd_y, inv_y)) # ax.set_xticks(low) # ax.set_yticks(high) # c = ax.pcolormesh(L, H, W) # add_colorbar(c) # show_values(c, fontsize='x-small') # # Combination # fig = plt.figure() axc = plt.subplot(111, xlabel='E split, MeV', ylabel=dchi2, title='Split test: ' + title) axc.xaxis.set_tick_params(top=True, labeltop=True, which='both') axc.minorticks_on() axc.grid() left_x, left_y = split['left'] right_x, right_y = split['right'] left_x = np.around(left_x, 6) axc.plot(left_x, left_y, label='left: [0.7, x] MeV') axc.plot(right_x, right_y, label='right: [x, 12] MeV') idx_right = np.in1d(right_x, left_x) idx_left = np.in1d(left_x, right_x) both_x = left_x[idx_left] both_y = left_y[idx_left] + right_y[idx_right] axc.plot(both_x, both_y, label='combined: uncorrelated sum') idx = np.argmin(both_y) worst_split_low_idx = np.argwhere(low == both_x[idx])[0, 0] worst_split_high_idx = np.argwhere(high == both_x[idx])[0, 0] - 1 worst_dchi2 = both_x[idx] worst_split = both_y[idx] axc.axvline(both_x[idx], linestyle='--', alpha=0.5, label='worst split: {}={:.2f} at {} MeV'.format( dchi2, worst_split, worst_dchi2)) axc.legend() savefig(output, suffix=suffix + ('split', )) # # Moving window # fig = plt.figure() ax = plt.subplot(111, xlabel='Window center', ylabel=dchi2, title='Moving window: ' + title) ax.xaxis.set_tick_params(top=True, labeltop=True, which='both') ax.minorticks_on() ax.grid() plt.subplots_adjust(right=0.81) Wunique = np.unique(W) maxpath_x = [] maxpath_y = [] maxpath_fun = [] counter = 0 for w in Wunique: if w <= 0.0: continue mask = W == w x = Center[mask] y = Data[mask] imax = np.argmax(y) xmax, ymax = x[imax], y[imax] if mask.sum() >= 3: maxpath_fun.append(ymax) if mask.sum() >= 3: color = ax.plot(x, y, label=str(w))[0].get_color() # if mask.sum()>=4: # eopts=dict(alpha=0.4, linewidth=3) # else: eopts = dict(alpha=1, linewidth=0.5, capsize=3) ax.errorbar([xmax], [ymax], xerr=w * 0.5, fmt='o-', markerfacecolor='none', color=color, **eopts) counter += 1 if counter % 5 == 0: handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], title='Width:', bbox_to_anchor=(1.0, 1.15), loc='upper left', labelspacing=0.1) savefig(output, suffix=suffix + ('window', str(counter))) if counter == 8: ax.axhline(worst_dchi2, linestyle='--', label='Min split', alpha=0.6, color='blue') ax.axhline(np.max(Data), linestyle='--', label='Full') handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], title='Width:', bbox_to_anchor=(1.0, 1.15), loc='upper left', labelspacing=0.1) savefig(output, suffix=suffix + ('window', )) # # Max path on the main plot # plt.sca(axd) maxpath_fun = sorted(maxpath_fun) fun_prev = None while True: fun = maxpath_fun[-1] mask = np.isclose(Data, fun) idxs = np.argwhere(mask) cmpto = [] for idx in idxs: if idx[0] > 0: app = Data[idx[0] - 1, idx[1]] if app != fun and app != fun_prev: cmpto.append(app) if idx[1] < Data.shape[1] - 1: app = Data[idx[0], idx[1] + 1] if app != fun and app != fun_prev: cmpto.append(app) if not cmpto: break maxpath_fun.append(max(cmpto)) fun_prev = fun Lcenter = 0.85 * L[1:, 1:] + 0.15 * L[:-1, 1:] Hcenter = 0.80 * H[:-1, 1:] + 0.20 * H[:-1, :-1] for fun in maxpath_fun: mask = np.isclose(Data, fun) maxpath_x.append(Lcenter[mask][0]) maxpath_y.append(Hcenter[mask][0]) # Max path xworst = [Lcenter[0, 0], Lcenter[worst_split_low_idx, -1]] yworst = [Hcenter[0, worst_split_high_idx], Hcenter[0, -1]] equiv_idx = np.argmin((Data - worst_dchi2)**2) equiv_idx = np.unravel_index(equiv_idx, Data.shape) equiv_idx1 = np.argmin((maxpath_fun - worst_dchi2)**2) x = [Lcenter[equiv_idx[0], equiv_idx[1]], maxpath_x[equiv_idx1]] y = [Hcenter[equiv_idx[0], equiv_idx[1]], maxpath_y[equiv_idx1]] # plot axd.plot(xworst, yworst, 'o', color='cyan', markerfacecolor='none', label='Worst split') axd.legend(bbox_to_anchor=(1.2, -0.15), loc='lower right', ncol=3, fontsize='small', numpoints=2) savefig(output, suffix=suffix + ('zoom_2', )) axd.plot(maxpath_x, maxpath_y, 'o', color='red', markerfacecolor='none', label='Moving window maximum position') axd.plot(x, y, 'o', color='red', alpha=0.8, markerfacecolor='red', label='Closest to worst split') axd.legend(bbox_to_anchor=(1.2, -0.15), loc='lower right', ncol=3, fontsize='small', numpoints=2) savefig(output, suffix=suffix + ('zoom_3', ))
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()