38from sklearn.neural_network
import MLPClassifier
44ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.WARNING)
51 grid = ROOT.RooMomentMorphFuncND.Grid(ROOT.RooBinning(4, 0.0, 4.0))
57 for i
in range(n_grid):
59 mu_help = ROOT.RooRealVar(f
"mu{i}", f
"mu{i}", i)
60 help = ROOT.RooGaussian(f
"g{i}", f
"g{i}", x_var, mu_help, sigma)
61 workspace.Import(help, Silence=
True)
64 hist = workspace[f
"g{i}"].generateBinned([x_var], n_samples)
67 for i_bin
in range(hist.numEntries()):
68 hist.add(hist.get(i_bin), 1.0)
71 workspace.Import(ROOT.RooHistPdf(f
"histpdf{i}", f
"histpdf{i}", [x_var], hist, 1), Silence=
True)
74 grid.addPdf(workspace[f
"histpdf{i}"], i)
77 morph_func = ROOT.RooMomentMorphFuncND(
"morph_func",
"morph_func", [mu_var], [x_var], grid, setting)
78 morph = ROOT.RooWrapperPdf(
"morph",
"morph", morph_func,
True)
79 workspace.Import(morph, Silence=
True)
94 def __init__(self, workspace):
96 self.classifier = MLPClassifier(hidden_layer_sizes=(20, 20), max_iter=1000, random_state=42)
97 self.data_model =
None
101 self.workspace = workspace
104 def model_data(self, model, x, mu, n_samples):
107 samples_gaussian = ws[model].generate([ws[x], ws[mu]], n_samples).to_numpy()
108 self._training_mus = samples_gaussian[mu]
109 data_test_model.extend(samples_gaussian[x])
111 self.data_model = np.array(data_test_model).reshape(-1, 1)
114 def reference_data(self, model, x, n_samples):
117 samples_uniform = ws[model].generate(ws[x], n_samples)
118 data_reference_model = np.array(
119 [samples_uniform.get(i).getRealValue(
"x")
for i
in range(samples_uniform.numEntries())]
121 self.data_ref = data_reference_model.reshape(-1, 1)
124 def preprocessing(self):
125 thetas_model = self._training_mus.reshape(-1, 1)
126 thetas_reference = self._training_mus.reshape(-1, 1)
127 thetas = np.concatenate((thetas_model, thetas_reference), axis=0)
128 X = np.concatenate([self.data_model, self.data_ref])
129 self.y_train = np.concatenate([np.ones(
len(self.data_model)), np.zeros(
len(self.data_ref))])
130 self.X_train = np.concatenate([X, thetas], axis=1)
133 def train_classifier(self):
134 self.classifier.fit(self.X_train, self.y_train)
138n_samples_train = n_samples * 5
142def build_ws(mu_observed, sigma):
144 ws = ROOT.RooWorkspace()
145 ws.factory(f
"Gaussian::gauss(x[-5,15], mu[0,4], {sigma})")
146 ws.factory(
"Uniform::uniform(x)")
147 ws[
"mu"].setVal(mu_observed)
149 obs_data = ws[
"gauss"].generate(ws[
"x"], 1000)
150 obs_data.SetName(
"obs_data")
151 ws.Import(obs_data, Silence=
True)
159workspace = build_ws(mu_observed, sigma)
160x_var = workspace[
"x"]
161mu_var = workspace[
"mu"]
162gauss = workspace[
"gauss"]
163uniform = workspace[
"uniform"]
164obs_data = workspace[
"obs_data"]
167model = SBI(workspace)
168model.model_data(
"gauss",
"x",
"mu", n_samples_train)
169model.reference_data(
"uniform",
"x", n_samples_train)
171model.train_classifier()
176def learned_likelihood_ratio(x, mu):
181 prob = sbi_model.classifier.predict_proba(X)[:, 1]
182 return prob / (1 - prob)
186llhr_learned = ROOT.RooFit.bindFunction(
"MyBinFunc", learned_likelihood_ratio, x_var, mu_var)
189llhr_calc = ROOT.RooFormulaVar(
"llhr_calc",
"x[0] / x[1]", [gauss, uniform])
192nll_gauss = gauss.createNLL(obs_data)
193ROOT.SetOwnership(nll_gauss,
True)
196pdf_learned = ROOT.RooWrapperPdf(
"learned_pdf",
"learned_pdf", llhr_learned,
True)
198nllr_learned = pdf_learned.createNLL(obs_data)
199ROOT.SetOwnership(nllr_learned,
True)
202morphing(ROOT.RooMomentMorphFuncND.Linear)
203nll_morph = workspace[
"morph"].createNLL(obs_data)
204ROOT.SetOwnership(nll_morph,
True)
207frame1 = mu_var.frame(Title=
"NLL of SBI vs. Morphing;mu;NLL", Range=(2.2, 2.8))
208nllr_learned.plotOn(frame1, LineColor=
"kP6Blue", ShiftToZero=
True, Name=
"learned")
209nll_gauss.plotOn(frame1, LineColor=
"kP6Blue+1", ShiftToZero=
True, Name=
"gauss")
210ROOT.RooAbsReal.setEvalErrorLoggingMode(
"Ignore")
211nll_morph.plotOn(frame1, LineColor=
"kP6Blue+2", ShiftToZero=
True, Name=
"morphed")
212ROOT.RooAbsReal.setEvalErrorLoggingMode(
"PrintErrors")
215frame2 = x_var.frame(Title=
"Likelihood ratio r(x|#mu=2.5);x;p_{gauss}/p_{uniform}")
216llhr_learned.plotOn(frame2, LineColor=
"kP6Blue", Name=
"learned_ratio")
217llhr_calc.plotOn(frame2, LineColor=
"kP6Blue+1", Name=
"exact")
222c = ROOT.TCanvas(
"",
"", 1200
if single_canvas
else 600, 600)
226 ROOT.gPad.SetLeftMargin(0.15)
227 frame1.GetYaxis().SetTitleOffset(1.8)
230legend1 = ROOT.TLegend(0.43, 0.63, 0.8, 0.87)
231legend1.SetFillColor(ROOT.kWhite)
232legend1.SetLineColor(ROOT.kWhite)
233legend1.SetTextSize(0.04)
234legend1.AddEntry(
"learned",
"learned (SBI)",
"L")
235legend1.AddEntry(
"gauss",
"true NLL",
"L")
236legend1.AddEntry(
"morphed",
"moment morphing",
"L")
241 ROOT.gPad.SetLeftMargin(0.15)
242 frame2.GetYaxis().SetTitleOffset(1.8)
244 c.SaveAs(
"rf615_plot_1.png")
245 c = ROOT.TCanvas(
"",
"", 600, 600)
249legend2 = ROOT.TLegend(0.53, 0.73, 0.87, 0.87)
250legend2.SetFillColor(ROOT.kWhite)
251legend2.SetLineColor(ROOT.kWhite)
252legend2.SetTextSize(0.04)
253legend2.AddEntry(
"learned_ratio",
"learned (SBI)",
"L")
254legend2.AddEntry(
"exact",
"true ratio",
"L")
258 c.SaveAs(
"rf615_plot_2.png")
261for nll
in [nll_gauss, nllr_learned, nll_morph]:
262 minimizer = ROOT.RooMinimizer(nll)
263 minimizer.setErrorLevel(0.5)
264 minimizer.setPrintLevel(-1)
265 minimizer.minimize(
"Minuit2")
266 result = minimizer.save()
267 ROOT.SetOwnership(result,
True)
278del sys.modules[
"libROOTPythonizations"]
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len