38from sklearn.neural_network
import MLPClassifier
44ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.WARNING)
48def morphing(setting, workspace):
50 grid = ROOT.RooMomentMorphFuncND.Grid(ROOT.RooBinning(4, 0.0, 4.0))
56 for i
in range(n_grid):
58 mu_help = ROOT.RooRealVar(f
"mu{i}", f
"mu{i}", i)
59 help = ROOT.RooGaussian(f
"g{i}", f
"g{i}", x_var, mu_help, sigma)
60 workspace.Import(help, Silence=
True)
63 hist = workspace[f
"g{i}"].generateBinned([x_var], n_samples)
66 for i_bin
in range(hist.numEntries()):
67 hist.add(hist.get(i_bin), 1.0)
70 workspace.Import(ROOT.RooHistPdf(f
"histpdf{i}", f
"histpdf{i}", [x_var], hist, 1), Silence=
True)
73 grid.addPdf(workspace[f
"histpdf{i}"], i)
76 morph_func = ROOT.RooMomentMorphFuncND(
"morph_func",
"morph_func", [mu_var], [x_var], grid, setting)
77 morph = ROOT.RooWrapperPdf(
"morph",
"morph", morph_func,
True)
78 workspace.Import(morph, Silence=
True)
93 def __init__(self, workspace):
95 self.classifier = MLPClassifier(hidden_layer_sizes=(20, 20), max_iter=1000, random_state=42)
96 self.data_model =
None
100 self.workspace = workspace
103 def model_data(self, model, x, mu, n_samples):
106 samples_gaussian = ws[model].generate([ws[x], ws[mu]], n_samples).to_numpy()
107 self._training_mus = samples_gaussian[mu]
108 data_test_model.extend(samples_gaussian[x])
110 self.data_model = np.array(data_test_model).reshape(-1, 1)
113 def reference_data(self, model, x, n_samples):
116 samples_uniform = ws[model].generate(ws[x], n_samples)
117 data_reference_model = np.array(
118 [samples_uniform.get(i).getRealValue(
"x")
for i
in range(samples_uniform.numEntries())]
120 self.data_ref = data_reference_model.reshape(-1, 1)
123 def preprocessing(self):
124 thetas_model = self._training_mus.reshape(-1, 1)
125 thetas_reference = self._training_mus.reshape(-1, 1)
126 thetas = np.concatenate((thetas_model, thetas_reference), axis=0)
127 X = np.concatenate([self.data_model, self.data_ref])
128 self.y_train = np.concatenate([np.ones(len(self.data_model)), np.zeros(len(self.data_ref))])
129 self.X_train = np.concatenate([X, thetas], axis=1)
132 def train_classifier(self):
133 self.classifier.fit(self.X_train, self.y_train)
137n_samples_train = n_samples * 5
141def build_ws(mu_observed, sigma):
143 ws = ROOT.RooWorkspace()
144 ws.factory(f
"Gaussian::gauss(x[-5,15], mu[0,4], {sigma})")
145 ws.factory(
"Uniform::uniform(x)")
146 ws[
"mu"].setVal(mu_observed)
148 obs_data = ws[
"gauss"].generate(ws[
"x"], 1000)
149 obs_data.SetName(
"obs_data")
150 ws.Import(obs_data, Silence=
True)
158workspace = build_ws(mu_observed, sigma)
159x_var = workspace[
"x"]
160mu_var = workspace[
"mu"]
161gauss = workspace[
"gauss"]
162uniform = workspace[
"uniform"]
163obs_data = workspace[
"obs_data"]
166model = SBI(workspace)
167model.model_data(
"gauss",
"x",
"mu", n_samples_train)
168model.reference_data(
"uniform",
"x", n_samples_train)
170model.train_classifier()
175def learned_likelihood_ratio(x, mu):
176 n = max(len(x), len(mu))
180 prob = sbi_model.classifier.predict_proba(X)[:, 1]
181 return prob / (1 - prob)
185llhr_learned = ROOT.RooFit.bindFunction(
"MyBinFunc", learned_likelihood_ratio, x_var, mu_var)
188llhr_calc = ROOT.RooFormulaVar(
"llhr_calc",
"x[0] / x[1]", [gauss, uniform])
191nll_gauss = gauss.createNLL(obs_data)
192ROOT.SetOwnership(nll_gauss,
True)
195pdf_learned = ROOT.RooWrapperPdf(
"learned_pdf",
"learned_pdf", llhr_learned,
True)
197nllr_learned = pdf_learned.createNLL(obs_data)
198ROOT.SetOwnership(nllr_learned,
True)
201morphing(ROOT.RooMomentMorphFuncND.Linear, workspace)
202nll_morph = workspace[
"morph"].createNLL(obs_data)
203ROOT.SetOwnership(nll_morph,
True)
206frame1 = mu_var.frame(Title=
"NLL of SBI vs. Morphing;mu;NLL", Range=(2.2, 2.8))
207nllr_learned.plotOn(frame1, LineColor=
"kP6Blue", ShiftToZero=
True, Name=
"learned")
208nll_gauss.plotOn(frame1, LineColor=
"kP6Yellow", ShiftToZero=
True, Name=
"gauss")
209ROOT.RooAbsReal.setEvalErrorLoggingMode(
"Ignore")
210nll_morph.plotOn(frame1, LineColor=
"kP6Red", ShiftToZero=
True, Name=
"morphed")
211ROOT.RooAbsReal.setEvalErrorLoggingMode(
"PrintErrors")
214frame2 = x_var.frame(Title=
"Likelihood ratio r(x|#mu=2.5);x;p_{gauss}/p_{uniform}")
215llhr_learned.plotOn(frame2, LineColor=
"kP6Blue", Name=
"learned_ratio")
216llhr_calc.plotOn(frame2, LineColor=
"kP6Yellow", Name=
"exact")
221c = ROOT.TCanvas(
"",
"", 1200
if single_canvas
else 600, 600)
225 ROOT.gPad.SetLeftMargin(0.15)
226 frame1.GetYaxis().SetTitleOffset(1.8)
229legend1 = ROOT.TLegend(0.43, 0.63, 0.8, 0.87)
230legend1.SetFillColor(
"kWhite")
231legend1.SetLineColor(
"kWhite")
232legend1.SetTextSize(0.04)
233legend1.AddEntry(
"learned",
"learned (SBI)",
"L")
234legend1.AddEntry(
"gauss",
"true NLL",
"L")
235legend1.AddEntry(
"morphed",
"moment morphing",
"L")
240 ROOT.gPad.SetLeftMargin(0.15)
241 frame2.GetYaxis().SetTitleOffset(1.8)
243 c.SaveAs(
"rf615_plot_1.png")
244 c = ROOT.TCanvas(
"",
"", 600, 600)
248legend2 = ROOT.TLegend(0.53, 0.73, 0.87, 0.87)
249legend2.SetFillColor(
"kWhite")
250legend2.SetLineColor(
"kWhite")
251legend2.SetTextSize(0.04)
252legend2.AddEntry(
"learned_ratio",
"learned (SBI)",
"L")
253legend2.AddEntry(
"exact",
"true ratio",
"L")
257 c.SaveAs(
"rf615_plot_2.png")
260for nll
in [nll_gauss, nllr_learned, nll_morph]:
261 minimizer = ROOT.RooMinimizer(nll)
262 minimizer.setErrorLevel(0.5)
263 minimizer.setPrintLevel(-1)
264 minimizer.minimize(
"Minuit2")
265 result = minimizer.save()
266 ROOT.SetOwnership(result,
True)