32from sklearn.neural_network
import MLPClassifier
36ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.WARNING)
38n_samples_morph = 10000
40n_samples_train = n_samples_morph * n_bins
44def morphing(setting, n_dimensions):
47 binning = [ROOT.RooBinning(n_bins, 0.0, n_bins - 1.0)
for dim
in range(n_dimensions)]
48 grid = ROOT.RooMomentMorphFuncND.Grid(*binning)
55 mu_helps = [ROOT.RooRealVar(f
"mu{i}", f
"mu{i}", 0.0)
for i
in range(n_dimensions)]
59 for j
in range(n_dimensions):
60 gaussian = ROOT.RooGaussian(f
"gdim{j}", f
"gdim{j}", x_vars[j], mu_helps[j], sigmas[j])
61 gaussians.append(gaussian)
64 gauss_product = ROOT.RooProdPdf(
"gauss_product",
"gauss_product", ROOT.RooArgList(*gaussians))
69 for idx, nd_idx
in enumerate(itertools.product(range(n_bins), repeat=n_dimensions)):
70 for i_dim
in range(n_dimensions):
71 mu_helps[i_dim].setVal(nd_idx[i_dim])
74 hist = gauss_product.generateBinned(ROOT.RooArgSet(*x_vars), n_samples_morph)
77 for i_bin
in range(hist.numEntries()):
78 hist.add(hist.get(i_bin), 1.0)
80 templates[nd_idx] = ROOT.RooHistPdf(f
"histpdf{idx}", f
"histpdf{idx}", ROOT.RooArgSet(*x_vars), hist, 1)
83 grid.addPdf(templates[nd_idx], *nd_idx)
86 morph_func = ROOT.RooMomentMorphFuncND(
"morph_func",
"morph_func", [*mu_vars], [*x_vars], grid, setting)
87 morph_func.setPdfMode(
True)
88 morph = ROOT.RooWrapperPdf(
"morph",
"morph", morph_func,
True)
103mu_observed = [2.5, 2.0]
110 def __init__(self, ws, n_vars):
112 self.classifier = MLPClassifier(hidden_layer_sizes=(20, 20), max_iter=1000, random_state=42)
113 self.data_model =
None
119 self._training_mus =
None
120 self._reference_mu =
None
123 def model_data(self, model, x_vars, mu_vars, n_samples):
126 ws[model].generate([ws[x]
for x
in x_vars] + [ws[mu]
for mu
in mu_vars], n_samples).to_numpy()
129 self._training_mus = np.array([samples_gaussian[mu]
for mu
in mu_vars]).T
130 data_test_model = np.array([samples_gaussian[x]
for x
in x_vars]).T
132 self.data_model = data_test_model.reshape(-1, self.n_vars)
135 def reference_data(self, model, x_vars, mu_vars, n_samples, help_model):
138 samples_uniform = ws[model].generate([ws[x]
for x
in x_vars], n_samples)
139 data_reference_model = np.array(
140 [samples_uniform.get(i).getRealValue(x)
for x
in x_vars
for i
in range(samples_uniform.numEntries())]
143 self.data_ref = data_reference_model.reshape(-1, self.n_vars)
145 samples_mu = ws[help_model].generate([ws[mu]
for mu
in mu_vars], n_samples)
147 [samples_mu.get(i).getRealValue(mu)
for mu
in mu_vars
for i
in range(samples_mu.numEntries())]
150 self._reference_mu = mu_data.reshape(-1, self.n_vars)
153 def preprocessing(self):
154 thetas = np.concatenate((self._training_mus, self._reference_mu))
155 X = np.concatenate([self.data_model, self.data_ref])
157 self.y_train = np.concatenate([np.ones(
len(self.data_model)), np.zeros(
len(self.data_ref))])
158 self.X_train = np.concatenate([X, thetas], axis=1)
161 def train_classifier(self):
162 self.classifier.fit(self.X_train, self.y_train)
166def build_ws(mu_observed):
167 n_vars =
len(mu_observed)
168 x_vars = [ROOT.RooRealVar(f
"x{i}", f
"x{i}", -5, 15)
for i
in range(n_vars)]
169 mu_vars = [ROOT.RooRealVar(f
"mu{i}", f
"mu{i}", mu_observed[i], 0, 4)
for i
in range(n_vars)]
170 gaussians = [ROOT.RooGaussian(f
"gauss{i}", f
"gauss{i}", x_vars[i], mu_vars[i], sigmas[i])
for i
in range(n_vars)]
171 uniforms = [ROOT.RooUniform(f
"uniform{i}", f
"uniform{i}", x_vars[i])
for i
in range(n_vars)]
172 uniforms_help = [ROOT.RooUniform(f
"uniformh{i}", f
"uniformh{i}", mu_vars[i])
for i
in range(n_vars)]
174 gauss = ROOT.RooProdPdf(
"gauss",
"gauss", ROOT.RooArgList(*gaussians))
175 uniform = ROOT.RooProdPdf(
"uniform",
"uniform", ROOT.RooArgList(*uniforms))
176 uniform_help = ROOT.RooProdPdf(
"uniform_help",
"uniform_help", ROOT.RooArgList(*uniforms_help))
177 obs_data = gauss.generate(ROOT.RooArgSet(*x_vars), n_samples_morph)
178 obs_data.SetName(
"obs_data")
181 ws = ROOT.RooWorkspace()
186 ws.Import(uniform_help)
193ws = build_ws(mu_observed)
197x_vars = [ws[f
"x{i}"]
for i
in range(
len(mu_observed))]
198mu_vars = [ws[f
"mu{i}"]
for i
in range(
len(mu_observed))]
201morphing(ROOT.RooMomentMorphFuncND.Linear,
len(mu_observed))
205nll_morph = ws[
"morph"].createNLL(ws[
"obs_data"], EvalBackend=
"legacy")
208model = SBI(ws,
len(mu_observed))
211model.model_data(
"gauss", [x.GetName()
for x
in x_vars], [mu.GetName()
for mu
in mu_vars], n_samples_train)
213 "uniform", [x.GetName()
for x
in x_vars], [mu.GetName()
for mu
in mu_vars], n_samples_train,
"uniform_help"
218model.train_classifier()
223def learned_likelihood_ratio(*args):
224 n = max(*(
len(a)
for a
in args))
225 X = np.zeros((n,
len(args)))
226 for i
in range(
len(args)):
228 prob = sbi_model.classifier.predict_proba(X)[:, 1]
229 return prob / (1.0 - prob)
233combined_vars = ROOT.RooArgList()
234for var
in x_vars + mu_vars:
235 combined_vars.add(var)
238lhr_learned = ROOT.RooFit.bindFunction(
"MyBinFunc", learned_likelihood_ratio, combined_vars)
241lhr_calc = ROOT.RooFormulaVar(
"lhr_calc",
"x[0] / x[1]", [ws[
"gauss"], ws[
"uniform"]])
244nll_gauss = ws[
"gauss"].createNLL(ws[
"obs_data"])
247pdf_learned = ROOT.RooWrapperPdf(
"learned_pdf",
"learned_pdf", lhr_learned,
True)
249nllr_learned = pdf_learned.createNLL(ws[
"obs_data"])
252frame1 = mu_vars[0].frame(
253 Title=
"NLL of SBI vs. Morphing;#mu_{1};NLL",
254 Range=(mu_observed[0] - 1, mu_observed[0] + 1),
256nll_gauss.plotOn(frame1, ShiftToZero=
True, LineColor=
"kP6Blue+1", Name=
"gauss")
257ROOT.RooAbsReal.setEvalErrorLoggingMode(
"Ignore")
258nll_morph.plotOn(frame1, ShiftToZero=
True, LineColor=
"kP6Blue+2", Name=
"morph")
259ROOT.RooAbsReal.setEvalErrorLoggingMode(
"PrintErrors")
260nllr_learned.plotOn(frame1, LineColor=
"kP6Blue", ShiftToZero=
True, Name=
"learned")
264ROOT.gInterpreter.Declare(
266RooAbsArg &my_deref(std::unique_ptr<RooAbsArg> const& ptr) { return *ptr; }
271norm_set = ROOT.RooArgSet(x_vars)
272lhr_calc_final_ptr = ROOT.RooFit.Detail.compileForNormSet(lhr_calc, norm_set)
273lhr_calc_final = ROOT.my_deref(lhr_calc_final_ptr)
274lhr_calc_final.recursiveRedirectServers(norm_set)
277frame2 = x_vars[0].frame(Title=
"Likelihood ratio r(x_{1}|#mu_{1}=2.5);x_{1};p_{gauss}/p_{uniform}")
278lhr_learned.plotOn(frame2, LineColor=
"kP6Blue", Name=
"learned_ratio")
279lhr_calc_final.plotOn(frame2, LineColor=
"kP6Blue+1", Name=
"exact")
284c = ROOT.TCanvas(
"",
"", 1200
if single_canvas
else 600, 600)
288 ROOT.gPad.SetLeftMargin(0.15)
289 frame1.GetYaxis().SetTitleOffset(1.8)
292legend1 = ROOT.TLegend(0.43, 0.63, 0.8, 0.87)
293legend1.SetFillColor(ROOT.kWhite)
294legend1.SetLineColor(ROOT.kWhite)
295legend1.SetTextSize(0.04)
296legend1.AddEntry(
"learned",
"learned (SBI)",
"L")
297legend1.AddEntry(
"gauss",
"true NLL",
"L")
298legend1.AddEntry(
"morphed",
"moment morphing",
"L")
303 ROOT.gPad.SetLeftMargin(0.15)
304 frame2.GetYaxis().SetTitleOffset(1.8)
306 c.SaveAs(
"rf617_plot_1.png")
307 c = ROOT.TCanvas(
"",
"", 600, 600)
311legend2 = ROOT.TLegend(0.53, 0.73, 0.87, 0.87)
312legend2.SetFillColor(ROOT.kWhite)
313legend2.SetLineColor(ROOT.kWhite)
314legend2.SetTextSize(0.04)
315legend2.AddEntry(
"learned_ratio",
"learned (SBI)",
"L")
316legend2.AddEntry(
"exact",
"true ratio",
"L")
320 c.SaveAs(
"rf617_plot_2.png")
324for nll
in [nll_gauss, nllr_learned, nll_morph]:
325 minimizer = ROOT.RooMinimizer(nll)
326 minimizer.setErrorLevel(0.5)
327 minimizer.setPrintLevel(-1)
328 minimizer.minimize(
"Minuit2")
329 result = minimizer.save()
335del 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