Newer
Older
Master_thesis / data / CLs / finished / f1d1 / 2257334 / raremodel-nb.py
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3.  
  4. # # Import
  5.  
  6. # In[1]:
  7.  
  8.  
  9. import os
  10.  
  11. # os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
  12.  
  13. import numpy as np
  14. from pdg_const import pdg
  15. import matplotlib
  16. import matplotlib.pyplot as plt
  17. import pickle as pkl
  18. import sys
  19. import time
  20. from helperfunctions import display_time, prepare_plot
  21. import cmath as c
  22. import scipy.integrate as integrate
  23. from scipy.optimize import fminbound
  24. from array import array as arr
  25. import collections
  26. from itertools import compress
  27. import tensorflow as tf
  28. import zfit
  29. from zfit import ztf
  30. # from IPython.display import clear_output
  31. import os
  32. import tensorflow_probability as tfp
  33. tfd = tfp.distributions
  34.  
  35.  
  36. # In[2]:
  37.  
  38.  
  39. # chunksize = 10000
  40. # zfit.run.chunking.active = True
  41. # zfit.run.chunking.max_n_points = chunksize
  42.  
  43.  
  44. # # Build model and graphs
  45. # ## Create graphs
  46.  
  47. # In[ ]:
  48.  
  49.  
  50.  
  51.  
  52.  
  53. # In[3]:
  54.  
  55.  
  56. def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value
  57. #check if subscript is viable
  58.  
  59. if subscript != "0" and subscript != "+" and subscript != "T":
  60. raise ValueError('Wrong subscript entered, choose either 0, + or T')
  61.  
  62. #get constants
  63.  
  64. mK = ztf.constant(pdg['Ks_M'])
  65. mbstar0 = ztf.constant(pdg["mbstar0"])
  66. mbstar = ztf.constant(pdg["mbstar"])
  67.  
  68.  
  69. mmu = ztf.constant(pdg['muon_M'])
  70. mb = ztf.constant(pdg['bquark_M'])
  71. ms = ztf.constant(pdg['squark_M'])
  72. mB = ztf.constant(pdg['Bplus_M'])
  73.  
  74. #N comes from derivation in paper
  75.  
  76. N = 3
  77.  
  78. #some helperfunctions
  79.  
  80. tpos = (mB - mK)**2
  81. tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2
  82.  
  83. z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero)
  84. z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero)
  85. z = tf.divide(z_oben, z_unten)
  86.  
  87. #calculate f0
  88.  
  89. if subscript == "0":
  90. prefactor = 1/(1 - q2/(mbstar0**2))
  91. _sum = 0
  92. b0 = [b0_0, b0_1, b0_2]
  93.  
  94. for i in range(N):
  95. _sum += b0[i]*(tf.pow(z,i))
  96.  
  97. return ztf.to_complex(prefactor * _sum)
  98.  
  99. #calculate f+ or fT
  100.  
  101. else:
  102. prefactor = 1/(1 - q2/(mbstar**2))
  103. _sum = 0
  104.  
  105. if subscript == "T":
  106. bT = [bT_0, bT_1, bT_2]
  107. for i in range(N):
  108. _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N))
  109. else:
  110. bplus = [bplus_0, bplus_1, bplus_2]
  111. for i in range(N):
  112. _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N))
  113.  
  114. return ztf.to_complex(prefactor * _sum)
  115.  
  116. def resonance(q, _mass, width, phase, scale):
  117.  
  118. q2 = tf.pow(q, 2)
  119.  
  120. mmu = ztf.constant(pdg['muon_M'])
  121.  
  122. p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2))
  123.  
  124. p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2)
  125.  
  126. gamma_j = tf.divide(p, q) * _mass * width / p0
  127.  
  128. #Calculate the resonance
  129.  
  130. _top = tf.complex(_mass * width, ztf.constant(0.0))
  131.  
  132. _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j)
  133.  
  134. com = _top/_bottom
  135.  
  136. #Rotate by the phase
  137.  
  138. r = ztf.to_complex(scale*tf.abs(com))
  139.  
  140. _phase = tf.angle(com)
  141.  
  142. _phase += phase
  143.  
  144. com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase))
  145.  
  146. return com
  147.  
  148.  
  149. def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2):
  150.  
  151. GF = ztf.constant(pdg['GF'])
  152. alpha_ew = ztf.constant(pdg['alpha_ew'])
  153. Vtb = ztf.constant(pdg['Vtb'])
  154. Vts = ztf.constant(pdg['Vts'])
  155. C10eff = ztf.constant(pdg['C10eff'])
  156.  
  157. mmu = ztf.constant(pdg['muon_M'])
  158. mb = ztf.constant(pdg['bquark_M'])
  159. ms = ztf.constant(pdg['squark_M'])
  160. mK = ztf.constant(pdg['Ks_M'])
  161. mB = ztf.constant(pdg['Bplus_M'])
  162.  
  163. q2 = tf.pow(q, 2)
  164.  
  165. #Some helperfunctions
  166.  
  167. beta = 1. - 4. * mmu**2. / q2
  168.  
  169. kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.)
  170.  
  171. #prefactor in front of whole bracket
  172.  
  173. prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.)
  174.  
  175. #left term in bracket
  176.  
  177. bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2)
  178.  
  179. #middle term in bracket
  180.  
  181. _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.)
  182.  
  183. _under = q2 * mB**2.
  184.  
  185. bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2)
  186. #Note sqrt(q2) comes from derivation as we use q2 and plot q
  187.  
  188. return prefactor1 * (bracket_left + bracket_middle) * 2 * q
  189.  
  190. def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2):
  191. q2 = tf.pow(q, 2)
  192.  
  193. GF = ztf.constant(pdg['GF'])
  194. alpha_ew = ztf.constant(pdg['alpha_ew'])
  195. Vtb = ztf.constant(pdg['Vtb'])
  196. Vts = ztf.constant(pdg['Vts'])
  197. C7eff = ztf.constant(pdg['C7eff'])
  198.  
  199. mmu = ztf.constant(pdg['muon_M'])
  200. mb = ztf.constant(pdg['bquark_M'])
  201. ms = ztf.constant(pdg['squark_M'])
  202. mK = ztf.constant(pdg['Ks_M'])
  203. mB = ztf.constant(pdg['Bplus_M'])
  204.  
  205. #Some helperfunctions
  206.  
  207. beta = 1. - 4. * mmu**2. / q2
  208.  
  209. kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2)
  210. #prefactor in front of whole bracket
  211.  
  212. prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.)
  213.  
  214. #right term in bracket
  215.  
  216. prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta)
  217.  
  218. abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2)
  219.  
  220. bracket_right = prefactor2 * abs_bracket
  221.  
  222. #Note sqrt(q2) comes from derivation as we use q2 and plot q
  223.  
  224. return prefactor1 * bracket_right * 2 * q
  225.  
  226. def c9eff(q, funcs):
  227.  
  228. C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff']))
  229.  
  230. c9 = C9eff_nr + funcs
  231.  
  232. return c9
  233.  
  234.  
  235. # In[4]:
  236.  
  237.  
  238. def G(y):
  239. def inner_rect_bracket(q):
  240. return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi)))
  241. def inner_right(q):
  242. return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q))))
  243. big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y))
  244. return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket
  245.  
  246. def h_S(m, q):
  247. return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2)))
  248.  
  249. def h_P(m, q):
  250. return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q)
  251.  
  252. def two_p_ccbar(mD, m_D_bar, m_D_star, q):
  253. #Load constants
  254. nu_D_bar = ztf.to_complex(pdg["nu_D_bar"])
  255. nu_D = ztf.to_complex(pdg["nu_D"])
  256. nu_D_star = ztf.to_complex(pdg["nu_D_star"])
  257. phase_D_bar = ztf.to_complex(pdg["phase_D_bar"])
  258. phase_D = ztf.to_complex(pdg["phase_D"])
  259. phase_D_star = ztf.to_complex(pdg["phase_D_star"])
  260. #Calculation
  261. left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q)
  262. right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q)
  263. right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q)
  264.  
  265. return left_part + right_part_D + right_part_D_star
  266.  
  267.  
  268. # ## Build pdf
  269.  
  270. # In[5]:
  271.  
  272.  
  273. class total_pdf_cut(zfit.pdf.ZPDF):
  274. _N_OBS = 1 # dimension, can be omitted
  275. _PARAMS = ['b0_0', 'b0_1', 'b0_2',
  276. 'bplus_0', 'bplus_1', 'bplus_2',
  277. 'bT_0', 'bT_1', 'bT_2',
  278. 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width',
  279. 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width',
  280. 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width',
  281. 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width',
  282. 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width',
  283. 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width',
  284. 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width',
  285. 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width',
  286. 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width',
  287. 'Dbar_mass', 'Dbar_scale', 'Dbar_phase',
  288. 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass',
  289. 'tau_mass', 'C_tt']
  290. # the name of the parameters
  291.  
  292. def _unnormalized_pdf(self, x):
  293. x = x.unstack_x()
  294. b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']]
  295. bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']]
  296. bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']]
  297. def rho_res(q):
  298. return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'],
  299. phase = self.params['rho_phase'], width = self.params['rho_width'])
  300. def omega_res(q):
  301. return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'],
  302. phase = self.params['omega_phase'], width = self.params['omega_width'])
  303. def phi_res(q):
  304. return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'],
  305. phase = self.params['phi_phase'], width = self.params['phi_width'])
  306.  
  307. def jpsi_res(q):
  308. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'],
  309. scale = self.params['jpsi_scale'],
  310. phase = self.params['jpsi_phase'],
  311. width = self.params['jpsi_width'])
  312. def psi2s_res(q):
  313. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'],
  314. scale = self.params['psi2s_scale'],
  315. phase = self.params['psi2s_phase'],
  316. width = self.params['psi2s_width'])
  317. def p3770_res(q):
  318. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'],
  319. scale = self.params['p3770_scale'],
  320. phase = self.params['p3770_phase'],
  321. width = self.params['p3770_width'])
  322. def p4040_res(q):
  323. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'],
  324. scale = self.params['p4040_scale'],
  325. phase = self.params['p4040_phase'],
  326. width = self.params['p4040_width'])
  327. def p4160_res(q):
  328. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'],
  329. scale = self.params['p4160_scale'],
  330. phase = self.params['p4160_phase'],
  331. width = self.params['p4160_width'])
  332. def p4415_res(q):
  333. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'],
  334. scale = self.params['p4415_scale'],
  335. phase = self.params['p4415_phase'],
  336. width = self.params['p4415_width'])
  337. def P2_D(q):
  338. Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q))
  339. DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q)))
  340. return Dbar_contrib + DDstar_contrib
  341. def ttau_cusp(q):
  342. return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q)))
  343.  
  344. funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x)
  345.  
  346. vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)
  347.  
  348. axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)
  349.  
  350. tot = vec_f + axiv_nr
  351. #Cut out jpsi and psi2s
  352. tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot)
  353. tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot)
  354. return tot
  355. class total_pdf_full(zfit.pdf.ZPDF):
  356. _N_OBS = 1 # dimension, can be omitted
  357. _PARAMS = ['b0_0', 'b0_1', 'b0_2',
  358. 'bplus_0', 'bplus_1', 'bplus_2',
  359. 'bT_0', 'bT_1', 'bT_2',
  360. 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width',
  361. 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width',
  362. 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width',
  363. 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width',
  364. 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width',
  365. 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width',
  366. 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width',
  367. 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width',
  368. 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width',
  369. 'Dbar_mass', 'Dbar_scale', 'Dbar_phase',
  370. 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass',
  371. 'tau_mass', 'C_tt']
  372. # the name of the parameters
  373.  
  374. def _unnormalized_pdf(self, x):
  375. x = x.unstack_x()
  376. b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']]
  377. bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']]
  378. bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']]
  379. def rho_res(q):
  380. return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'],
  381. phase = self.params['rho_phase'], width = self.params['rho_width'])
  382. def omega_res(q):
  383. return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'],
  384. phase = self.params['omega_phase'], width = self.params['omega_width'])
  385. def phi_res(q):
  386. return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'],
  387. phase = self.params['phi_phase'], width = self.params['phi_width'])
  388.  
  389. def jpsi_res(q):
  390. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'],
  391. scale = self.params['jpsi_scale'],
  392. phase = self.params['jpsi_phase'],
  393. width = self.params['jpsi_width'])
  394. def psi2s_res(q):
  395. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'],
  396. scale = self.params['psi2s_scale'],
  397. phase = self.params['psi2s_phase'],
  398. width = self.params['psi2s_width'])
  399. def p3770_res(q):
  400. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'],
  401. scale = self.params['p3770_scale'],
  402. phase = self.params['p3770_phase'],
  403. width = self.params['p3770_width'])
  404. def p4040_res(q):
  405. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'],
  406. scale = self.params['p4040_scale'],
  407. phase = self.params['p4040_phase'],
  408. width = self.params['p4040_width'])
  409. def p4160_res(q):
  410. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'],
  411. scale = self.params['p4160_scale'],
  412. phase = self.params['p4160_phase'],
  413. width = self.params['p4160_width'])
  414. def p4415_res(q):
  415. return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'],
  416. scale = self.params['p4415_scale'],
  417. phase = self.params['p4415_phase'],
  418. width = self.params['p4415_width'])
  419. def P2_D(q):
  420. Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q))
  421. DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q)))
  422. return Dbar_contrib + DDstar_contrib
  423. def ttau_cusp(q):
  424. return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q)))
  425.  
  426. funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x)
  427.  
  428. vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)
  429.  
  430. axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)
  431.  
  432. tot = vec_f + axiv_nr
  433. #Cut out jpsi and psi2s
  434. # tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot)
  435. # tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot)
  436. return tot
  437.  
  438.  
  439. # ## Setup parameters
  440.  
  441. # In[6]:
  442.  
  443.  
  444. # formfactors
  445.  
  446. b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0)
  447. b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0)
  448. b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0)
  449.  
  450. bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0)
  451. bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0)
  452. bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0)
  453.  
  454. bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0)
  455. bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0)
  456. bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0)
  457.  
  458.  
  459. #rho
  460.  
  461. rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"]
  462.  
  463. rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width)
  464. rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False)
  465. rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  466. rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale))
  467.  
  468. #omega
  469.  
  470. omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"]
  471.  
  472. omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False)
  473. omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False)
  474. omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  475. omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale))
  476.  
  477.  
  478. #phi
  479.  
  480. phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"]
  481.  
  482. phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False)
  483. phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False)
  484. phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  485. phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale))
  486.  
  487. #jpsi
  488.  
  489. jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"]
  490.  
  491. jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False)
  492. jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False)
  493. jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  494. jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale))
  495.  
  496. #psi2s
  497.  
  498. psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"]
  499.  
  500. psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False)
  501. psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False)
  502. psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  503. psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale))
  504.  
  505. #psi(3770)
  506.  
  507. p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"]
  508.  
  509. p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False)
  510. p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False)
  511. p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  512. p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale))
  513.  
  514. #psi(4040)
  515.  
  516. p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"]
  517.  
  518. p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False)
  519. p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False)
  520. p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  521. p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale))
  522.  
  523. #psi(4160)
  524.  
  525. p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"]
  526.  
  527. p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False)
  528. p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False)
  529. p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  530. p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale))
  531.  
  532. #psi(4415)
  533.  
  534. p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"]
  535.  
  536. p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False)
  537. p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False)
  538. p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)
  539. p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale))
  540.  
  541.  
  542. # ## Dynamic generation of 2 particle contribution
  543.  
  544. # In[7]:
  545.  
  546.  
  547. m_c = 1300
  548.  
  549. Dbar_phase = 0.0
  550. DDstar_phase = 0.0
  551. Dstar_mass = pdg['Dst_M']
  552. Dbar_mass = pdg['D0_M']
  553. D_mass = pdg['D0_M']
  554.  
  555. Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)
  556. Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False)
  557. Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False)
  558. DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False)
  559. Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False)
  560. D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False)
  561. DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False)
  562.  
  563.  
  564. # ## Tau parameters
  565.  
  566. # In[8]:
  567.  
  568.  
  569. tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False)
  570. Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5)
  571.  
  572.  
  573. # ## Load data
  574.  
  575. # In[9]:
  576.  
  577.  
  578. x_min = 2*pdg['muon_M']
  579. x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1)
  580.  
  581. # # Full spectrum
  582.  
  583. obs_toy = zfit.Space('q', limits = (x_min, x_max))
  584.  
  585. # Jpsi and Psi2s cut out
  586.  
  587. obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.))
  588. obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.))
  589. obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max))
  590.  
  591. obs_fit = obs1 + obs2 + obs3
  592.  
  593. # with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file:
  594. # part_set = pkl.load(input_file)
  595.  
  596. # x_part = part_set['x_part']
  597.  
  598. # x_part = x_part.astype('float64')
  599.  
  600. # data = zfit.data.Data.from_numpy(array=x_part, obs=obs)
  601.  
  602.  
  603. # ## Setup pdf
  604.  
  605. # In[10]:
  606.  
  607.  
  608. total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w,
  609. psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w,
  610. p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w,
  611. p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w,
  612. p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w,
  613. p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w,
  614. rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w,
  615. omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w,
  616. phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w,
  617. Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m,
  618. Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p,
  619. tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2,
  620. bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2,
  621. bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2)
  622.  
  623. total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w,
  624. psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w,
  625. p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w,
  626. p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w,
  627. p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w,
  628. p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w,
  629. rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w,
  630. omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w,
  631. phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w,
  632. Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m,
  633. Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p,
  634. tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2,
  635. bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2,
  636. bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2)
  637. # print(total_pdf.obs)
  638.  
  639. # print(calcs_test)
  640.  
  641. # for param in total_f.get_dependents():
  642. # print(zfit.run(param))
  643.  
  644.  
  645. # In[11]:
  646.  
  647.  
  648. total_f_fit.normalization(obs_toy)
  649.  
  650.  
  651. # ## Test if graphs actually work and compute values
  652.  
  653. # In[12]:
  654.  
  655.  
  656. # def total_test_tf(xq):
  657.  
  658. # def jpsi_res(q):
  659. # return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w)
  660.  
  661. # def psi2s_res(q):
  662. # return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w)
  663.  
  664. # def cusp(q):
  665. # return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s)
  666.  
  667. # funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq)
  668.  
  669. # vec_f = vec(xq, funcs)
  670.  
  671. # axiv_nr = axiv_nonres(xq)
  672.  
  673. # tot = vec_f + axiv_nr
  674. # return tot
  675.  
  676. # def jpsi_res(q):
  677. # return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w)
  678.  
  679. # calcs = zfit.run(total_test_tf(x_part))
  680.  
  681. test_q = np.linspace(x_min, x_max, int(2e6))
  682.  
  683. probs = total_f_fit.pdf(test_q, norm_range=False)
  684.  
  685. calcs_test = zfit.run(probs)
  686. # res_y = zfit.run(jpsi_res(test_q))
  687. # b0 = [b0_0, b0_1, b0_2]
  688. # bplus = [bplus_0, bplus_1, bplus_2]
  689. # bT = [bT_0, bT_1, bT_2]
  690. # f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT)))
  691. # fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT)))
  692. # fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT)))
  693.  
  694.  
  695. # In[13]:
  696.  
  697.  
  698. plt.clf()
  699. # plt.plot(x_part, calcs, '.')
  700. plt.plot(test_q, calcs_test, label = 'pdf')
  701. # plt.plot(test_q, f0_y, label = '0')
  702. # plt.plot(test_q, fT_y, label = 'T')
  703. # plt.plot(test_q, fplus_y, label = '+')
  704. # plt.plot(test_q, res_y, label = 'res')
  705. plt.legend()
  706. plt.ylim(0.0, 1.5e-6)
  707. # plt.yscale('log')
  708. # plt.xlim(770, 785)
  709. plt.savefig('test.png')
  710. # print(jpsi_width)
  711.  
  712.  
  713. # In[14]:
  714.  
  715.  
  716.  
  717.  
  718. # probs = mixture.prob(test_q)
  719. # probs_np = zfit.run(probs)
  720. # probs_np *= np.max(calcs_test) / np.max(probs_np)
  721. # plt.figure()
  722. # plt.semilogy(test_q, probs_np,label="importance sampling")
  723. # plt.semilogy(test_q, calcs_test, label = 'pdf')
  724.  
  725.  
  726. # In[15]:
  727.  
  728.  
  729. # 0.213/(0.00133+0.213+0.015)
  730.  
  731.  
  732. # ## Adjust scaling of different parts
  733.  
  734. # In[16]:
  735.  
  736.  
  737. total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None)
  738. # inte = total_f.integrate(limits = (950., 1050.), norm_range=False)
  739. # inte_fl = zfit.run(inte)
  740. # print(inte_fl/4500)
  741. # print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"])
  742.  
  743.  
  744. # In[17]:
  745.  
  746.  
  747. # # print("jpsi:", inte_fl)
  748. # # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl))
  749. # # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl))
  750.  
  751. # # print("psi2s:", inte_fl)
  752. # # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl))
  753. # # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl))
  754.  
  755. # name = "phi"
  756.  
  757. # print(name+":", inte_fl)
  758. # print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl))
  759. # print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl))
  760.  
  761.  
  762. # print(x_min)
  763. # print(x_max)
  764. # # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None)
  765. # total_f.update_integration_options(mc_sampler=lambda dim, num_results,
  766. # dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype),
  767. # draws_per_dim=1000000)
  768. # # _ = []
  769.  
  770. # # for i in range(10):
  771.  
  772. # # inte = total_f.integrate(limits = (x_min, x_max))
  773. # # inte_fl = zfit.run(inte)
  774. # # print(inte_fl)
  775. # # _.append(inte_fl)
  776.  
  777. # # print("mean:", np.mean(_))
  778.  
  779. # _ = time.time()
  780.  
  781. # inte = total_f.integrate(limits = (x_min, x_max))
  782. # inte_fl = zfit.run(inte)
  783. # print(inte_fl)
  784. # print("Time taken: {}".format(display_time(int(time.time() - _))))
  785.  
  786. # print(pdg['NR_BR']/pdg['NR_auc']*inte_fl)
  787. # print(0.25**2*4.2/1000)
  788.  
  789.  
  790. # # Sampling
  791. # ## Mixture distribution for sampling
  792.  
  793. # In[18]:
  794.  
  795.  
  796.  
  797. # print(list_of_borders[:9])
  798. # print(list_of_borders[-9:])
  799.  
  800.  
  801. class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin):
  802. def __call__(self, limits, dtype, n_to_produce):
  803. # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32)
  804. low, high = limits.limit1d
  805. low = tf.cast(low, dtype=dtype)
  806. high = tf.cast(high, dtype=dtype)
  807. # uniform = tfd.Uniform(low=low, high=high)
  808. # uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype))
  809. # uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype))
  810.  
  811. # list_of_borders = []
  812. # _p = []
  813. # splits = 10
  814.  
  815. # _ = np.linspace(x_min, x_max, splits)
  816.  
  817. # for i in range(splits):
  818. # list_of_borders.append(tf.constant(_[i], dtype=dtype))
  819. # _p.append(tf.constant(1/splits, dtype=dtype))
  820. # mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]),
  821. # components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)],
  822. # high=list_of_borders[-(splits-1):]))
  823. mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype),
  824. tf.constant(0.93, dtype=dtype),
  825. tf.constant(0.05, dtype=dtype),
  826. tf.constant(0.065, dtype=dtype),
  827. tf.constant(0.04, dtype=dtype),
  828. tf.constant(0.05, dtype=dtype)]),
  829. components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype),
  830. tf.constant(3090, dtype=dtype),
  831. tf.constant(3681, dtype=dtype),
  832. tf.constant(3070, dtype=dtype),
  833. tf.constant(1000, dtype=dtype),
  834. tf.constant(3660, dtype=dtype)],
  835. high=[tf.constant(x_max, dtype=dtype),
  836. tf.constant(3102, dtype=dtype),
  837. tf.constant(3691, dtype=dtype),
  838. tf.constant(3110, dtype=dtype),
  839. tf.constant(1040, dtype=dtype),
  840. tf.constant(3710, dtype=dtype)]))
  841. # dtype = tf.float64
  842. # mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype),
  843. # tf.constant(0.90, dtype=dtype),
  844. # tf.constant(0.02, dtype=dtype),
  845. # tf.constant(0.07, dtype=dtype),
  846. # tf.constant(0.02, dtype=dtype)]),
  847. # components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype),
  848. # tf.constant(3089, dtype=dtype),
  849. # tf.constant(3103, dtype=dtype),
  850. # tf.constant(3681, dtype=dtype),
  851. # tf.constant(3691, dtype=dtype)],
  852. # high=[tf.constant(3089, dtype=dtype),
  853. # tf.constant(3103, dtype=dtype),
  854. # tf.constant(3681, dtype=dtype),
  855. # tf.constant(3691, dtype=dtype),
  856. # tf.constant(x_max, dtype=dtype)]))
  857. # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype))
  858. # sample = tf.random.uniform((n_to_produce, 1), dtype=dtype)
  859. sample = mixture.sample((n_to_produce, 1))
  860. # sample = tf.random.uniform((n_to_produce, 1), dtype=dtype)
  861. weights = mixture.prob(sample)[:,0]
  862. # weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,))
  863. # sample = tf.expand_dims(sample, axis=-1)
  864. # print(sample, weights)
  865. # weights = tf.ones(shape=(n_to_produce,), dtype=dtype)
  866. weights_max = None
  867. thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype)
  868. return sample, thresholds, weights, weights_max, n_to_produce
  869.  
  870.  
  871. # In[19]:
  872.  
  873.  
  874. # total_f._sample_and_weights = UniformSampleAndWeights
  875.  
  876.  
  877. # In[20]:
  878.  
  879.  
  880. # 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min)
  881.  
  882.  
  883. # In[21]:
  884.  
  885.  
  886. # zfit.settings.set_verbosity(10)
  887.  
  888.  
  889. # In[22]:
  890.  
  891.  
  892. # # zfit.run.numeric_checks = False
  893.  
  894. # nr_of_toys = 1
  895. # nevents = int(pdg["number_of_decays"])
  896. # nevents = pdg["number_of_decays"]
  897. # event_stack = 1000000
  898. # # zfit.settings.set_verbosity(10)
  899. # calls = int(nevents/event_stack + 1)
  900.  
  901. # total_samp = []
  902.  
  903. # start = time.time()
  904.  
  905. # sampler = total_f.create_sampler(n=event_stack)
  906.  
  907. # for toy in range(nr_of_toys):
  908. # dirName = 'data/zfit_toys/toy_{0}'.format(toy)
  909. # if not os.path.exists(dirName):
  910. # os.mkdir(dirName)
  911. # print("Directory " , dirName , " Created ")
  912.  
  913. # for call in range(calls):
  914.  
  915. # sampler.resample(n=event_stack)
  916. # s = sampler.unstack_x()
  917. # sam = zfit.run(s)
  918. # # clear_output(wait=True)
  919.  
  920. # c = call + 1
  921. # print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys))
  922. # print("Time taken: {}".format(display_time(int(time.time() - start))))
  923. # print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c)))))
  924.  
  925. # with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f:
  926. # pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL)
  927.  
  928.  
  929. # In[23]:
  930.  
  931.  
  932. # with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file:
  933. # sam = pkl.load(input_file)
  934. # print(sam[:10])
  935.  
  936. # with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file:
  937. # sam2 = pkl.load(input_file)
  938. # print(sam2[:10])
  939.  
  940. # print(np.sum(sam-sam2))
  941.  
  942.  
  943. # In[24]:
  944.  
  945.  
  946. # print("Time to generate full toy: {} s".format(int(time.time()-start)))
  947.  
  948. # total_samp = []
  949.  
  950. # for call in range(calls):
  951. # with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file:
  952. # sam = pkl.load(input_file)
  953. # total_samp = np.append(total_samp, sam)
  954.  
  955. # total_samp = total_samp.astype('float64')
  956.  
  957. # data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs)
  958.  
  959. # data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs)
  960.  
  961. # print(total_samp[:nevents].shape)
  962.  
  963.  
  964. # In[25]:
  965.  
  966.  
  967. # plt.clf()
  968.  
  969. # bins = int((x_max-x_min)/7)
  970.  
  971. # # calcs = zfit.run(total_test_tf(samp))
  972. # print(total_samp[:nevents].shape)
  973.  
  974. # plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data')
  975. # # plt.plot(test_q, calcs_test*nevents , label = 'pdf')
  976.  
  977. # # plt.plot(sam, calcs, '.')
  978. # # plt.plot(test_q, calcs_test)
  979. # # plt.yscale('log')
  980. # plt.ylim(0, 200)
  981. # # plt.xlim(3080, 3110)
  982.  
  983. # plt.legend()
  984.  
  985. # plt.savefig('test2.png')
  986.  
  987.  
  988. # In[26]:
  989.  
  990.  
  991. # sampler = total_f.create_sampler(n=nevents)
  992. # nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max))
  993.  
  994. # # for param in pdf.get_dependents():
  995. # # param.set_value(initial_value)
  996.  
  997. # sampler.resample(n=nevents)
  998.  
  999. # # Randomise initial values
  1000. # # for param in pdf.get_dependents():
  1001. # # param.set_value(random value here)
  1002.  
  1003. # # Minimise the NLL
  1004. # minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10)
  1005. # minimum = minimizer.minimize(nll)
  1006.  
  1007.  
  1008. # In[27]:
  1009.  
  1010.  
  1011. # jpsi_width
  1012.  
  1013.  
  1014. # In[28]:
  1015.  
  1016.  
  1017. # plt.hist(sample, weights=1 / prob(sample))
  1018.  
  1019.  
  1020. # # Fitting
  1021.  
  1022. # In[29]:
  1023.  
  1024.  
  1025. # start = time.time()
  1026.  
  1027. # for param in total_f.get_dependents():
  1028. # param.randomize()
  1029. # # for param in total_f.get_dependents():
  1030. # # print(zfit.run(param))
  1031. # nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max))
  1032.  
  1033. # minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5)
  1034. # # minimizer._use_tfgrad = False
  1035. # result = minimizer.minimize(nll)
  1036.  
  1037. # # param_errors = result.error()
  1038.  
  1039. # # for var, errors in param_errors.items():
  1040. # # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower']))
  1041.  
  1042. # print("Function minimum:", result.fmin)
  1043. # # print("Results:", result.params)
  1044. # print("Hesse errors:", result.hesse())
  1045.  
  1046.  
  1047. # In[30]:
  1048.  
  1049.  
  1050. # print("Time taken for fitting: {}".format(display_time(int(time.time()-start))))
  1051.  
  1052. # # probs = total_f.pdf(test_q)
  1053.  
  1054. # calcs_test = zfit.run(probs)
  1055. # res_y = zfit.run(jpsi_res(test_q))
  1056.  
  1057.  
  1058. # In[31]:
  1059.  
  1060.  
  1061. # plt.clf()
  1062. # # plt.plot(x_part, calcs, '.')
  1063. # plt.plot(test_q, calcs_test, label = 'pdf')
  1064. # # plt.plot(test_q, res_y, label = 'res')
  1065. # plt.legend()
  1066. # plt.ylim(0.0, 10e-6)
  1067. # # plt.yscale('log')
  1068. # # plt.xlim(3080, 3110)
  1069. # plt.savefig('test3.png')
  1070. # # print(jpsi_width)
  1071.  
  1072.  
  1073. # In[32]:
  1074.  
  1075.  
  1076. # _tot = 4.37e-7+6.02e-5+4.97e-6
  1077. # _probs = []
  1078. # _probs.append(6.02e-5/_tot)
  1079. # _probs.append(4.97e-6/_tot)
  1080. # _probs.append(4.37e-7/_tot)
  1081. # print(_probs)
  1082.  
  1083.  
  1084. # In[33]:
  1085.  
  1086.  
  1087. # dtype = 'float64'
  1088. # # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype))
  1089. # mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype),
  1090. # tf.constant(0.917, dtype=dtype),
  1091. # tf.constant(0.076, dtype=dtype)]),
  1092. # components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype),
  1093. # tf.constant(3080, dtype=dtype),
  1094. # tf.constant(3670, dtype=dtype)],
  1095. # high=[tf.constant(x_max, dtype=dtype),
  1096. # tf.constant(3112, dtype=dtype),
  1097. # tf.constant(3702, dtype=dtype)]))
  1098. # # for i in range(10):
  1099. # # print(zfit.run(mixture.prob(mixture.sample((10, 1)))))
  1100.  
  1101.  
  1102. # In[34]:
  1103.  
  1104.  
  1105. # print((zfit.run(jpsi_p)%(2*np.pi))/np.pi)
  1106. # print((zfit.run(psi2s_p)%(2*np.pi))/np.pi)
  1107.  
  1108.  
  1109. # In[35]:
  1110.  
  1111.  
  1112. # def jpsi_res(q):
  1113. # return resonance(q, _mass = jpsi_mass, scale = jpsi_scale,
  1114. # phase = jpsi_phase, width = jpsi_width)
  1115.  
  1116. # def psi2s_res(q):
  1117. # return resonance(q, _mass = psi2s_mass, scale = psi2s_scale,
  1118. # phase = psi2s_phase, width = psi2s_width)
  1119. # def p3770_res(q):
  1120. # return resonance(q, _mass = p3770_mass, scale = p3770_scale,
  1121. # phase = p3770_phase, width = p3770_width)
  1122. # def p4040_res(q):
  1123. # return resonance(q, _mass = p4040_mass, scale = p4040_scale,
  1124. # phase = p4040_phase, width = p4040_width)
  1125. # def p4160_res(q):
  1126. # return resonance(q, _mass = p4160_mass, scale = p4160_scale,
  1127. # phase = p4160_phase, width = p4160_width)
  1128. # def p4415_res(q):
  1129. # return resonance(q, _mass = p4415_mass, scale = p4415_scale,
  1130. # phase = p4415_phase, width = p4415_width)
  1131.  
  1132.  
  1133. # In[36]:
  1134.  
  1135.  
  1136. # 0.15**2*4.2/1000
  1137. # result.hesse()
  1138.  
  1139.  
  1140. # ## Constraints
  1141.  
  1142. # In[37]:
  1143.  
  1144.  
  1145. # 1. Constraint - Real part of sum of Psi contrib and D contribs
  1146.  
  1147. sum_list = []
  1148.  
  1149. sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3))))
  1150. sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3))))
  1151. sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3))))
  1152. sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3))))
  1153. sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3))))
  1154. sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3))))
  1155. sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2)))))
  1156. sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2))))
  1157.  
  1158. sum_ru_1 = ztf.to_complex(ztf.constant(0.0))
  1159.  
  1160. for part in sum_list:
  1161. sum_ru_1 += part
  1162.  
  1163. sum_1 = tf.math.real(sum_ru_1)
  1164. # constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8),
  1165. # sigma = ztf.constant(2.2*10**-8))
  1166.  
  1167. constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.)
  1168.  
  1169. # 2. Constraint - Abs. of sum of Psi contribs and D contribs
  1170.  
  1171. sum_2 = tf.abs(sum_ru_1)
  1172. constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.)
  1173.  
  1174. # 3. Constraint - Maximum eta of D contribs
  1175.  
  1176. constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.)
  1177.  
  1178. constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.)
  1179.  
  1180. # 4. Constraint - Formfactor multivariant gaussian covariance fplus
  1181.  
  1182. Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)],
  1183. [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)],
  1184. [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)],
  1185. [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)],
  1186. [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)],
  1187. [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)],
  1188. [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)],
  1189. [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)],
  1190. [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]]
  1191.  
  1192. def triGauss(val1,val2,val3,m = Cov_matrix):
  1193.  
  1194. mean1 = ztf.constant(0.466)
  1195. mean2 = ztf.constant(-0.885)
  1196. mean3 = ztf.constant(-0.213)
  1197. sigma1 = ztf.constant(0.014)
  1198. sigma2 = ztf.constant(0.128)
  1199. sigma3 = ztf.constant(0.548)
  1200. x1 = (val1-mean1)/sigma1
  1201. x2 = (val2-mean2)/sigma2
  1202. x3 = (val3-mean3)/sigma3
  1203. rho12 = m[0][1]
  1204. rho13 = m[0][2]
  1205. rho23 = m[1][2]
  1206. w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13))
  1207. d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1)
  1208. fcn = -w/d
  1209. chisq = -2*fcn
  1210. return chisq
  1211.  
  1212. constraint4 = triGauss(bplus_0, bplus_1, bplus_2)
  1213.  
  1214. # mean1 = ztf.constant(0.466)
  1215. # mean2 = ztf.constant(-0.885)
  1216. # mean3 = ztf.constant(-0.213)
  1217. # sigma1 = ztf.constant(0.014)
  1218. # sigma2 = ztf.constant(0.128)
  1219. # sigma3 = ztf.constant(0.548)
  1220. # constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.)
  1221. # constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.)
  1222. # constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.)
  1223.  
  1224. # 5. Constraint - Abs. of sum of light contribs
  1225.  
  1226. sum_list_5 = []
  1227.  
  1228. sum_list_5.append(rho_s*rho_w/rho_m)
  1229. sum_list_5.append(omega_s*omega_w/omega_m)
  1230. sum_list_5.append(phi_s*phi_w/phi_m)
  1231.  
  1232.  
  1233. sum_ru_5 = ztf.constant(0.0)
  1234.  
  1235. for part in sum_list_5:
  1236. sum_ru_5 += part
  1237.  
  1238. constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.)
  1239.  
  1240. # 6. Constraint on phases of Jpsi and Psi2s for cut out fit
  1241.  
  1242.  
  1243. # constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]),
  1244. # sigma = ztf.constant(jpsi_phase))
  1245. # constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]),
  1246. # sigma = ztf.constant(psi2s_phase))
  1247.  
  1248. constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.)
  1249. constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.)
  1250.  
  1251. # 7. Constraint on Ctt with higher limits
  1252.  
  1253. constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.)
  1254.  
  1255. constraint7dtype = tf.float64
  1256.  
  1257. # zfit.run(constraint6_0)
  1258.  
  1259. # ztf.convert_to_tensor(constraint6_0)
  1260.  
  1261. #List of all constraints
  1262.  
  1263. constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2,
  1264. constraint6_0, constraint6_1]#, constraint7]
  1265.  
  1266.  
  1267. # ## Reset params
  1268.  
  1269. # In[38]:
  1270.  
  1271.  
  1272. def reset_param_values():
  1273. jpsi_m.set_value(jpsi_mass)
  1274. jpsi_s.set_value(jpsi_scale)
  1275. jpsi_p.set_value(jpsi_phase)
  1276. jpsi_w.set_value(jpsi_width)
  1277. psi2s_m.set_value(psi2s_mass)
  1278. psi2s_s.set_value(psi2s_scale)
  1279. psi2s_p.set_value(psi2s_phase)
  1280. psi2s_w.set_value(psi2s_width)
  1281. p3770_m.set_value(p3770_mass)
  1282. p3770_s.set_value(p3770_scale)
  1283. p3770_p.set_value(p3770_phase)
  1284. p3770_w.set_value(p3770_width)
  1285. p4040_m.set_value(p4040_mass)
  1286. p4040_s.set_value(p4040_scale)
  1287. p4040_p.set_value(p4040_phase)
  1288. p4040_w.set_value(p4040_width)
  1289. p4160_m.set_value(p4160_mass)
  1290. p4160_s.set_value(p4160_scale)
  1291. p4160_p.set_value(p4160_phase)
  1292. p4160_w.set_value(p4160_width)
  1293. p4415_m.set_value(p4415_mass)
  1294. p4415_s.set_value(p4415_scale)
  1295. p4415_p.set_value(p4415_phase)
  1296. p4415_w.set_value(p4415_width)
  1297. rho_m.set_value(rho_mass)
  1298. rho_s.set_value(rho_scale)
  1299. rho_p.set_value(rho_phase)
  1300. rho_w.set_value(rho_width)
  1301. omega_m.set_value(omega_mass)
  1302. omega_s.set_value(omega_scale)
  1303. omega_p.set_value(omega_phase)
  1304. omega_w.set_value(omega_width)
  1305. phi_m.set_value(phi_mass)
  1306. phi_s.set_value(phi_scale)
  1307. phi_p.set_value(phi_phase)
  1308. phi_w.set_value(phi_width)
  1309. Dstar_m.set_value(Dstar_mass)
  1310. DDstar_s.set_value(0.0)
  1311. DDstar_p.set_value(0.0)
  1312. D_m.set_value(D_mass)
  1313. Dbar_m.set_value(Dbar_mass)
  1314. Dbar_s.set_value(0.0)
  1315. Dbar_p.set_value(0.0)
  1316. tau_m.set_value(pdg['tau_M'])
  1317. Ctt.set_value(0.0)
  1318. b0_0.set_value(0.292)
  1319. b0_1.set_value(0.281)
  1320. b0_2.set_value(0.150)
  1321. bplus_0.set_value(0.466)
  1322. bplus_1.set_value(-0.885)
  1323. bplus_2.set_value(-0.213)
  1324. bT_0.set_value(0.460)
  1325. bT_1.set_value(-1.089)
  1326. bT_2.set_value(-1.114)
  1327.  
  1328.  
  1329. # # Analysis
  1330.  
  1331. # In[39]:
  1332.  
  1333.  
  1334. # # zfit.run.numeric_checks = False
  1335.  
  1336. # fitting_range = 'cut'
  1337. # total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7
  1338. # cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR
  1339.  
  1340. # Ctt_list = []
  1341. # Ctt_error_list = []
  1342.  
  1343. # nr_of_toys = 1
  1344. # if fitting_range == 'cut':
  1345. # nevents = int(pdg["number_of_decays"]*cut_BR)
  1346. # else:
  1347. # nevents = int(pdg["number_of_decays"])
  1348. # # nevents = pdg["number_of_decays"]
  1349. # event_stack = 1000000
  1350. # # nevents *= 41
  1351. # # zfit.settings.set_verbosity(10)
  1352. # calls = int(nevents/event_stack + 1)
  1353.  
  1354. # total_samp = []
  1355.  
  1356. # start = time.time()
  1357.  
  1358. # sampler = total_f.create_sampler(n=event_stack)
  1359.  
  1360. # for toy in range(nr_of_toys):
  1361. # ### Generate data
  1362. # # clear_output(wait=True)
  1363. # print("Toy {}: Generating data...".format(toy))
  1364. # dirName = 'data/zfit_toys/toy_{0}'.format(toy)
  1365. # if not os.path.exists(dirName):
  1366. # os.mkdir(dirName)
  1367. # print("Directory " , dirName , " Created ")
  1368. # reset_param_values()
  1369. # if fitting_range == 'cut':
  1370. # sampler.resample(n=nevents)
  1371. # s = sampler.unstack_x()
  1372. # sam = zfit.run(s)
  1373. # calls = 0
  1374. # c = 1
  1375. # else:
  1376. # for call in range(calls):
  1377.  
  1378. # sampler.resample(n=event_stack)
  1379. # s = sampler.unstack_x()
  1380. # sam = zfit.run(s)
  1381.  
  1382. # c = call + 1
  1383.  
  1384. # with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f:
  1385. # pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL)
  1386. # print("Toy {}: Data generation finished".format(toy))
  1387. # ### Load data
  1388. # print("Toy {}: Loading data...".format(toy))
  1389. # if fitting_range == 'cut':
  1390. # total_samp = sam
  1391. # else:
  1392. # for call in range(calls):
  1393. # with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file:
  1394. # sam = pkl.load(input_file)
  1395. # total_samp = np.append(total_samp, sam)
  1396.  
  1397. # total_samp = total_samp.astype('float64')
  1398. # if fitting_range == 'full':
  1399.  
  1400. # data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs)
  1401. # print("Toy {}: Loading data finished".format(toy))
  1402.  
  1403. # ### Fit data
  1404.  
  1405. # print("Toy {}: Fitting pdf...".format(toy))
  1406.  
  1407. # for param in total_f.get_dependents():
  1408. # param.randomize()
  1409.  
  1410. # nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints)
  1411.  
  1412. # minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5)
  1413. # # minimizer._use_tfgrad = False
  1414. # result = minimizer.minimize(nll)
  1415.  
  1416. # print("Toy {}: Fitting finished".format(toy))
  1417.  
  1418. # print("Function minimum:", result.fmin)
  1419. # print("Hesse errors:", result.hesse())
  1420.  
  1421. # params = result.params
  1422. # Ctt_list.append(params[Ctt]['value'])
  1423. # Ctt_error_list.append(params[Ctt]['minuit_hesse']['error'])
  1424.  
  1425. # #plotting the result
  1426.  
  1427. # plotdirName = 'data/plots'.format(toy)
  1428.  
  1429. # if not os.path.exists(plotdirName):
  1430. # os.mkdir(plotdirName)
  1431. # # print("Directory " , dirName , " Created ")
  1432. # probs = total_f.pdf(test_q, norm_range=False)
  1433. # calcs_test = zfit.run(probs)
  1434. # plt.clf()
  1435. # plt.plot(test_q, calcs_test, label = 'pdf')
  1436. # plt.legend()
  1437. # plt.ylim(0.0, 6e-6)
  1438. # plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy))
  1439.  
  1440. # print("Toy {0}/{1}".format(toy+1, nr_of_toys))
  1441. # print("Time taken: {}".format(display_time(int(time.time() - start))))
  1442. # print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c)))))
  1443. # if fitting_range == 'cut':
  1444. # _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.)))
  1445. # tot_sam_1 = total_samp[_1]
  1446. # _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.)))
  1447. # tot_sam_2 = total_samp[_2]
  1448.  
  1449. # _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max))
  1450. # tot_sam_3 = total_samp[_3]
  1451.  
  1452. # tot_sam = np.append(tot_sam_1, tot_sam_2)
  1453. # tot_sam = np.append(tot_sam, tot_sam_3)
  1454. # data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit)
  1455. # print("Toy {}: Loading data finished".format(toy))
  1456. # ### Fit data
  1457.  
  1458. # print("Toy {}: Fitting pdf...".format(toy))
  1459.  
  1460. # for param in total_f_fit.get_dependents():
  1461. # param.randomize()
  1462.  
  1463. # nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints)
  1464.  
  1465. # minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5)
  1466. # # minimizer._use_tfgrad = False
  1467. # result = minimizer.minimize(nll)
  1468.  
  1469. # print("Function minimum:", result.fmin)
  1470. # print("Hesse errors:", result.hesse())
  1471.  
  1472. # params = result.params
  1473. # if result.converged:
  1474. # Ctt_list.append(params[Ctt]['value'])
  1475. # Ctt_error_list.append(params[Ctt]['minuit_hesse']['error'])
  1476.  
  1477. # #plotting the result
  1478.  
  1479. # plotdirName = 'data/plots'.format(toy)
  1480.  
  1481. # if not os.path.exists(plotdirName):
  1482. # os.mkdir(plotdirName)
  1483. # # print("Directory " , dirName , " Created ")
  1484. # plt.clf()
  1485. # plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data')
  1486. # plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy))
  1487.  
  1488. # probs = total_f_fit.pdf(test_q, norm_range=False)
  1489. # calcs_test = zfit.run(probs)
  1490. # plt.clf()
  1491. # plt.plot(test_q, calcs_test, label = 'pdf')
  1492. # plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted')
  1493. # plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted')
  1494. # plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted')
  1495. # plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted')
  1496. # plt.legend()
  1497. # plt.ylim(0.0, 1.5e-6)
  1498. # plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy))
  1499. # print("Toy {0}/{1}".format(toy+1, nr_of_toys))
  1500. # print("Time taken: {}".format(display_time(int(time.time() - start))))
  1501. # print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1)))))
  1502.  
  1503.  
  1504. # In[40]:
  1505.  
  1506.  
  1507. # with open("data/results/Ctt_list.pkl", "wb") as f:
  1508. # pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL)
  1509. # with open("data/results/Ctt_error_list.pkl", "wb") as f:
  1510. # pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL)
  1511.  
  1512.  
  1513. # In[41]:
  1514.  
  1515.  
  1516. # print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys))
  1517. # print('Mean Ctt value = {}'.format(np.mean(Ctt_list)))
  1518. # print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list)))
  1519. # print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000))
  1520.  
  1521.  
  1522. # In[42]:
  1523.  
  1524.  
  1525. # plt.hist(tot_sam, bins = int((x_max-x_min)/7.))
  1526.  
  1527. # plt.show()
  1528.  
  1529. # # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.)))
  1530.  
  1531. # tot_sam.shape
  1532.  
  1533.  
  1534. # In[43]:
  1535.  
  1536.  
  1537. # Ctt.floating = False
  1538.  
  1539.  
  1540. # In[44]:
  1541.  
  1542.  
  1543. # zfit.run(nll.value())
  1544.  
  1545.  
  1546. # In[45]:
  1547.  
  1548.  
  1549. # result.fmin
  1550.  
  1551.  
  1552. # In[46]:
  1553.  
  1554.  
  1555. # BR_steps = np.linspace(0.0, 1e-3, 11)
  1556.  
  1557.  
  1558. # # CLS Code
  1559.  
  1560. # In[48]:
  1561.  
  1562.  
  1563. # zfit.run.numeric_checks = False
  1564.  
  1565. load = False
  1566.  
  1567. bo5 = True
  1568.  
  1569. bo5_set = 5
  1570.  
  1571. fitting_range = 'cut'
  1572. total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7
  1573. cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR
  1574.  
  1575. Ctt_list = []
  1576. Ctt_error_list = []
  1577.  
  1578. nr_of_toys = 1
  1579. nevents = int(pdg["number_of_decays"]*cut_BR)
  1580. # nevents = pdg["number_of_decays"]
  1581. event_stack = 1000000
  1582. # nevents *= 41
  1583. # zfit.settings.set_verbosity(10)
  1584.  
  1585. mi = 0.0
  1586. ma = 1e-3
  1587. ste = 11
  1588.  
  1589. BR_steps = np.linspace(mi, ma, ste)
  1590.  
  1591. Ctt_steps = np.sqrt(BR_steps/4.2*1000)
  1592.  
  1593. total_samp = []
  1594.  
  1595. start = time.time()
  1596.  
  1597. Nll_list = []
  1598.  
  1599. sampler = total_f.create_sampler(n=nevents)
  1600.  
  1601. __ = 0
  1602.  
  1603. #-----------------------------------------------------
  1604.  
  1605. if not load:
  1606.  
  1607. for Ctt_step in Ctt_steps:
  1608. __ += 1
  1609. newset = True
  1610. for floaty in [True, False]:
  1611.  
  1612. Ctt.floating = floaty
  1613.  
  1614. Nll_list.append([])
  1615. if bo5:
  1616. if __ < 6:
  1617. while len(Nll_list[-1])/bo5_set < nr_of_toys:
  1618.  
  1619. print('Step: {0}/{1}'.format(__, ste))
  1620.  
  1621. print('Current Ctt: {0}'.format(Ctt_step))
  1622. print('Ctt floating: {0}'.format(floaty))
  1623.  
  1624. print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set))
  1625.  
  1626. reset_param_values()
  1627.  
  1628. if floaty:
  1629. Ctt.set_value(Ctt_step)
  1630. else:
  1631. Ctt.set_value(0.0)
  1632.  
  1633. if newset:
  1634. sampler.resample(n=nevents)
  1635. s = sampler.unstack_x()
  1636. total_samp = zfit.run(s)
  1637. calls = 0
  1638. c = 1
  1639. newset = False
  1640.  
  1641.  
  1642. data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit)
  1643.  
  1644. ### Fit data
  1645.  
  1646. for param in total_f_fit.get_dependents():
  1647. param.randomize()
  1648.  
  1649. nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints)
  1650.  
  1651. minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5)
  1652. # minimizer._use_tfgrad = False
  1653. result = minimizer.minimize(nll)
  1654.  
  1655. # print("Function minimum:", result.fmin)
  1656. # print("Hesse errors:", result.hesse())
  1657.  
  1658. params = result.params
  1659.  
  1660. if result.converged:
  1661. Nll_list[-1].append(result.fmin)
  1662.  
  1663. else:
  1664.  
  1665. while len(Nll_list[-1]) < nr_of_toys:
  1666.  
  1667. print('Step: {0}/{1}'.format(__, ste))
  1668.  
  1669. print('Current Ctt: {0}'.format(Ctt_step))
  1670. print('Ctt floating: {0}'.format(floaty))
  1671.  
  1672. print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys))
  1673.  
  1674. reset_param_values()
  1675.  
  1676. if floaty:
  1677. Ctt.set_value(Ctt_step)
  1678. else:
  1679. Ctt.set_value(0.0)
  1680.  
  1681. if floaty:
  1682. sampler.resample(n=nevents)
  1683. s = sampler.unstack_x()
  1684. total_samp = zfit.run(s)
  1685. calls = 0
  1686. c = 1
  1687.  
  1688.  
  1689. data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit)
  1690.  
  1691. ### Fit data
  1692.  
  1693. for param in total_f_fit.get_dependents():
  1694. param.randomize()
  1695.  
  1696. nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints)
  1697.  
  1698. minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5)
  1699. # minimizer._use_tfgrad = False
  1700. result = minimizer.minimize(nll)
  1701.  
  1702. # print("Function minimum:", result.fmin)
  1703. # print("Hesse errors:", result.hesse())
  1704.  
  1705. params = result.params
  1706.  
  1707. if result.converged:
  1708. Nll_list[-1].append(result.fmin)
  1709.  
  1710. _t = int(time.time()-start)
  1711.  
  1712. print('Time Taken: {}'.format(display_time(int(_t))))
  1713.  
  1714. print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1))))))
  1715.  
  1716.  
  1717. # In[49]:
  1718.  
  1719.  
  1720. if load:
  1721. Nll_list = []
  1722. CLs_values = []
  1723.  
  1724. _dir = 'data/CLs/finished/f1d1'
  1725. jobs = os.listdir(_dir)
  1726. for s in range(ste):
  1727. CLs_values.append([])
  1728. for s in range(2*ste):
  1729. Nll_list.append([])
  1730. for job in jobs:
  1731. if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)):
  1732. print(job)
  1733. continue
  1734. with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file:
  1735. _Nll_list = pkl.load(input_file)
  1736. if bo5:
  1737. for s in range(2*ste):
  1738. Nll_list[s].append(np.min(_Nll_list[s]))
  1739. else:
  1740. for s in range(2*ste):
  1741. Nll_list[s].extend(_Nll_list[s])
  1742. with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file:
  1743. _CLs_values = pkl.load(input_file)
  1744. for s in range(ste):
  1745. CLs_values[s].extend(_CLs_values[s])
  1746. print(np.shape(Nll_list))
  1747.  
  1748.  
  1749. # In[50]:
  1750.  
  1751.  
  1752. dirName = 'data/CLs'
  1753.  
  1754. # if bo5 and not load:
  1755. # for s in range(2*ste):
  1756. # Nll_list[s] = [np.min(Nll_list[s])]
  1757.  
  1758. # if bo5:
  1759. # CLs_values= []
  1760. # for i in range(int(len(Nll_list)/2)):
  1761. # CLs_values.append([])
  1762. # for j in range(len(Nll_list[0])):
  1763. # CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])
  1764.  
  1765.  
  1766. if not load:
  1767. if not os.path.exists(dirName):
  1768. os.mkdir(dirName)
  1769. print("Directory " , dirName , " Created ")
  1770.  
  1771. with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f:
  1772. pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL)
  1773. # CLs_values = []
  1774. # for i in range(int(len(Nll_list)/2)):
  1775. # CLs_values.append([])
  1776. # for j in range(nr_of_toys):
  1777. # CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])
  1778.  
  1779. # with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f:
  1780. # pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL)
  1781.  
  1782.  
  1783. # In[51]:
  1784.  
  1785.  
  1786. # print(CLs_values)
  1787. # print(Nll_list)
  1788.  
  1789.  
  1790. # ## Plot
  1791.  
  1792. # In[56]:
  1793.  
  1794.  
  1795. # l = []
  1796.  
  1797. # if not os.path.exists('data/CLs/plots'):
  1798. # os.mkdir('data/CLs/plots')
  1799. # print("Directory " , 'data/CLs/plots' , " Created ")
  1800.  
  1801. # for i in range(len(CLs_values)):
  1802. # plt.clf()
  1803. # plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i]))
  1804. # plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0')
  1805. # plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating')
  1806. # plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted')
  1807. # plt.legend()
  1808. # plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i]))
  1809. # l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0]))
  1810.  
  1811.  
  1812. # In[57]:
  1813.  
  1814.  
  1815. # for s in range(len(l)):
  1816. # print('BR: {:.4f}'.format(BR_steps[s]))
  1817. # print(2*l[s]/len(CLs_values[0]))
  1818. # print()
  1819.  
  1820.  
  1821. # In[ ]:
  1822.  
  1823.  
  1824. # print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10]))
  1825.  
  1826.  
  1827. # In[ ]:
  1828.  
  1829.  
  1830.  
  1831.