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)
81 templates[nd_idx]._data_hist = hist
84 grid.addPdf(templates[nd_idx], *nd_idx)
87 morph_func = ROOT.RooMomentMorphFuncND(
"morph_func",
"morph_func", [*mu_vars], [*x_vars], grid, setting)
88 morph_func.setPdfMode(
True)
89 morph = ROOT.RooWrapperPdf(
"morph",
"morph", morph_func,
True)
104mu_observed = [2.5, 2.0]
111 def __init__(self, ws, n_vars):
113 self.classifier = MLPClassifier(hidden_layer_sizes=(20, 20), max_iter=1000, random_state=42)
114 self.data_model =
None
120 self._training_mus =
None
121 self._reference_mu =
None
124 def model_data(self, model, x_vars, mu_vars, n_samples):
127 ws[model].generate([ws[x]
for x
in x_vars] + [ws[mu]
for mu
in mu_vars], n_samples).to_numpy()
130 self._training_mus = np.array([samples_gaussian[mu]
for mu
in mu_vars]).T
131 data_test_model = np.array([samples_gaussian[x]
for x
in x_vars]).T
133 self.data_model = data_test_model.reshape(-1, self.n_vars)
136 def reference_data(self, model, x_vars, mu_vars, n_samples, help_model):
139 samples_uniform = ws[model].generate([ws[x]
for x
in x_vars], n_samples)
140 data_reference_model = np.array(
141 [samples_uniform.get(i).getRealValue(x)
for x
in x_vars
for i
in range(samples_uniform.numEntries())]
144 self.data_ref = data_reference_model.reshape(-1, self.n_vars)
146 samples_mu = ws[help_model].generate([ws[mu]
for mu
in mu_vars], n_samples)
148 [samples_mu.get(i).getRealValue(mu)
for mu
in mu_vars
for i
in range(samples_mu.numEntries())]
151 self._reference_mu = mu_data.reshape(-1, self.n_vars)
154 def preprocessing(self):
155 thetas = np.concatenate((self._training_mus, self._reference_mu))
156 X = np.concatenate([self.data_model, self.data_ref])
158 self.y_train = np.concatenate([np.ones(len(self.data_model)), np.zeros(len(self.data_ref))])
159 self.X_train = np.concatenate([X, thetas], axis=1)
162 def train_classifier(self):
163 self.classifier.fit(self.X_train, self.y_train)
167def build_ws(mu_observed):
168 n_vars = len(mu_observed)
169 x_vars = [ROOT.RooRealVar(f
"x{i}", f
"x{i}", -5, 15)
for i
in range(n_vars)]
170 mu_vars = [ROOT.RooRealVar(f
"mu{i}", f
"mu{i}", mu_observed[i], 0, 4)
for i
in range(n_vars)]
171 gaussians = [ROOT.RooGaussian(f
"gauss{i}", f
"gauss{i}", x_vars[i], mu_vars[i], sigmas[i])
for i
in range(n_vars)]
172 uniforms = [ROOT.RooUniform(f
"uniform{i}", f
"uniform{i}", x_vars[i])
for i
in range(n_vars)]
173 uniforms_help = [ROOT.RooUniform(f
"uniformh{i}", f
"uniformh{i}", mu_vars[i])
for i
in range(n_vars)]
175 gauss = ROOT.RooProdPdf(
"gauss",
"gauss", ROOT.RooArgList(*gaussians))
176 uniform = ROOT.RooProdPdf(
"uniform",
"uniform", ROOT.RooArgList(*uniforms))
177 uniform_help = ROOT.RooProdPdf(
"uniform_help",
"uniform_help", ROOT.RooArgList(*uniforms_help))
178 obs_data = gauss.generate(ROOT.RooArgSet(*x_vars), n_samples_morph)
179 obs_data.SetName(
"obs_data")
182 ws = ROOT.RooWorkspace()
187 ws.Import(uniform_help)
194ws = build_ws(mu_observed)
198x_vars = [ws[f
"x{i}"]
for i
in range(len(mu_observed))]
199mu_vars = [ws[f
"mu{i}"]
for i
in range(len(mu_observed))]
202morphing(ROOT.RooMomentMorphFuncND.Linear, len(mu_observed))
206nll_morph = ws[
"morph"].createNLL(ws[
"obs_data"], EvalBackend=
"legacy")
209model = SBI(ws, len(mu_observed))
212model.model_data(
"gauss", [x.GetName()
for x
in x_vars], [mu.GetName()
for mu
in mu_vars], n_samples_train)
214 "uniform", [x.GetName()
for x
in x_vars], [mu.GetName()
for mu
in mu_vars], n_samples_train,
"uniform_help"
219model.train_classifier()
224def learned_likelihood_ratio(*args):
225 n = max(*(len(a)
for a
in args))
226 X = np.zeros((n, len(args)))
227 for i
in range(len(args)):
229 prob = sbi_model.classifier.predict_proba(X)[:, 1]
230 return prob / (1.0 - prob)
234combined_vars = ROOT.RooArgList()
235for var
in x_vars + mu_vars:
236 combined_vars.add(var)
239lhr_learned = ROOT.RooFit.bindFunction(
"MyBinFunc", learned_likelihood_ratio, combined_vars)
242lhr_calc = ROOT.RooFormulaVar(
"lhr_calc",
"x[0] / x[1]", [ws[
"gauss"], ws[
"uniform"]])
245nll_gauss = ws[
"gauss"].createNLL(ws[
"obs_data"])
248pdf_learned = ROOT.RooWrapperPdf(
"learned_pdf",
"learned_pdf", lhr_learned,
True)
250nllr_learned = pdf_learned.createNLL(ws[
"obs_data"])
253frame1 = mu_vars[0].frame(
254 Title=
"NLL of SBI vs. Morphing;#mu_{1};NLL",
255 Range=(mu_observed[0] - 1, mu_observed[0] + 1),
257nll_gauss.plotOn(frame1, ShiftToZero=
True, LineColor=
"kP6Yellow", Name=
"gauss")
258ROOT.RooAbsReal.setEvalErrorLoggingMode(
"Ignore")
259nll_morph.plotOn(frame1, ShiftToZero=
True, LineColor=
"kP6Red", Name=
"morph")
260ROOT.RooAbsReal.setEvalErrorLoggingMode(
"PrintErrors")
261nllr_learned.plotOn(frame1, LineColor=
"kP6Blue", ShiftToZero=
True, Name=
"learned")
265ROOT.gInterpreter.Declare(
267RooAbsArg &my_deref(std::unique_ptr<RooAbsArg> const& ptr) { return *ptr; }
272norm_set = ROOT.RooArgSet(x_vars)
273lhr_calc_final_ptr = ROOT.RooFit.Detail.compileForNormSet(lhr_calc, norm_set)
274lhr_calc_final = ROOT.my_deref(lhr_calc_final_ptr)
275lhr_calc_final.recursiveRedirectServers(norm_set)
278frame2 = x_vars[0].frame(Title=
"Likelihood ratio r(x_{1}|#mu_{1}=2.5);x_{1};p_{gauss}/p_{uniform}")
279lhr_learned.plotOn(frame2, LineColor=
"kP6Blue", Name=
"learned_ratio")
280lhr_calc_final.plotOn(frame2, LineColor=
"kP6Yellow", Name=
"exact")
285c = ROOT.TCanvas(
"",
"", 1200
if single_canvas
else 600, 600)
289 ROOT.gPad.SetLeftMargin(0.15)
290 frame1.GetYaxis().SetTitleOffset(1.8)
293legend1 = ROOT.TLegend(0.43, 0.63, 0.8, 0.87)
294legend1.SetFillColor(
"background")
295legend1.SetLineColor(
"background")
296legend1.SetTextSize(0.04)
297legend1.AddEntry(
"learned",
"learned (SBI)",
"L")
298legend1.AddEntry(
"gauss",
"true NLL",
"L")
299legend1.AddEntry(
"morphed",
"moment morphing",
"L")
304 ROOT.gPad.SetLeftMargin(0.15)
305 frame2.GetYaxis().SetTitleOffset(1.8)
307 c.SaveAs(
"rf617_plot_1.png")
308 c = ROOT.TCanvas(
"",
"", 600, 600)
312legend2 = ROOT.TLegend(0.53, 0.73, 0.87, 0.87)
313legend2.SetFillColor(
"background")
314legend2.SetLineColor(
"background")
315legend2.SetTextSize(0.04)
316legend2.AddEntry(
"learned_ratio",
"learned (SBI)",
"L")
317legend2.AddEntry(
"exact",
"true ratio",
"L")
321 c.SaveAs(
"rf617_plot_2.png")
325for nll
in [nll_gauss, nllr_learned, nll_morph]:
326 minimizer = ROOT.RooMinimizer(nll)
327 minimizer.setErrorLevel(0.5)
328 minimizer.setPrintLevel(-1)
329 minimizer.minimize(
"Minuit2")
330 result = minimizer.save()